Africa's Talking Node.js API wrapper
The wrapper provides convenient access to the Africa's Talking API from applications written in server-side JavaScript.
Documentation
Take a look at the API docs here.
Install
You can install the package by running:
$ npm install --save africastalking
Usage
The package needs to be configured with your app username and API key (which you can get from the dashboard).
In addition to the API key, there are a few other options you can set including the response format.
const options = {
apiKey: 'YOUR_API_KEY',
username: 'YOUR_USERNAME',
};
const AfricasTalking = require('africastalking')(options);
const Server = require('africastalking/server');
const server = new Server(options);
server.start({
privateKeyFile: fs.readFileSync('path/to/pk'),
certChainFile: fs.readFileSync('path/to/cert/chain'),
rootCertFile: fs.readFileSync('path/to/root/cert'),
port: 35897,
insecure: false,
});
SMS
const sms = AfricasTalking.SMS;
sms.send(opts)
.then(success)
.catch(error);
-
send(options)
: Send a message. options
contains:
to
: A single recipient or an array of recipients. REQUIRED
from
: Shortcode or alphanumeric ID that is registered with Africa's Talking account.message
: SMS content. REQUIRED
-
sendBulk(options)
: Send bulk SMS. In addition to paramaters of send()
, we would have:
enqueue
: "[...] would like deliver as many messages to the API before waiting for an Ack from the Telcos."
-
sendPremium(options)
: Send premium SMS. In addition to paramaters of send()
, we would have:
keyword
: Value is a premium keyword REQUIRED
linkId
: "[...] We forward the linkId
to your application when the user send a message to your service" REQUIRED
retryDurationInHours
: "It specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber"
You can register a callback URL with us and we will forward any messages that are sent to your account the moment they arrive.
Read more
If you have subscription products on your premium SMS short codes, you will need to configure a callback URL that we will invoke to notify you when users subscribe or unsubscribe from your products.
Read more
Processing USSD requests using our API is very easy once your account is set up. In particular, you will need to:
- Register a service code with us.
- Register a URL that we can call whenever we get a request from a client coming into our system.
Once you register your callback URL, any requests that we receive belonging to you will trigger a callback that sends the request data to that page using HTTP POST.
Read more.
If you are using connect-like frameworks (express), you could use the middleware AfricasTalking.USSD(handler)
:
handler(params, next)
: Process USSD request and call next()
when done.
params
: contains the following user data sent by Africa's Talking servers: sessionId
, serviceCode
, phoneNumber
and text
.next(args)
: args
must contain the following:
response
: Text to display on user's device. REQUIRED
endSession
: Boolean to decide whether to END session or to CONtinue it. REQUIRED
app.post('/natoil-ussd', new AfricasTalking.USSD((params, next) => {
const endSession = false;
const message = '';
const session = sessions.get(params.sessionId);
const user = db.getUserByPhone(params.phoneNumber);
if (params.text === '') {
message = "Welcome to Nat Oil \n";
message += "1: For account info \n";
message += "2: For lost gas cylinder";
} else if (params.text === '1') {
message = user.getInfo();
endSession = true;
} else if (params.text === '2') {
message = "Enter 1 for recovery \n";
message += "Enter 2 for lost and found";
endSession = true;
} else {
message = "Invalid option";
endSession = true;
}
next({
response: message,
endSession: endSession
});
}));
Voice
const voice = AfricasTalking.VOICE;
- Helpers that will construct proper
xml
to send back to Africa's Taking API when it comes POST
ing. Read more
Say
, Play
, GetDigits
, Dial
, Record
, Enqueue
, Dequeue
, Conference
, Redirect
, Reject
- Initiate a call
- Fetch call queue
- Upload Media File
- Remember to send back an HTTP 200.
voice.call({
callFrom: '+2547XXXXXXXX',
callTo: from_
})
.then(function(s) {
console.log(s);
})
.catch(function(error) {
console.log(error);
});
voice.getNumQueuedCalls({
phoneNumbers: destinationNumber
})
.then(function(s) {
console.log(s);
})
.catch(function(error) {
console.log(error);
});
voice.uploadMediaFile({
phoneNumber: destinationNumber,
url: 'http://myOnlineMediaFile.mp3'
})
.then(function(s) {
console.log(s);
})
.catch(function(error) {
console.log(error);
});
check issue #15
const airtime = AfricasTalking.AIRTIME;
airtime.send(options)
: Send airtime options
is an object which contains the key:
recipients
: Contains an array of objects containing the following keys
phoneNumber
: Recipient of airtimeamount
: Amount sent >= 10 && <= 10K
with currency e.g KES 100
airtime.send(options)
.then(success)
.catch(error);
Checkout Token
AfricasTalking.createCheckoutToken(phoneNumber)
: Create a checkout token. Accepts the phoneNumber
to create a token for.
AfricasTalking.fetchAccount()
.then(success)
.catch(error);
fetchAccount()
: Fetch account info; i.e. balance
Payments
Mobile Consumer To Business (C2B) functionality allows your application to receive payments that are initiated by a mobile subscriber.
This is typically achieved by disctributing a PayBill or BuyGoods number (and optionally an account number) that clients can use to make payments from their mobile devices.
Read more
const payments = AfricasTalking.PAYMENTS;
payments.mobileCheckout(opts)
.then(success)
.catch(error);
payments.mobileB2C(opts)
.then(success)
.catch(error);
payments.mobileB2B(opts)
.then(success)
.catch(error);
payments.bankCheckout(opts)
.then(success)
.catch(error);
bankCheckout(opts)
Initiate a banck checkout charge request. More info
-
productName
: Payment Product as setup on your account. REQUIRED
-
bankAccount
: Bank account to be charged. REQUIRED
-
currencyCode
: 3-digit ISO format currency code (only NGN
is supported). REQUIRED
-
amount
: Payment amount. REQUIRED
-
narration
: A short description of the transaction REQUIRED
-
metadata
: Some optional data to associate with transaction.
payments.validateBankCheckout(opts)
.then(success)
.catch(error);
validateBankCheckout(opts)
initiate a bank OTP validation request. More info
transactionId
: The transaction that your application wants to validate. REQUIRED
otp
: One Time Password that the bank sent to the client. REQUIRED
payments.bankTransfer(opts)
.then(success)
.catch(error);
bankTransfer(opts)
initiate a bank transfer request. More info
productName
: Payment Product as setup on your account. REQUIRED
recipients
: A list of recipients. Each recipient has:
bankAccount
: Bank account to be charged:
accountName
: The name of the bank account.accountNumber
: The account number REQUIRED
bankCode
: A 6-Digit Integer Code for the bank that we allocate; See payments.BANK.*
for supported banks. REQUIRED
currencyCode
: 3-digit ISO format currency code (only NGN
is supported). REQUIRED
amount
: Payment amount. REQUIRED
narration
: A short description of the transaction REQUIRED
metadata
: Some optional data to associate with transaction.
payments.cardCheckout(opts)
.then(success)
.catch(error);
cardCheckout(opts)
initiate a card checkout charge request. More info
productName
: Payment Product as setup on your account. REQUIRED
checkoutToken
: 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, the paymentCard
data should NOT be populated.paymentCard
: Payment Card to be charged:
number
: The payment card number. REQUIRED
cvvNumber
: The 3 or 4 digit Card Verification Value. REQUIRED
expiryMonth
: The expiration month on the card (e.g 8
) REQUIRED
authToken
: The card's ATM PIN. REQUIRED
countryCode
: The 2-Digit countryCode where the card was issued (only NG
is supported). REQUIRED
currencyCode
: 3-digit ISO format currency code (only NGN
is supported). REQUIRED
amount
: Payment amount. REQUIRED
narration
: A short description of the transaction REQUIRED
metadata
: Some optional data to associate with transaction.
payments.validateCardCheckout(opts)
.then(success)
.catch(error);
validateCardCheckout(opts)
initiate a card OTP validation request. More info
transactionId
: The transaction that your application wants to validate. REQUIRED
otp
: One Time Password that the card issuer sent to the client. REQUIRED
Development
Run all tests:
$ npm install
$ npm test
or on Windows...
$ npm install
$ npm run test-windows
Issues
If you find a bug, please file an issue on our issue tracker on GitHub.