africastalking-php
africastalking-php copied to clipboard
Official PHP SDK
Africa's Talking PHP SDK
This SDK provides convenient access to the Africa's Talking API for applications written in PHP.
Documentation
Take a look at the API docs here.
Install
You can install the PHP SDK via composer or by downloading the source
Via Composer
The recommended way to install the SDK is with Composer.
composer require africastalking/africastalking
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
use AfricasTalking\SDK\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 = new AfricasTalking($username, $apiKey);
// Get one of the services
$sms = $AT->sms();
// Use the service
$result = $sms->send([
'to' => '+2XXYYYOOO',
'message' => 'Hello World!'
]);
print_r($result);
See example for more usage examples.
Instantiation
Instantiating the class will give you an object with available methods
$AT = new AfricasTalking($username, $apiKey): Instantiate the class- Get available service
- SMS Service:
$sms = $AT->sms() - Content Service:
$content = $AT->content() - Airtime Service:
$airtime = $AT->airtime() - Payments Service:
$payments = $AT->payments() - Voice Service:
$voice = $AT->voice() - Token Service:
$token = $AT->token() - Application Service:
$application = $AT->application()
- SMS Service:
Application
fetchApplicationData(): Get app information. e.g balance
Airtime
-
send($parameters, $options): Send airtime-
$parameters: associative array with the following keys:
recipients: An array of arrays containing the following keysphoneNumber: Recipient of airtime.REQUIREDcurrencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc).REQUIREDamount: Amount to send.REQUIRED
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
SMS
-
send($options): Send a messagemessage: SMS content.REQUIREDto: An array of phone numbers.REQUIREDfrom: Shortcode or alphanumeric ID that is registered with your Africa's Talking account.enqueue: Set totrueif you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.
-
fetchMessages($options): Fetch your messageslastReceivedId: This is the id of the message you last processed. Defaults to0
The followoing methods have been moved to the content service, but, have been maintained on SMS for backwards compatibility:
sendPremium($options): Send a premium SMS. Calls$content->send($options)createSubscription($options): Create a premium subscription. Calls$content->createSubscription($options)fetchSubscriptions($options): Fetch your premium subscription data. Calls$content->fetchSubscriptions($options)deleteSubscription($options): Delete a phone number from a premium subscription. Calls$content->$deleteSubscription($options)
Content
-
send($options): Send a premium SMSmessage: SMS content.REQUIREDto: An array of phone numbers.REQUIREDfrom: Shortcode that is registered with your Africa's Talking account.REQUIREDkeyword: Your premium product keywordlinkId: "[...] We forward thelinkIdto your application when a user sends a message to your onDemand service"retryDurationInHours: "This specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber"
-
createSubscription($options): Create a premium subscriptionshortCode: Premium short code mapped to your account.REQUIREDkeyword: Premium keyword under the above short code and is also mapped to your account.REQUIREDphoneNumber: PhoneNumber to be subscribedREQUIRED
-
fetchSubscriptions($options): Fetch your premium subscription datashortCode: 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
-
deleteSubscription($options): Delete a phone number from a premium subscriptionshortCode: Premium short code mapped to your account.REQUIREDkeyword: Premium keyword under the above short code and is also mapped to your account.REQUIREDphoneNumber: PhoneNumber to be subscribedREQUIRED
Payments
-
mobileCheckout($parameters, $options): Charge a customers mobile money account-
$parameters: associative array with the following keys:
productName: Payment product on Africa's Talking.REQUIREDproviderChannel: Provider channel to consider when charging.phoneNumber: Customer phone number (in international format).REQUIREDcurrencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc).REQUIREDamount: Amount to charge.REQUIREDmetadata: Additional data to associate with the transaction.REQUIRED
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
mobileB2C($parameters, $options): Send mobile money to customers-
$parameters: associative array with the following keys:
-
productName: Payment product on Africa's Talking.REQUIRED -
recipients: A list of up to 10 recipients. Each recipient has:phoneNumber: Customer phone number (in international format).REQUIREDcurrencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc).REQUIREDamount: Amount to pay.REQUIREDreason: The purpose of the payment. Seepayments::REASON*for supported reasons.REQUIREDmetadata: Additional data to associate with the tranasction.REQUIRED
-
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
mobileB2B($parameters, $options): Send mobile money to businesses e.g banks-
$parameters: associative array with the following keys:
productName: Payment product on Africa's Talking.REQUIREDprovider: Payment provider that is facilitating this transaction. Seepayments::PROVIDER*for supported providers.REQUIREDtransferType: Describes the type of payment being made. Seepayments::TRANSFER_TYPE*for supported transfer types.REQUIREDdestinationChannel: Name or number of the channel that will receive payment by the provider.REQUIREDdestinationAccount: Name used by the business to receive money on the provided destinationChannel.REQUIREDcurrencyCode: 3-digit ISO format currency code (e.gKES,USD,UGXetc).REQUIREDamount: Amount to pay.REQUIREDrequester: PhoneNumber through which KPLC will send tokens when using B2B to buy electricity tokens.metadata: Additional data to associate with the transaction.REQUIRED
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
mobileData($parameters, $options): Send mobile data to customers-
$parameters: associative array with the following keys:
-
productName: Payment product on Africa's Talking.REQUIRED -
recipients: 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 tranasction.REQUIRED
-
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
bankCheckoutCharge($parameters, $options): Charge a customers bank account-
$parameters: associative array with the following keys:
-
productName: Payment product on Africa's Talking.REQUIRED -
bankAccount: Bank account to be charged:accountName: Name of the bank account.REQUIREDaccountNumber: Account number.REQUIREDbankCode: A 6-Digit Integer Code for the bank that we allocate. Seepayments::BANK*for supported banks.REQUIREDdateOfBirth: Date of birth of the account owner (in the formatYYYY-MM-DD). Required for Zenith Bank Nigeria.
-
currencyCode: 3-digit ISO format currency code (onlyNGNis supported at present).REQUIRED -
amount: Amount to charge.REQUIRED -
narration: A short description of the transaction.REQUIRED -
metadata: Additional data to associate with the transaction.REQUIRED
-
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
bankCheckoutValidate($parameters): Validate a bank checkout chargetransactionId: Transaction id returned from a bank charge request.REQUIREDotp: One Time Password provided by the customer you're charging.REQUIRED
-
bankTransfer($parameters, $options): Send money to a bank account-
$parameters: associative array with the following keys:
-
productName: Payment product on Africa's Talking.REQUIRED -
recipients: A list of recipients. Each recipient has:-
bankAccount: Bank account to receive money:accountName: Name of the bank account.REQUIREDaccountNumber: Account number.REQUIREDbankCode: A 6-Digit Integer Code for the bank that we allocate. Seepayments::BANK*for supported banks.REQUIREDdateOfBirth: Date of birth of the account owner (in the formatYYYY-MM-DD). Required for Zenith Bank Nigeria.
-
currencyCode: 3-digit ISO format currency code (onlyNGNis supported at present).REQUIRED -
amount: Amount to pay.REQUIRED -
narration: A short description of the transaction.REQUIRED -
metadata: Additonal data to associate with the transaction.REQUIRED
-
-
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
cardCheckoutCharge($parameters, $options): Charge a customers payment card-
$parameters: associative array with the following keys:
-
productName: Payment product on Africa's Talking.REQUIRED -
paymentCard: Payment card to be charged:number: Payment card number.REQUIREDcvvNumber: 3 or 4 digit card verification Value.REQUIREDexpiryMonth: Expiration month on the card (e.g8).REQUIREDauthToken: Payment card's ATM PIN.REQUIREDcountryCode: 2-Digit countryCode where the card was issued (onlyNGis supported at present).REQUIRED
-
checkoutToken: A token that has been generated by our APIs as as result of charging a customers payment card in a previous transaction. When using acheckoutToken, thepaymentCarddata should NOT be populated. -
currencyCode: 3-digit ISO format currency code (onlyNGNis supported at present).REQUIRED -
amount: Amount to charge.REQUIRED -
narration: A short description of the transaction.REQUIRED -
metadata: Additonal data to associate with the transaction.REQUIRED
-
-
$options: optional associative array with the following keys:
idempotencyKey: Key to use when making idempotent requests
-
-
cardCheckoutValidate($parameters): Validate a card checkout chargetransactionId: Transaction id returned from a card charge request.REQUIREDotp: One Time Password provided by the customer you're charging.REQUIRED
-
walletTransfer($parameters): Move money from one payment product to anotherproductName: Payment product on Africa's Talking.REQUIREDtargetProductCode: Unique code ode of payment product receiving funds on Africa's Talking.REQUIREDcurrencyCode: 3-digit ISO format currency code.REQUIREDamount: Amount to transfer.REQUIREDmetadata: Additional data to associate with the transation.REQUIRED
-
topupStash($parameters): Move money from a payment product to an applications stashproductName: Payment product on Africa's Talking.REQUIREDcurrencyCode: 3-digit ISO format currency code.REQUIREDamount: Amount to transfer.REQUIREDmetadata: Additonal data to associate with the transaction.REQUIRED
-
fetchProductTransactions($parameters): Fetch payment product transactions-
productName: Payment product on Africa's Talking.REQUIRED -
filters: 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 fetching.endDate: End Date to consider when fetching.category: Category to consider when fetching.provider: Provider to consider when fetching.status: Status to consider when fetching.source: Source to consider when fetching.destination: Destination to consider when fetching.providerChannel: Provider channel to consider when fetching.
-
-
fetchWalletTransactions($parameters): Fetch payment wallet transactions-
filters: 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 fetching.endDate: End Date to consider when fetching.categories: Comma delimited list of categories to consider when fetching.
-
-
findTransaction($parameters): Find a particular transactiontransactionId: ID of trancation to find.REQUIRED
-
fetchWalletBalance(): Fetch your payment wallet balance
Voice
-
call($options): Initiate a phone callto: Phone number that you wish to dial (in international format).REQUIREDfrom: Phone number on Africa's Talking (in international format).REQUIRED
-
fetchQueuedCalls($options): Fetch queued calls on a phone numberphoneNumber: Phone number mapped to your Africa's Talking account (in international format).REQUIREDname: Fetch calls for a specific queue.
-
uploadMediaFile($options): Upload a voice media filephoneNumber: phone number mapped to your Africa's Talking account (in international format).REQUIREDurl: The url of the file to upload. Should start withhttp(s)://.REQUIRED
MessageBuilder
Build voice xml when callback URL receives a POST from the voice API. Actions can be chained to create an XML string.
$voiceActions = $voice->messageBuilder();
$xmlresponse = $voiceActions
->getDigits($options)
->say($text)
->record()
->build();
-
say($text): Add aSayaction -
text: Text (in English) that will be read out to the user. -
play($url): Add aPlayactionurl: Public url to an audio file. This file will be played back to user.
-
getDigits($options): Add aGetDigitsactionnumDigits: Number of digits should be gotten from the usertimeout: Timeout (in seconds) for getting digits from a user.finishOnKey: key which will terminate the action of getting digits.callbackUrl: URL to forward the results of the GetDigits action.
-
dial($options): Add aDialactionphoneNumbers: An array of phone numbers (in international format) to call.REQUIREDrecord: Boolean - Whether to record the conversation.sequenntial: Boolean - If many numbers provided forphoneNumbers, determines whether the phone numbers will be dialed one after the other or at the same time.callerId: Africa's Talking number you want to dial out with.ringBackTone: URL location of a media playback you would want the user to listen to when the call has been placed before its picked up.maxDuration: maximum amount of time in seconds a call should take.
-
conference(): Add aConferenceaction -
record($options): Add aRecordactionfinishOnKey: Key which will terminate the action of recording.maxLength: Maximum amount of time in seconds a recording should take.timeout: Timeout (in seconds) for getting a recording from a user.trimSilence: Boolean - Specifies whether you want to remove the initial and final parts of a recording where user was silent.playBeep: Boolean - Specifies whether the API should play a beep when recording starts.callbackUrl: URL to forward the results of the Recording action.
-
enqueue($options): Add anEnqueueactionholdMusic: URL to the file to be played while the user is on hold.name: Name of queue to put call on.
-
deqeue($options): Add aDequeueactonphoneNumber: Phone number mapped to your Africa's Talking account which a user called to join the queue.REQUIREDname: Name of queue you want to dequeue from.
-
reject(): Add aRejectaction -
redirect($url): Add aRedirectactionurl: URL to transfer control of the call to
-
build(): Build the xml after chaining some of the above actions
Token
generateAuthToken(): Generate an auth token to use for authenticating API requests instead of your API key.
Testing the SDK
The SDK uses PHPUnit as the test runner.
To run available tests, from the root of the project run:
# Configure needed fixtures, e.g sandbox api key, Africa's Talking products
cp tests/Fixtures.php.tpl tests/Fixtures.php
# Run tests
phpunit
Issues
If you find a bug, please file an issue on our issue tracker on GitHub.