AfricasTalking SDK
Provides convenient access to the Africa's Talking API from applications written in ruby.
Documentation
Take a look at the API docs here.
Installation
Add this line to your application's Gemfile:
gem "africastalking-ruby"
And then execute:
$ bundle
Usage
The SDK needs to be instantiated using your username and API key, which you can get from the dashboard.
You can use this SDK for either production or sandbox apps. For sandbox, the app username is ALWAYS
sandbox
require "AfricasTalking"
username = 'YOUR_USERNAME' # use 'sandbox' for development in the test environment
apiKey = 'YOUR_API_KEY' # use your sandbox app API key for development in the test environment
@AT=AfricasTalking::Initialize.new(username, apiKey)
You can now make API calls using the @AT object
Token
token = @AT.token
Create authentication Token
token.createCheckoutToken
optionsphoneNumber: The phone number you want to create a subscription for
Create Checkout Token
token.generateAuthToken phoneNumber
Airtime
Send airtime to phone numbers
airtime = @AT.airtime
airtime.send
optionsrecipients: Contains an hash of arrays containing the following keysphoneNumber: Recipient of airtimeREQUIREDcurrency:3-digit ISO format currency code .REQUIREDamount: Amount sent>= 10 && <= 10Kwith currency e.gKES 100REQUIRED
Sms
sms = @AT.sms
Send Sms
sms.send
optionsmessage: SMS content.REQUIREDto: A single recipient or a comma separated string of recipients.REQUIREDfrom: Shortcode or alphanumeric ID that is registered with Africa's Talking account.OPTIONALenqueue: Set totrueif you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.OPTIONALbulkSMSMode: This parameter will be used by the Mobile Service Provider to determine who gets billed for a message sent using a Mobile-Terminated ShortCode. The default value is 1 (which means that the sender (The AfricasTalking account being used ) gets charged).OPTIONALretryDurationInHours: t specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber.OPTIONAL
Send Premium SMS
sms.sendPremium
optionsmessage: SMS content.REQUIREDkeyword: The keyword to be used for a premium service.REQUIREDlinkId: This parameter is used for premium services to send OnDemand messages. We forward the linkId to your application when the user send a message to your service..REQUIREDto: A single recipient or a comma separated string of recipients.REQUIREDfrom: Shortcode or alphanumeric ID that is registered with Africa's Talking account.OPTIONALenqueue: Set totrueif you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.OPTIONALbulkSMSMode: This parameter will be used by the Mobile Service Provider to determine who gets billed for a message sent using a Mobile-Terminated ShortCode. The default value is 1 (which means that the sender (The AfricasTalking account being used ) gets charged).OPTIONALretryDurationInHours: t specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber.OPTIONAL
Fetch Messsages
sms.fetchMessages
optionslastReceivedId: This is the id of the message that you last processed. The default is 0OPTIONAL
Create subscription
sms.createSubcription
optionsshortCode: This is a premium short code mapped to your account.REQUIREDkeyword: Value is a premium keyword under the above short code and mapped to your account.REQUIREDphoneNumber: The phoneNumber to be subscribedREQUIREDcheckoutToken: This is a token used to validate the subscription requestREQUIRED
Fetch Subscription
sms.fetchSubscriptions
optionsshortCode: This is a premium short code mapped to your account.REQUIREDkeyword: Premium keyword under the above short code and mapped to your account.REQUIREDlastReceivedId: ID of the subscription you believe to be your last. Defaults to0
Delete Subscription
sms.deleteSubscriptions
optionsshortCode: This is a premium short code mapped to your account.REQUIREDkeyword: Premium keyword under the above short code and mapped to your account.REQUIREDphoneNumber: PhoneNumber to be unsubscribedREQUIRED
Voice
voice = @AT.voice
Making a call
voice.call
optionsto: A single recipient or an array of recipients.REQUIRED- array of recipients contains ['2XXXXXXXX', '2XXXXXXXX']
from: Phone number that is registered with Africa's Talking account.REQUIREDclientRequestId: String sent to your Events Callback URL that can be used to tag the call.OPTIONAL
Fetch queued calls
voice.fetchQueuedCalls
optionsphoneNumber: is phone number mapped to your AfricasTalking account.REQUIRED
Upload media file
voice.uploadMediaFile
optionsurl: The url of the file to upload. Don't forget to start with http://REQUIREDphoneNumber: is phone number mapped to your AfricasTalking account.REQUIRED
Account
account = @AT.account
Fetch User data
account.fetchUserData
Payments
payments = @AT.payments
Credit card checkout
payments.cardCheckoutCharge
optionsproductName: Payment Product as setup on your account.REQUIREDcurrencyCode: 3-digit ISO format currency code (onlyNGNis supported).REQUIREDamount: Payment amount.REQUIREDnarration: A short description of the transactionREQUIREDcheckoutToken: Token that has been generated by our APIs as as result of charging a user's Payment Card in a previous transaction. When using a token, thepaymentCarddata should NOT be populated.OPTIONALpaymentCard: Hash of payment Card to be charged:OPTIONALnumber: The payment card number.REQUIREDcvvNumber: The 3 or 4 digit Card Verification Value.REQUIREDexpiryMonth: The expiration month on the card (e.g8)REQUIREDexpiryYear: The expiration year on the card (e.g2020)REQUIREDauthToken: The card's ATM PIN.REQUIREDcountryCode: The 2-Digit countryCode where the card was issued (onlyNGis supported).REQUIRED
metadata: Some optional data to associate with transaction.OPTIONAL
Validate credit card checkout
payments.cardCheckoutValidate
optionstransactionId: The transaction that your application wants to validate.REQUIREDotp: One Time Password that the card issuer sent to the client.REQUIRED
Initiate bank charge checkout
payments.bankCheckoutCharge
optionsproductName: Payment Product as setup on your account.REQUIREDbankAccount: Hash of bank account to be charged:accountName: The name of the bank account.REQUIREDaccountNumber: The account number.REQUIREDdateOfBirth: Date of birth of the account owner (YYYY-MM-DD). Required for Zenith Bank Nigeria.bankCode: A 6-Digit Integer Code for the bank that we allocate. Supported banks at the moment are:REQUIREDruby payments.class::BANK_CODES['FCMB_NG'] payments.class::BANK_CODES['ZENITH_NG'] payments.class::BANK_CODES['ACCESS_NG'] payments.class::BANK_CODES['PROVIDUS_NG'] payments.class::BANK_CODES['STERLING_NG']
currencyCode: 3-digit ISO format currency code (onlyNGNis supported).REQUIREDamount: Payment amount.REQUIREDnarration: A short description of the transactionREQUIREDmetadata: Some optional data to associate with transactionOPTIONAL
Validate bank checkout
payments.bankCheckoutValidate
optionstransactionId: The transaction that your application wants to validate.REQUIREDotp: One Time Password that the bank sent to the client.REQUIRED
Bank transfer
payments.bankTransfer
optionsproductName: Payment Product as setup on your account.REQUIREDrecipients: A list of recipients. Each recipient has:bankAccount: Bank account to be charged:accountName: The name of the bank account.accountNumber: The account numberREQUIREDbankCode: A 6-Digit Integer Code for the bank that we allocate; Seepayments.class::BANK_CODESfor supported banks.REQUIRED
currencyCode: 3-digit ISO format currency code (onlyNGNis supported).REQUIREDamount: Payment amount.REQUIREDnarration: A short description of the transactionREQUIREDmetadata: Some optional data to associate with transaction.
Mobile Checkout
payments.mobileCheckout
optionsproductName: Your Payment Product.REQUIREDphoneNumber: The customer phone number (in international format; e.g.25471xxxxxxx).REQUIREDcurrencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc.)REQUIREDamount: This is the amount.REQUIREDmetadata: Some optional data to associate with transaction.OPTIONALproviderChannel: This represents the payment channel the payment will be made from. eg paybill number. The payment channel must be mapped to you. The AfricasTalking default provider channel is used if not specified.OPTIONAL
Mobile B2C
payments.mobileB2C
optionsproductName: Your Payment Product.REQUIREDrecipients: A list of up to 10 recipients. Each recipient has:phoneNumber: The payee phone number (in international format; e.g.25471xxxxxxx).REQUIREDcurrencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc.)REQUIREDamount: Payment amount.REQUIREDproviderChannel: This represents the payment channel the payment will be made from. eg paybill number. The payment channel must be mapped to you. The AfricasTalking default provider channel is used if not specified.reason: This field contains a string showing the purpose for the payment. If set, it should be one of the followingSalaryPayment SalaryPaymentWithWithdrawalChargePaid BusinessPayment BusinessPaymentWithWithdrawalChargePaid PromotionPaymentmetadata: Some optional data to associate with transaction.
Mobile B2B
payments.mobileB2B
optionsproductName: Your Payment Product as setup on your account.REQUIREDproviderData: Hash containing Provider details. this include;REQUIREDprovider: String that shows the payment provider that is facilitating this transaction. Supported providers at the moment are:Athena - Please note: This is not available on our production systems MpesatransferType: This contains the payment provider that is facilitating this transaction. Supported providers at the moment are:BusinessBuyGoods BusinessPayBill DisburseFundsToBusiness BusinessToBusinessTransferdestinationChannel: This value contains the name or number of the channel that will receive payment by the provider.REQUIREDdestinationAccount: This value contains the account name used by the business to receive money on the provided destinationChannel.REQUIRED
currencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc.)REQUIREDamount: Payment amount.REQUIREDmetadata: Some optional data to associate with transaction.REQUIRED
Mobile Data
payments.mobileData
optionsproductName: Your Payment Product.REQUIREDrecipients: A list of recipients. Each recipient has:phoneNumber: Customer phone number (in international format).REQUIREDquantity: Mobile data amount.REQUIREDunit: Mobile data unit. Can either beMBorGB.REQUIREDvalidity: How long the mobile data is valid for. Must be one ofDay,WeekandMonth.REQUIREDmetadata: Additional data to associate with the transaction.REQUIRED
Wallet Transfer
payments.walletTransfer
optionsproductName: Your Payment Product as setup on your account.REQUIREDtargetProductCode: Unique code ode of payment product receiving funds on Africa's TalkingREQUIREDcurrencyCode: 3-digit ISO format currency code.REQUIREDamount: Amount to transfer.REQUIREDmetadata: Additional data to associate with the transaction.REQUIRED
Topup Stash
payments.topupStash
optionsproductName: Your Payment Product as setup on your account.REQUIREDcurrencyCode: 3-digit ISO format currency code.REQUIREDamount: Amount to transfer.REQUIREDmetadata: Additonal data to associate with the transaction.REQUIRED
Fetch Product Transactions
payments.fetchProductTransactions
optionsproductName: Your Payment Product as setup on your account.REQUIREDfilters: Filters to use when fetching transactions:pageNumber: Page number to fetch results from. Starts from1.REQUIREDcount: Number of results to fetch.REQUIREDstartDate: Start Date to consider when fetchingendDate: End Date to consider when fetchingcategory: Category to consider when fetchingprovider: Provider to consider when fetchingstatus: Status to consider when fetchingsource: Source to consider when fetchingdestination: Destination to consider when fetchingproviderChannel: Provider to consider when fetching
fetch Wallet Transactions
payments.fetchWalletTransactions
optionsfilters: Filters to use when fetching transactions:pageNumber: Page number to fetch results from. Starts from1.REQUIREDcount: Number of results to fetch.REQUIREDstartDate: Start Date to consider when fetchingendDate: End Date to consider when fetchingcategories: Comma delimited list of categories to consider when fetching
Find Transaction
payments.findTransaction
optionstransactionId: ID of trancation to findREQUIRED
Fetch Wallet Balance
payments.fetchWalletBalance
- Fetch your payment wallet balance
Development
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/AfricasTalkingLtd. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.