### Install AfricasTalking Node.js SDK
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Install the package from npm using the command below. This is the first step to integrating Africa's Talking services into your Node.js application.
```bash
npm install --save africastalking
```
--------------------------------
### Application fetchApplicationData
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Get application information, such as balance.
```APIDOC
## Application fetchApplicationData
### Description
Get app information. e.g. balance
### Method
`fetchApplicationData()`
### Endpoint
For more information, please read [https://developers.africastalking.com/docs/application](https://developers.africastalking.com/docs/application)
```
--------------------------------
### Build Voice Call XML Responses - ActionBuilder
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Constructs XML responses for voice call control using a fluent API. Supports various actions like say, play, getDigits, dial, record, enqueue, dequeue, redirect, conference, and reject. Use the `build()` method to get the final XML string.
```javascript
const { ActionBuilder } = client.VOICE
// IVR menu: say prompt, collect digits
const xml = new ActionBuilder()
.say('Welcome to our service. Press 1 for sales, 2 for support.', { voice: 'en-US-Wavenet-A', playBeep: false })
.getDigits(
{ say: { text: 'Enter your choice followed by hash.' } },
{ numDigits: 1, finishOnKey: '#', timeout: 10, callbackUrl: 'https://myapp.com/ivr/handle' }
)
.build()
console.log(xml)
// Welcome......
```
```javascript
// Transfer call to agent
const transferXml = new ActionBuilder()
.say('Connecting you to an agent.')
.dial('+254711000199', { record: true, sequential: false, maxDuration: 3600 })
.build()
```
```javascript
// Record a voicemail
const recordXml = new ActionBuilder()
.say('Please leave a message after the beep.')
.record(
{ say: { text: 'Recording... press hash when done.' } },
{ maxLength: 120, trimSilence: true, callbackUrl: 'https://myapp.com/voicemail', playBeep: true }
)
.build()
```
```javascript
// Handle incoming call with Express (send XML response)
const express = require('express')
const app = express()
app.post('/voice/incoming', (req, res) => {
const xml = new ActionBuilder()
.say('Thank you for calling.')
.conference()
.build()
res.set('Content-Type', 'application/xml')
res.send(xml)
})
```
--------------------------------
### SMS Service - Fetch Subscription
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Fetches premium subscription data based on a provided short code and keyword. Allows fetching data starting from a specific message ID.
```APIDOC
## SMS Service - Fetch Subscription
### Description
Fetch your premium subscription data.
### Method Signature
`sms.fetchSubscription({ shortCode, keyword, lastReceivedId })`
### Parameters
#### Required
- **shortCode** (string) - The premium short code mapped to your account.
- **keyword** (string) - A premium keyword under the above short code and mapped to your account.
#### Optional
- **lastReceivedId** (number) - The ID of the message that you last processed. Defaults to 0.
```
--------------------------------
### SMS Service - Fetch Messages
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Manually retrieves messages that have been received. Allows fetching messages starting from a specific ID.
```APIDOC
## SMS Service - Fetch Messages
### Description
Manually retrieve your messages.
### Method Signature
`sms.fetchMessages({ lastReceivedId })`
### Parameters
#### Optional
- **lastReceivedId** (number) - The ID of the message that you last processed. Defaults to 0.
```
--------------------------------
### Initialize Africa's Talking SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Initialize the SDK with your API credentials for production or sandbox environments. Destructure services for easy access.
```javascript
const AfricasTalking = require('africastalking')
// Production
const client = AfricasTalking({
apiKey: 'YOUR_API_KEY',
username: 'YOUR_USERNAME',
format: 'json' // optional: 'json' (default) or 'xml'
})
// Sandbox (for development/testing)
const sandboxClient = AfricasTalking({
apiKey: 'YOUR_SANDBOX_API_KEY',
username: 'sandbox'
})
// Destructure services
const { SMS, VOICE, AIRTIME, MOBILE_DATA, USSD, TOKEN, INSIGHTS, WHATSAPP, APPLICATION } = client
```
--------------------------------
### Initialize and Send SMS with Node.js SDK
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Configure the SDK with your API key and username, then initialize the SMS service to send messages. Ensure you use 'sandbox' for username and a sandbox API key for testing.
```javascript
const credentials = {
apiKey: 'YOUR_API_KEY', // use your sandbox app API key for development in the test environment
username: 'YOUR_USERNAME', // use 'sandbox' for development in the test environment
};
const AfricasTalking = require('africastalking')(credentials);
// Initialize a service e.g. SMS
const sms = AfricasTalking.SMS
// Use the service
const options = {
to: ['+254711XXXYYY', '+254733YYYZZZ'],
message: "I'm a lumberjack and its ok, I work all night and sleep all day"
}
// Send message and capture the response or error
sms.send(options)
.then( response => {
console.log(response);
})
.catch( error => {
console.log(error);
});
```
--------------------------------
### Get Number of Queued Calls - Voice Service
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Retrieves the count of calls waiting in the queue for a specific virtual phone number. Ensure the phone number is correctly formatted.
```javascript
client.VOICE.getNumQueuedCalls({ phoneNumbers: '+254711000100' })
.then(response => {
console.log(response)
// { entries: [{ phoneNumber: '+254711000100', queueName: 'default', numCalls: 3 }] }
})
.catch(err => console.error(err))
```
--------------------------------
### Fetch Application Data with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Use `APPLICATION.fetchApplicationData` to retrieve your Africa's Talking application metadata, including your current wallet balance. An alias `fetchAccount` is available for backward compatibility.
```javascript
client.APPLICATION.fetchApplicationData()
.then(data => {
console.log(data)
// { userData: { balance: 'KES 1250.50' } }
})
.catch(err => console.error(err.message))
```
```javascript
// Alias for backward compatibility
client.APPLICATION.fetchAccount()
.then(data => console.log(data.userData.balance))
```
--------------------------------
### Application Service - fetchApplicationData
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Fetches account metadata for your Africa's Talking application, including the current wallet balance.
```APIDOC
## Application Service — `APPLICATION.fetchApplicationData()`
### Description
Fetches account metadata for your Africa's Talking application, including the current wallet balance.
### Method
`fetchApplicationData`
### Parameters
None
### Request Example
```javascript
client.APPLICATION.fetchApplicationData()
.then(data => {
console.log(data)
// { userData: { balance: 'KES 1250.50' } }
})
.catch(err => console.error(err.message))
```
### Response
- `userData` (object): Contains user-specific data.
- `balance` (string): The current wallet balance of the application.
```
```APIDOC
## Application Service — `APPLICATION.fetchAccount()`
### Description
Alias for `fetchApplicationData`. Fetches account metadata for your Africa's Talking application, including the current wallet balance.
### Method
`fetchAccount`
### Parameters
None
### Request Example
```javascript
client.APPLICATION.fetchAccount()
.then(data => console.log(data.userData.balance))
```
### Response
- `userData` (object): Contains user-specific data.
- `balance` (string): The current wallet balance of the application.
```
--------------------------------
### Initiate Voice Call with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Make outbound voice calls from your Africa's Talking virtual number to specified destinations. Both `callFrom` and `callTo` are mandatory. An optional `clientRequestId` can be used for callback tagging.
```javascript
client.VOICE.call({
callFrom: '+254711000100', // your AT virtual number
callTo: '+254711000111,+254722000222', // comma-separated string or array
clientRequestId: 'session-xyz-001' // optional tagging for your callback
})
.then(response => {
console.log(response)
// { entries: [{ phoneNumber: '+254711000111', status: 'Queued' }, ...] }
})
.catch(err => console.error(err))
```
--------------------------------
### WhatsApp createTemplate
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Create a template for your future WhatsApp messages.
```APIDOC
## WhatsApp createTemplate
### Description
Create a template for your future messages.
### Method
`createTemplate({ component, waNumber, name, language, category })`
### Parameters
#### Path Parameters
- **waNumber** (string) - Required - The WhatsApp phone number that will be used to send the messages associated with the template.
- **name** (string) - Required - The name of the template. This must be unique.
- **language** (string) - Required - The language code([ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)) associated with the template.
- **category** (string) - Required - The category associated with the template. Must be one of `MARKETING`, `UTILITY` and `AUTHENTICATION`.
- **components** (object) - Required - An object containing the template values. It can contain header, body, footer, and buttons.
#### Components (header)
- **type** (string) - always `HEADER`
- **format** (string) - Required - One of `LOCATION`, `TEXT`, `DOCUMENT`, `IMAGE` and `VIDEO`
- **text** (string) - Optional - The text to be contained in the header. Can be used with variables, e.g 'Hello {{1}}' where `{{1}}` will be replaced by a value sent.
- **example** (object) - Optional
- **header_handle** (string) - Text used for replacement when header is of type media(i.e. anything but `TEXT`)
- **header_text** (string) - Text used for replacement when header type is `TEXT`
#### Components (body)
- **type** (string) - always `BODY`
- **text** (string) - Required - The text to be contained in the body. Can be used with variables, e.g 'Hello {{1}} there {{2}}' where `{{1}}` and `{{2}}` will be replaced by values sent.
- **example** (object) - Optional
- **body_text** (array) - A list of texts to use for replacement. e.g. `['Juma', 'Champ']`
#### Components (footer)
- **type** (string) - always `FOOTER`
- **text** (string) - Required - The footer text.
#### Components (buttons)
- **type** (string) - always `BUTTONS`
- **buttons** (array) - Required - A list of buttons to be sent in the template. Each can have the following, depending on the type:
- **type** (string) - Required - One of `PHONE_NUMBER`, `URL`, `FLOW`, `COPY_CODE` and `QUICK_REPLY`
- **phone_number** (string) - Only needed for phone number type
- **url** (string) - Only needed for url type
- **text** (string) - Required - Button text
- **example** (string or array) - An example string(Or list of string for type `URL`)
- **flow_id**, **flow_action**(navigate or data_exchange) and **navigate_screen** - Only needed for type `FLOW`
```
--------------------------------
### WhatsApp Service - createTemplate
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Creates a reusable WhatsApp message template with header, body, footer, and button components, submitted for approval under a registered WhatsApp number.
```APIDOC
## WhatsApp Service — `WHATSAPP.createTemplate(payload)`
### Description
Creates a reusable WhatsApp message template with header, body, footer, and button components, submitted for approval under a registered WhatsApp number.
### Method
`createTemplate`
### Parameters
- `payload` (object) - Required - An object containing template details.
- `waNumber` (string) - Required - Your registered Africa's Talking WhatsApp number.
- `name` (string) - Required - The name of the template.
- `language` (string) - Required - The language code for the template (e.g., 'en').
- `category` (string) - Required - The category of the template (e.g., 'UTILITY', 'MARKETING', 'AUTHENTICATION').
- `components` (object) - Required - The components of the template.
- `header` (object) - Optional - The header component.
- `type` (string) - Required - Must be 'HEADER'.
- `format` (string) - Required - The format of the header ('TEXT', 'IMAGE', 'VIDEO').
- `text` (string) - Required if `format` is 'TEXT' - The header text, can include placeholders like {{1}}.
- `example` (object) - Optional - Example values for header placeholders.
- `body` (object) - Required - The body component.
- `type` (string) - Required - Must be 'BODY'.
- `text` (string) - Required - The body text, can include placeholders like {{1}}, {{2}}.
- `example` (object) - Optional - Example values for body placeholders.
- `footer` (object) - Optional - The footer component.
- `type` (string) - Required - Must be 'FOOTER'.
- `text` (string) - Required - The footer text.
- `buttons` (object) - Optional - The buttons component.
- `type` (string) - Required - Must be 'BUTTONS'.
- `buttons` (array) - Required - An array of button objects.
- Each button object can be of type 'QUICK_REPLY' or 'URL'.
- `type` (string) - Required - 'QUICK_REPLY' or 'URL'.
- `text` (string) - Required - The button text.
- `url` (string) - Required if `type` is 'URL' - The URL for the button.
- `example` (array) - Optional - Example values for URL placeholders.
### Request Example
```javascript
client.WHATSAPP.createTemplate({
waNumber: '254700000000',
name: 'order_confirmation',
language: 'en',
category: 'UTILITY',
components: {
header: {
type: 'HEADER',
format: 'TEXT',
text: 'Order {{1}} Update',
example: { header_text: 'Order #12345 Update' }
},
body: {
type: 'BODY',
text: 'Hi {{1}}, your order worth {{2}} will arrive {{3}}.',
example: { body_text: ['John', 'KES 1200', 'tomorrow'] }
},
footer: {
type: 'FOOTER',
text: 'Thank you for shopping with us!'
},
buttons: {
type: 'BUTTONS',
buttons: [
{ type: 'QUICK_REPLY', text: 'Track Order' },
{ type: 'URL', url: 'https://mystore.com/orders/{{1}}', text: 'View Details', example: ['12345'] }
]
}
}
})
```
### Response
- The response object contains details about the created template and its approval status.
```
--------------------------------
### VOICE.ActionBuilder
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
A fluent builder for constructing Voice XML responses, supporting various actions like say, play, getDigits, dial, and more.
```APIDOC
## VOICE.ActionBuilder
### Description
A fluent XML builder for constructing voice call control responses (sent back to Africa's Talking when it POSTs to your voice callback URL). Supports chaining of `say`, `play`, `getDigits`, `dial`, `record`, `enqueue`, `dequeue`, `redirect`, `conference`, and `reject`.
### Usage
Instantiate the builder and chain methods to construct the XML response.
### Example 1: IVR menu with digit collection
```javascript
const { ActionBuilder } = client.VOICE
const xml = new ActionBuilder()
.say('Welcome to our service. Press 1 for sales, 2 for support.', { voice: 'en-US-Wavenet-A', playBeep: false })
.getDigits(
{ say: { text: 'Enter your choice followed by hash.' } },
{ numDigits: 1, finishOnKey: '#', timeout: 10, callbackUrl: 'https://myapp.com/ivr/handle' }
)
.build()
console.log(xml)
// Welcome......
```
### Example 2: Transfer call to agent
```javascript
const transferXml = new ActionBuilder()
.say('Connecting you to an agent.')
.dial('+254711000199', { record: true, sequential: false, maxDuration: 3600 })
.build()
```
### Example 3: Record a voicemail
```javascript
const recordXml = new ActionBuilder()
.say('Please leave a message after the beep.')
.record(
{ say: { text: 'Recording... press hash when done.' } },
{ maxLength: 120, trimSilence: true, callbackUrl: 'https://myapp.com/voicemail', playBeep: true }
)
.build()
```
### Example 4: Handling incoming calls with Express
```javascript
const express = require('express')
const app = express()
app.post('/voice/incoming', (req, res) => {
const xml = new ActionBuilder()
.say('Thank you for calling.')
.conference()
.build()
res.set('Content-Type', 'application/xml')
res.send(xml)
})
```
```
--------------------------------
### Create WhatsApp Message Template with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Use `WHATSAPP.createTemplate` to define and submit reusable WhatsApp message templates for approval. Templates include header, body, footer, and button components. Ensure the `waNumber` is registered.
```javascript
client.WHATSAPP.createTemplate({
waNumber: '254700000000',
name: 'order_confirmation',
language: 'en',
category: 'UTILITY',
components: {
header: {
type: 'HEADER',
format: 'TEXT',
text: 'Order {{1}} Update',
example: { header_text: 'Order #12345 Update' }
},
body: {
type: 'BODY',
text: 'Hi {{1}}, your order worth {{2}} will arrive {{3}}.',
example: { body_text: ['John', 'KES 1200', 'tomorrow'] }
},
footer: {
type: 'FOOTER',
text: 'Thank you for shopping with us!'
},
buttons: {
type: 'BUTTONS',
buttons: [
{ type: 'QUICK_REPLY', text: 'Track Order' },
{ type: 'URL', url: 'https://mystore.com/orders/{{1}}', text: 'View Details', example: ['12345'] }
]
}
}
})
.then(res => console.log(res))
.catch(err => console.error(err.message))
```
--------------------------------
### Manage SMS Subscriptions with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Use these methods to manage premium SMS subscriptions. Ensure you have the correct shortCode and keyword. The createSubscription method requires user confirmation.
```javascript
const sms = client.SMS
// Create a subscription
sms.createSubscription({
shortCode: '40001',
keyword: 'MYAPP',
phoneNumber: '+254711000111'
})
.then(res => console.log(res)) // { status: 'Success', description: 'Waiting for user confirmation' }
.catch(err => console.error(err.message))
// Fetch subscriptions (paginated)
sms.fetchSubscription({
shortCode: '40001',
keyword: 'MYAPP',
lastReceivedId: 0
})
.then(res => {
console.log(res)
// { Subscriptions: [{ id: 1, phoneNumber: '+254711000111', date: '...' }] }
})
// Delete a subscription
sms.deleteSubscription({
shortCode: '40001',
keyword: 'MYAPP',
phoneNumber: '+254711000111'
})
.then(res => console.log(res)) // { status: 'Success', description: 'Subscription removed' }
.catch(err => console.error(err.message))
```
--------------------------------
### SMS Service - Create Subscription
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Creates a premium subscription for a given phone number, short code, and keyword.
```APIDOC
## SMS Service - Create Subscription
### Description
Create a premium subscription.
### Method Signature
`sms.createSubscription({ shortCode, keyword, phoneNumber })`
### Parameters
#### Required
- **shortCode** (string) - The premium short code mapped to your account.
- **keyword** (string) - A premium keyword under the above short code and mapped to your account.
- **phoneNumber** (string) - The phone number to be subscribed.
```
--------------------------------
### Mobile Data Service - Fetch Wallet Balance
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Retrieves the current wallet balance for your mobile data product.
```APIDOC
## MOBILE_DATA.fetchWalletBalance()
### Description
Retrieves the current wallet balance for your mobile data product.
### Method
`MOBILE_DATA.fetchWalletBalance`
### Parameters
None
### Request Example
```javascript
client.MOBILE_DATA.fetchWalletBalance()
```
### Response
#### Success Response (200)
- **balance** (string) - The current wallet balance, including currency (e.g., 'KES 2500.00').
#### Response Example
```json
{ "balance": "KES 2500.00" }
```
```
--------------------------------
### VOICE.uploadMediaFile(params)
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Uploads a media file from a public HTTPS URL for use in voice call flows.
```APIDOC
## VOICE.uploadMediaFile(params)
### Description
Uploads a media file (e.g., audio prompt) from a public HTTPS URL to be used in voice call flows.
### Parameters
#### Request Body
- **phoneNumber** (string) - Required - The phone number associated with the media file.
- **url** (string) - Required - The public HTTPS URL of the media file.
### Request Example
```javascript
client.VOICE.uploadMediaFile({
phoneNumber: '+254711000100',
url: 'https://example.com/audio/welcome.mp3'
})
.then(res => console.log(res))
// { status: 'success' }
.catch(err => console.error(err))
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the status of the upload, e.g., 'success'.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### MobileData Fetch Wallet Balance
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Check the remaining balance for mobile data products.
```APIDOC
## MobileData Fetch Wallet Balance
### Description
Fetch the mobile data product balance.
### Method
`fetchWalletBalance()`
### Parameters
None
```
--------------------------------
### TOKEN.generateAuthToken()
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Generates a temporary authentication token that can be used in place of an API key for API requests.
```APIDOC
## TOKEN.generateAuthToken()
### Description
Generates a short-lived auth token that can be used instead of an API key for authenticating subsequent API requests.
### Request Example
```javascript
client.TOKEN.generateAuthToken()
.then(result => {
console.log(result)
// { token: 'ATtkn_...', lifetimeInSeconds: 3600 }
// Use result.token as the apiKey in subsequent requests
})
.catch(err => console.error(err))
```
### Response
#### Success Response (200)
- **token** (string) - The generated authentication token.
- **lifetimeInSeconds** (number) - The duration in seconds for which the token is valid.
#### Response Example
```json
{
"token": "ATtkn_...",
"lifetimeInSeconds": 3600
}
```
```
--------------------------------
### Send Mobile Data Bundles with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Distribute mobile data bundles to recipients. Each recipient requires a phone number, quantity, unit (MB/GB), validity period, and metadata. An optional idempotency key can be provided.
```javascript
client.MOBILE_DATA.send({
productName: 'MY_DATA_PRODUCT',
recipients: [
{
phoneNumber: '+254711000111',
quantity: 500,
unit: 'MB',
validity: 'Month',
metadata: { customerId: 'CUS001', reason: 'loyalty-reward' }
},
{
phoneNumber: '+254722000222',
quantity: 1,
unit: 'GB',
validity: 'Week',
metadata: { customerId: 'CUS002' }
}
],
idempotencyKey: 'data-txn-20240101' // optional
})
.then(res => console.log(res))
.catch(err => console.error(err.message))
```
--------------------------------
### Find Mobile Data Transaction or Fetch Wallet Balance with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Look up a specific mobile data transaction by its ID or retrieve your current data product wallet balance. Use `findTransaction` for specific lookups and `fetchWalletBalance` for balance inquiries.
```javascript
// Find a specific transaction
client.MOBILE_DATA.findTransaction({ transactionId: 'TXN123456' })
.then(res => {
console.log(res)
// { transactionId: 'TXN123456', status: 'Success', quantity: '500MB', ... }
})
.catch(err => console.error(err.message))
// Fetch wallet balance
client.MOBILE_DATA.fetchWalletBalance()
.then(res => {
console.log(res)
// { balance: 'KES 2500.00' }
})
.catch(err => console.error(err.message))
```
--------------------------------
### Upload Media File - Voice Service
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Uploads an audio file from a public HTTPS URL for use in voice call prompts. The URL must be accessible and serve a valid audio format.
```javascript
client.VOICE.uploadMediaFile({
phoneNumber: '+254711000100',
url: 'https://example.com/audio/welcome.mp3'
})
.then(res => console.log(res))
// { status: 'success' }
.catch(err => console.error(err))
```
--------------------------------
### Token Generate Auth Token
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Generate an authentication token to use instead of an API key.
```APIDOC
## Token Generate Auth Token
### Description
Generate an auth token to use for authentication instead of an API key.
### Method
`generateAuthToken()`
### Parameters
None
```
--------------------------------
### Voice Upload Media File
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Upload a voice media file to be used in calls.
```APIDOC
## Voice Upload Media File
### Description
Upload voice media file.
### Method
`uploadMediaFile({ phoneNumber, url })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- `phoneNumber` (string) - Required. Your Africa's Talking virtual phone number.
- `url` (string) - Required. URL to your media file.
```
--------------------------------
### Send Airtime with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Send airtime to one or multiple recipients. Each recipient needs a phone number, currency code, and amount. Optional idempotency key and retry logic are supported.
```javascript
client.AIRTIME.send({
recipients: [
{ phoneNumber: '+254711000111', currencyCode: 'KES', amount: 50 },
{ phoneNumber: '+254722000222', currencyCode: 'KES', amount: 100 }
],
maxNumRetry: 3, // optional: retry up to 3 times on failure
idempotencyKey: 'unique-txn-id-001' // optional: prevent duplicate sends
})
.then(response => {
console.log(response)
// {
// numSent: 2,
// totalAmount: 'KES 150',
// responses: [
// { phoneNumber: '+254711000111', amount: 'KES 50', status: 'Success', requestId: '...' },
// { phoneNumber: '+254722000222', amount: 'KES 100', status: 'Success', requestId: '...' }
// ]
// }
})
.catch(err => console.error(err.message))
```
--------------------------------
### Voice Fetch Qued Calls
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Retrieve a list of calls that are currently queued.
```APIDOC
## Voice Fetch Qued Calls
### Description
Get queued calls.
### Method
`fetchQuedCalls({ phoneNumber })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- `phoneNumber` (string) - Required. Your Africa's Talking virtual phone number.
```
--------------------------------
### Generate Authentication Token - Token Service
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Creates a temporary authentication token that can be used in place of an API key for subsequent API calls. The response includes the token and its validity period.
```javascript
client.TOKEN.generateAuthToken()
.then(result => {
console.log(result)
// { token: 'ATtkn_...', lifetimeInSeconds: 3600 }
// Use result.token as the apiKey in subsequent requests
})
.catch(err => console.error(err))
```
--------------------------------
### Send WhatsApp Message with Node.js SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Use `WHATSAPP.sendMessage` to send various types of WhatsApp messages. Supports text, media, interactive lists, and template messages. Ensure you have a registered Africa's Talking WhatsApp number.
```javascript
const wa = client.WHATSAPP
// Simple text message
wa.sendMessage({
waNumber: '254700000000',
phoneNumber: '+254711000111',
body: { message: 'Hello! How can we help you today?' }
})
.then(res => console.log(res))
.catch(err => console.error(err))
```
```javascript
// Media message
wa.sendMessage({
waNumber: '254700000000',
phoneNumber: '+254711000111',
body: {
mediaType: 'Image',
url: 'https://example.com/promo-banner.jpg',
caption: 'Check out our latest offers!'
}
})
.then(res => console.log(res))
```
```javascript
// Interactive list
wa.sendMessage({
waNumber: '254700000000',
phoneNumber: '+254711000111',
body: {
header: { text: 'Main Menu' },
body: { text: 'Select a category:' },
footer: { text: 'Powered by MyApp' },
action: {
button: 'Browse',
sections: [{
title: 'Services',
rows: [
{ id: 'svc_1', title: 'Airtime', description: 'Top up your phone' },
{ id: 'svc_2', title: 'Data', description: 'Buy data bundles' }
]
}]
}
}
})
.then(res => console.log(res))
```
```javascript
// Template message
wa.sendMessage({
waNumber: '254700000000',
phoneNumber: '+254711000111',
body: {
templateId: 'order_confirmation',
headerValue: 'Order #12345',
bodyValues: ['John', 'KES 1200', 'tomorrow']
}
})
.then(res => console.log(res))
```
--------------------------------
### Voice Service - Call Initiation
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Initiates an outbound voice call from your Africa's Talking virtual number to one or more destinations.
```APIDOC
## VOICE.call(params)
### Description
Initiates an outbound voice call from your Africa's Talking virtual number to one or more destinations.
### Method
`VOICE.call`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **callFrom** (string) - Required - Your Africa's Talking virtual number.
- **callTo** (string or array) - Required - A comma-separated string or an array of destination phone numbers.
- **clientRequestId** (string) - Optional - A tag for your callback requests.
### Request Example
```javascript
client.VOICE.call({
callFrom: '+254711000100',
callTo: '+254711000111,+254722000222',
clientRequestId: 'session-xyz-001'
})
```
### Response
#### Success Response (200)
- **entries** (array) - A list of call entries.
- **phoneNumber** (string) - The destination phone number.
- **status** (string) - The status of the call initiation (e.g., 'Queued').
#### Response Example
```json
{ "entries": [{ "phoneNumber": "+254711000111", "status": "Queued" }, ...] }
```
```
--------------------------------
### Fetch Incoming SMS using Africa's Talking SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Fetch incoming messages from the SMS inbox. Use `lastReceivedId` for pagination, passing the ID of the last processed message (defaults to `0`).
```javascript
// Initial fetch
client.SMS.fetchMessages({ lastReceivedId: 0 })
.then(data => {
console.log(data)
// { SMSMessageData: { Messages: [{ id: 1, text: 'Hello', from: '+254...', date: '...' }, ...] } }
const lastId = data.SMSMessageData.Messages.slice(-1)[0]?.id
// Use lastId in next call for pagination
})
.catch(err => console.error(err.message))
```
--------------------------------
### SMS.sendPremium(params)
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Sends a premium-rated SMS to a subscriber, billed through a registered premium shortcode and keyword. Requires `keyword`; `linkId` and `retryDurationInHours` are optional.
```APIDOC
## SMS.sendPremium(params)
### Description
Sends a premium-rated SMS to a subscriber, billed through a registered premium shortcode and keyword. Requires `keyword`; `linkId` and `retryDurationInHours` are optional.
### Method
POST (inferred)
### Endpoint
/sms/premium
### Parameters
#### Request Body
- **to** (string) - Required - Recipient phone number in international format.
- **from** (string) - Required - Your registered premium shortcode.
- **message** (string) - Required - The message content.
- **keyword** (string) - Required - The keyword associated with the premium service.
- **linkId** (string) - Optional - Link ID from an incoming message.
- **retryDurationInHours** (integer) - Optional - Number of hours to retry failed deliveries.
### Request Example
```javascript
client.SMS.sendPremium({
to: '+254711000111',
from: '40001', // your registered premium shortcode
message: 'Your premium content here',
keyword: 'MYAPP',
linkId: 'link_abc123', // optional: subscribe linkId from incoming message
retryDurationInHours: 2 // optional: retry failed deliveries for 2 hours
})
```
### Response
#### Success Response (200)
- **SMSMessageData** (object) - Contains message status, cost, and recipient details.
- **Message** (string) - Summary of the send operation.
- **Recipients** (array) - Array of recipient objects.
- **number** (string) - Recipient's phone number.
- **status** (string) - Delivery status.
- **cost** (string) - Cost of sending to this recipient.
- **messageId** (string) - Unique ID for the sent message.
#### Response Example
```json
{
"SMSMessageData": {
"Message": "Sent to 1/1 Total Cost: KES 5",
"Recipients": [
{ "number": "+254711000111", "status": "Success", "cost": "KES 5", "messageId": "ATXid_..." }
]
}
}
```
```
--------------------------------
### SMS Service - Subscription Management
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Manage premium SMS subscriptions: create, fetch, or delete subscriptions for a given phone number, shortcode, and keyword.
```APIDOC
## SMS.createSubscription(params)
### Description
Creates a new premium SMS subscription for a phone number under a specified shortcode and keyword.
### Method
`SMS.createSubscription`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **shortCode** (string) - Required - The short code for the subscription.
- **keyword** (string) - Required - The keyword for the subscription.
- **phoneNumber** (string) - Required - The phone number to subscribe.
### Request Example
```javascript
sms.createSubscription({
shortCode: '40001',
keyword: 'MYAPP',
phoneNumber: '+254711000111'
})
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the status of the operation (e.g., 'Success').
- **description** (string) - A message describing the result (e.g., 'Waiting for user confirmation').
#### Response Example
```json
{ "status": "Success", "description": "Waiting for user confirmation" }
```
## SMS.fetchSubscription(params)
### Description
Fetches existing premium SMS subscriptions, supporting pagination.
### Method
`SMS.fetchSubscription`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **shortCode** (string) - Required - The short code for the subscription.
- **keyword** (string) - Required - The keyword for the subscription.
- **lastReceivedId** (number) - Required - The ID to start fetching from for pagination.
### Request Example
```javascript
sms.fetchSubscription({
shortCode: '40001',
keyword: 'MYAPP',
lastReceivedId: 0
})
```
### Response
#### Success Response (200)
- **Subscriptions** (array) - A list of subscription objects.
- **id** (number) - The subscription ID.
- **phoneNumber** (string) - The phone number associated with the subscription.
- **date** (string) - The date of the subscription.
#### Response Example
```json
{ "Subscriptions": [{ "id": 1, "phoneNumber": "+254711000111", "date": "..." }] }
```
## SMS.deleteSubscription(params)
### Description
Deletes an existing premium SMS subscription for a given phone number, shortcode, and keyword.
### Method
`SMS.deleteSubscription`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **shortCode** (string) - Required - The short code for the subscription.
- **keyword** (string) - Required - The keyword for the subscription.
- **phoneNumber** (string) - Required - The phone number to unsubscribe.
### Request Example
```javascript
sms.deleteSubscription({
shortCode: '40001',
keyword: 'MYAPP',
phoneNumber: '+254711000111'
})
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the status of the operation (e.g., 'Success').
- **description** (string) - A message describing the result (e.g., 'Subscription removed').
#### Response Example
```json
{ "status": "Success", "description": "Subscription removed" }
```
```
--------------------------------
### Voice Call
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Initiate a phone call from your Africa's Talking virtual number to specified recipients.
```APIDOC
## Voice Call
### Description
Initiate a phone call.
### Method
`call({ callFrom, callTo, clientRequestId })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- `callFrom` (string) - Required. Your Africa's Talking virtual phone number.
- `callTo` (string) - Required. Comma-separated string of phone numbers to call.
- `clientRequestId` (string) - Optional. Identifier for the call in callback URLs.
```
--------------------------------
### Register USSD Handler - Express Middleware
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Sets up an Express middleware to handle incoming USSD requests. The handler function receives session parameters and a `sendResponse` callback. Use `endSession: true` to terminate the USSD session.
```javascript
const express = require('express')
const { USSD } = client
const app = express()
app.post('/ussd', USSD(function (params, sendResponse) {
// params: { sessionId, serviceCode, phoneNumber, text }
const { text, phoneNumber } = params
if (text === '') {
// Initial request — show main menu
sendResponse({ response: 'Welcome!\n1. Check balance\n2. Buy airtime', endSession: false })
} else if (text === '1') {
sendResponse({ response: 'Your balance is KES 250.00', endSession: true })
} else if (text === '2') {
sendResponse({ response: 'Enter amount:', endSession: false })
} else {
// text is '2*50', '2*100', etc.
const amount = text.split('*')[1]
sendResponse({ response: `Purchasing KES ${amount} airtime for ${phoneNumber}. Done!`, endSession: true })
}
}))
app.listen(3000)
```
--------------------------------
### MobileData Send
Source: https://github.com/africastalkingltd/africastalking-node.js/blob/develop/README.md
Send mobile data bundles to recipients. Requires product name and recipient details.
```APIDOC
## MobileData Send
### Description
Send mobile data bundles to recipients.
### Method
`send({ productName, recipients })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- `productName` (string) - Required. The application's product name for mobile data.
- `recipients` (Array) - Required. An array of objects, each containing:
- `phoneNumber` (string) - Required. Recipient's phone number.
- `quantity` (number) - Required. Amount of data.
- `unit` (string) - Required. Unit of data (e.g., 'MB', 'GB').
- `validity` (string) - Required. Validity period (e.g., 'Day', 'Week', 'Month').
- `metadata` (object) - Required. Any metadata to associate with the request.
```
--------------------------------
### SMS.fetchMessages(params)
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Fetches incoming messages manually from the SMS inbox. Use `lastReceivedId` for pagination — pass the ID of the last message you processed (defaults to `0`).
```APIDOC
## SMS.fetchMessages(params)
### Description
Fetches incoming messages manually from the SMS inbox. Use `lastReceivedId` for pagination — pass the ID of the last message you processed (defaults to `0`).
### Method
GET (inferred)
### Endpoint
/sms/inbox
### Parameters
#### Query Parameters
- **lastReceivedId** (integer) - Optional - The ID of the last message received. Defaults to 0 for initial fetch.
### Request Example
```javascript
// Initial fetch
client.SMS.fetchMessages({ lastReceivedId: 0 })
// Subsequent fetch for pagination
// const lastId = ... // obtained from previous response
// client.SMS.fetchMessages({ lastReceivedId: lastId })
```
### Response
#### Success Response (200)
- **SMSMessageData** (object) - Contains incoming messages.
- **Messages** (array) - Array of incoming message objects.
- **id** (integer) - Unique ID of the message.
- **text** (string) - The content of the message.
- **from** (string) - Sender's phone number.
- **date** (string) - Timestamp of when the message was received.
#### Response Example
```json
{
"SMSMessageData": {
"Messages": [
{ "id": 1, "text": "Hello", "from": "+254...", "date": "..." },
{ "id": 2, "text": "How are you?", "from": "+254...", "date": "..." }
]
}
}
```
```
--------------------------------
### Send Premium SMS using Africa's Talking SDK
Source: https://context7.com/africastalkingltd/africastalking-node.js/llms.txt
Send premium-rated SMS to subscribers, billed through a registered shortcode and keyword. Requires `keyword`; `linkId` and `retryDurationInHours` are optional.
```javascript
client.SMS.sendPremium({
to: '+254711000111',
from: '40001', // your registered premium shortcode
message: 'Your premium content here',
keyword: 'MYAPP',
linkId: 'link_abc123', // optional: subscribe linkId from incoming message
retryDurationInHours: 2 // optional: retry failed deliveries for 2 hours
})
.then(response => {
console.log(response.SMSMessageData)
// { Message: 'Sent to 1/1 Total Cost: KES 5', Recipients: [...] }
})
.catch(err => console.error(err.message))
```