Skip to content
This repository has been archived by the owner on Jun 24, 2024. It is now read-only.

Latest commit

 

History

History
1108 lines (855 loc) · 31.1 KB

DOCS.md

File metadata and controls

1108 lines (855 loc) · 31.1 KB

SDK Reference

Contents

What can I import from the SDK?

You can import the following functions, classes and Typescript types from the SDK:

  • Client
  • ActionBuilder (for Voice)
  • CONSTANTS (for Payments)
  • Types for Typescript e.g. SmsResponse, SendAirtimeResponse, etc.
import { Client, ActionBuilder, CONSTANTS, SmsResponse, SendAirtimeResponse } from 'africastalking-ts';

// or

const { Client, ActionBuilder, CONSTANTS, SmsResponse, SendAirtimeResponse } = require('africastalking-ts').

Notes

  • All functions are asynchronous.
  • All phone numbers use the international format. e.g. +254xxxxxxxx.

Initializing a Client

You need your app username and your API key to create a new Africa's Talking Client, both of 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

import { Client } from 'africastalking-ts'; // const { Client } = require('africastalking-ts');

const client = new Client({
    apiKey: 'YOUR_API_KEY', // you can get this from the dashboard: https://account.africastalking.com
    username: 'YOUR_USERNAME', // use 'sandbox' as the value for development in the test environment
});

Client Functions

Airtime Operations

  • sendAirtimeRequest({ recipients })

Send airtime to a bunch of phone numbers.

Parameters

Param Type Description
recipients array, REQUIRED An array of objects containing the recipients.

Each recipient in the array is of the format:

Param Type Description
phoneNumber string, REQUIRED The recipient's phone number.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to charge.

For more information, please read http://docs.africastalking.com/airtime/sending.

Example

client.sendAirtimeRequest({
  recipients: [
    {
      phoneNumber: '+254711111111',
      currencyCode: 'KES',
      amount: 10,
    },
  ],
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Application Operations

  • fetchApplicationData()

Get app information. e.g. balance.

For more information, please read http://docs.africastalking.com/userdata/balance.

Example

client.fetchApplicationData()
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Chat Operations

  • sendChatOptIn({ from, to, action })

Send an Opt In request to a Whatsapp phone number.

Parameters

Param Type Description
from string, REQUIRED The channel number, e.g. +254711111111.
to string, REQUIRED The customer number, e.g. +254711111111.
action string, REQUIRED The type of action. Can be OptIn or OptOut.

Example

client.sendChatOptIn({
  from: '+254711111111',
  to: '+254711111111',
  action: 'OptIn',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • sendChatTemplateMessage({ productId, from, to, template })

Send a Template Message to a Whatsapp phone number.

Parameters

Param Type Description
productId string, REQUIRED The product id, e.g. titan-ltd.
from string, REQUIRED The channel number, e.g. +254711111111.
to string, REQUIRED The customer number, e.g. +254711111111.
template object, REQUIRED The template to be used. See format below.

template is of the following format:

Param Type Description
name name, REQUIRED The name of the WhatsApp template to use. This must be approved by WhatsApp.
params array of strings, REQUIRED Parameters to use to substitute into the WhatsApp template message.

Example

client.sendChatTemplateMessage({
  productId: 'titan-ltd',
  from: '+254711111111',
  to: '+254711111111',
  template: {
    name: 'lorem',
    params: ['john', 'doe', 10, 5],
  },
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • sendChatTextMessage({ productId, channel, from, to, message })

Send a Text Message to a Whatsapp phone number or Telegram chat.

Parameters

Param Type Description
productId string, REQUIRED The product id, e.g. titan-ltd.
channel string, REQUIRED Can be either whatsapp or telegram.
from string, REQUIRED The channel number, e.g. +254711111111.
to string, REQUIRED The customer number, e.g. +254711111111.
message string, REQUIRED The message to be sent.

Example 1: Whatsapp

client.sendChatTextMessage({
  productId: 'titan-ltd',
  channel: 'whatsapp',
  from: '+254711111111',
  to: '+254711111111',
  message: 'Hello world',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Example 2: Telegram

client.sendChatTextMessage({
  productId: 'titan-ltd',
  channel: 'telegram',
  from: 'titan_ltd_bot',
  to: '987654321',
  message: 'Hello world',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • sendChatMediaMessage({ productId, channel, from, to, type, url, caption })

Send a Media Message to a Whatsapp phone number or Telegram chat.

Parameters

Param Type Description
productId string, REQUIRED The product id, e.g. titan-ltd.
channel string, REQUIRED Can be either whatsapp or telegram.
from string, REQUIRED The channel number, e.g. +254711111111.
to string, REQUIRED The customer number, e.g. +254711111111.
type string, REQUIRED Can be image, video, audio, document, voice, or sticker.
url string, REQUIRED The file url.
caption string, OPTIONAL A caption for the media file.

Example 1: Whatsapp

client.sendChatTextMessage({
  productId: 'titan-ltd',
  channel: 'whatsapp',
  from: '+254711111111',
  to: '+254711111111',
  type: 'image',
  url: 'https://www.fonewalls.com/wp-content/uploads/1536x2048-Background-HD-Wallpaper-213.jpg',
  caption: 'Hello world',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Example 2: Telegram

client.sendChatTextMessage({
  productId: 'titan-ltd',
  channel: 'telegram',
  from: 'titan_ltd_bot',
  to: '987654321',
  type: 'image',
  url: 'https://www.fonewalls.com/wp-content/uploads/1536x2048-Background-HD-Wallpaper-213.jpg',
  caption: 'Hello world',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • sendChatLocationMessage({ productId, channel, from, to, lat, lng })

Send a Location Message to a Whatsapp phone number or Telegram chat.

Parameters

Param Type Description
productId string, REQUIRED The product id, e.g. titan-ltd.
channel string, REQUIRED Can be either whatsapp or telegram.
from string, REQUIRED The channel number, e.g. +254711111111.
to string, REQUIRED The customer number, e.g. +254711111111.
lat string, REQUIRED The latitude which should be between -90 and +90.
lng string, REQUIRED The longitude which should be between -180 and +180

Example 1: Whatsapp

client.sendChatTextMessage({
  productId: 'titan-ltd',
  channel: 'whatsapp',
  from: '+254711111111',
  to: '+254711111111',
  lat: 1.2,
  lng: -5.224,
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Example 2: Telegram

client.sendChatTextMessage({
  productId: 'titan-ltd',
  channel: 'telegram',
  from: 'titan_ltd_bot',
  to: '987654321',
  lat: 1.2,
  lng: -5.224,
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Payments Operations

  • topupStash({ productName, currencyCode, amount, metadata })

Move money from a Payment Product to an app's stash.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to transfer.
metadata object Additional info to go with the transfer.

Example

client.walletTransfer({
  productName: 'TestProduct',
  currencyCode: 'KES',
  amount: 50,
  metadata: {
    id: '088930432excvmklevdf',
    name: 'John Doe',
  },
});
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • walletTransfer({ productName, targetProductCode, currencyCode, amount, metadata })

Move money form one payment product to another.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
targetProductCode string, REQUIRED ID of recipient payment product on Africa's Talking.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to transfer.
metadata object Additional info to go with the transfer.

Example

client.walletTransfer({
  productName: 'TestProduct',
  targetProductCode: 3323,
  currencyCode: 'KES',
  amount: 50,
  metadata: {
    id: '088930432excvmklevdf',
    name: 'John Doe',
  },
});
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

bank

  • bankCheckoutCharge({ productName, bankAccount, currencyCode, amount, narration, metadata })

Initiate a bank checkout.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
bankAccount object, REQUIRED Bank account to charge.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to transfer.
narration string, REQUIRED Checkout description.
metadata object Additional info to go with the transfer.

Example

import { CONSTANTS } from 'africastalking-ts';

client.bankCheckoutCharge({
  productName: 'TestProduct',
  bankAccount: {
    accountName: 'Test Bank Account',
    accountNumber: '1234567890',
    bankCode: CONSTANTS.BANK.FCMB_NG,
  },
  currencyCode: 'KES',
  amount: 50,
  narration: 'Test Payment',
  metadata: {
    id: '088930432excvmklevdf',
    name: 'John Doe',
  },
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • bankCheckoutValidate({ transactionId, otp })

Validate a bank checkout.

Parameters

Param Type Description
transactionId string, REQUIRED Transaction ID returned on charge request.
otp string, REQUIRED A user-provided OTP.

Example

client.bankCheckoutValidate({
  transactionId: 'ATPid_SampleTxnId1',
  otp: '1234',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • bankTransfer({ productName, recipients })

Initiate a bank transfer.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
recipients array, REQUIRED A list of banks to transfer to.

Each recipient in the array is of the format:

Param Type Description
bankAccount object, REQUIRED Bank account to charge.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to transfer.
narration string, REQUIRED Checkout description.
metadata object Additional info to go with the transfer.

The bankAccount is of the format:

Param Type Description
accountName string, REQUIRED The name of the bank account.
accountNumber string, REQUIRED The bank account number.
bankCode number, REQUIRED The bank code.
dateOfBirth string, REQUIRED The date of birth.

Example

import { CONSTANTS } from 'africastalking-ts';

client.bankTransfer({
  productName: 'TestProduct',
  recipients: [{
    bankAccount: {
      accountName: 'Test Bank Account',
      accountNumber: '1234567890',
      bankCode: CONSTANTS.BANK.FCMB_NG,
    },
    currencyCode: 'KES',
    amount: 50,
    narration: 'Test Payment',
    metadata: {
      id: '088930432excvmklevdf',
      name: 'John Doe',
    },
  }],
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

card

  • cardCheckoutCharge({ productName, paymentCard, checkoutToken, currencyCode, amount, narration, metadata })

Initiate a card checkout.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
paymentCard object, REQUIRED (if checkoutToken is not provided) Card to charge.
checkoutToken string, REQUIRED (if paymentCard is not provided) Token from a previous successful transaction.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to transfer.
narration string, REQUIRED Checkout description.
metadata object Additional info to go with the transfer.

paymentCard is of the following format:

Param Type Description
number string, REQUIRED Payment card number.
cvvNumber object, REQUIRED 3 or 4 digit payment card verification value.
expiryMonth number, REQUIRED Expiration month on the payment card.
expiryYear number, REQUIRED Expiration year on the payment card.
countryCode string, REQUIRED 2-Digit country code where the payment card was issued. Only “NG” is currently supported
authToken string, REQUIRED The payment cards ATM PIN.

Example

client.cardCheckoutCharge({
  productName: 'TestProduct',
  paymentCard: {
    number: '123456789000',
    cvvNumber: 654,
    expiryMonth: 7,
    expiryYear: 2025,
    authToken: '2345',
    countryCode: 'NG',
  },
  currencyCode: 'NGX',
  amount: 50,
  narration: 'Test Payment',
  metadata: {
    id: '088930432excvmklevdf',
    name: 'John Doe',
  },
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • cardCheckoutValidate()

Validate a card checkout.

Parameters

Param Type Description
transactionId string, REQUIRED Transaction ID returned on charge request.
otp string, REQUIRED A user-provided OTP.

Example

client.cardCheckoutValidate({
  transactionId: 'ATPid_SampleTxnId1',
  otp: '1234',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

mobile

  • mobileB2B({ productName, provider, transferType, currencyCode, amount, destinationChannel, destinationAccount, metadata })

Send mobile money to business.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
provider string, REQUIRED Provider used to process request.
transferType string, REQUIRED Transfer type of the payment.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to transfer.
destinationChannel string, REQUIRED Name or number of channel to receive payment.
destinationAccount string, REQUIRED Account name used to receive money.
metadata object, REQUIRED Additional info to go with the transfer.

Example

import { CONSTANTS } from 'africastalking-ts';

client.mobileB2B({
  productName: 'TestProduct',
  provider: CONSTANTS.PROVIDER.ATHENA,
  transferType: CONSTANTS.TRANSFER_TYPE.B2B_TRANSFER,
  currencyCode: 'KES',
  amount: 100,
  destinationChannel: '456789',
  destinationAccount: 'octopus',
  metadata: { notes: 'Account top-up for July 2017' },
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • mobileB2C({ productName, recipients })

Send mobile money to consumer.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
recipients array, REQUIRED A list of consumers that will receive the money.

Each recipient in the array is of the format:

Param Type Description
name string The recipient's name.
phoneNumber string, REQUIRED The recipient's phone number.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to charge.
providerChannel string, REQUIRED The channel the payment will be made from e.g a paybill number.
reason string, REQUIRED Purpose of the payment.
metadata object, REQUIRED Additional info to go with the transfer.

Example

import { CONSTANTS } from 'africastalking-ts';

client.mobileB2C({
  productName: 'TestProduct',
  recipients: [
    {
      phoneNumber: '254711111111',
      currencyCode: 'KES',
      reason: CONSTANTS.REASON.SALARY,
      metadata: {
        id: '088930432excvmklevdf',
        name: 'John Doe',
      },
      amount: 234.5,
    },
  ],
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • mobileCheckout({ productName, providerChannel, phoneNumber, currencyCode, amount, metadata })

Initiate mobile checkout.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
providerChannel string Provider channel to consider when charging.
phoneNumber string, REQUIRED The recipient's phone number.
currencyCode string, REQUIRED 3-digit ISO format currency code.
amount number, REQUIRED Amount to charge.
metadata object, REQUIRED Additional info to go with the transfer.

Example

client.mobileCheckout({
  productName: 'TestProduct',
  phoneNumber: '+254711111111',
  currencyCode: 'KES',
  metadata: {
    id: '088930432excvmklevdf',
    name: 'John Doe',
  },
  amount: 234.5,
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • mobileData({ productName, recipients })

Send mobile data to customers.

Parameters

Param Type Description
productName string, REQUIRED Your payment product.
recipients array, REQUIRED A list of consumers that will receive the money.

Each recipient in the array is of the format:

Param Type Description
phoneNumber string, REQUIRED The recipient's phone number.
quantity number, REQUIRED Mobile data amount.
unit string, REQUIRED Mobile data unit. Can either be MB or GB.
validity string, REQUIRED How long the mobile data is valid for. Must be one of Day, Week and Month.
metadata object, REQUIRED Additional info to go with the transfer.

Example

client.mobileData({
  productName: 'TestProduct',
  recipients: [{
    phoneNumber: '+254711223344',
    quantity: 10,
    unit: 'GB',
    validity: 'Month',
    metadata: {
      id: '088930432excvmklevdf',
      name: 'John Doe',
    },
  }],
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

query

  • fetchProductTransactions({ productName, filters })

Fetch payment product transactions.

Param Type Description
productName string, REQUIRED Your payment product.
filters object, REQUIRED Query filters.

filters is of the format:

Param Type Description
pageNumber string, REQUIRED Page number to fetch results from. Starts from '1'.
count string, REQUIRED Number of results to fetch.
startDate string Start Date to consider when fetching.
endDate string End Date to consider when fetching.
category string Category to consider when fetching.
provider string Provider to consider when fetching.
status string Status to consider when fetching.
source string Source to consider when fetching.
destination string Destination to consider when fetching.
providerChannel string Provider channel to consider when fetching.

Example

client.fetchProductTransactions({
  productName: 'TestProduct',
  filters: {
    pageNumber: '1',
    count: '10',
  },
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • fetchWalletBalance()

Fetch your wallet's balance

Example

client.fetchWalletBalance()
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • fetchWalletTransactions({ filters })

Fetch wallet transactions.

Param Type Description
filters object, REQUIRED Query filters.

filters is of the format:

Param Type Description
pageNumber string, REQUIRED Page number to fetch results from. Starts from '1'.
count string, REQUIRED Number of results to fetch.
startDate string Start Date to consider when fetching.
endDate string End Date to consider when fetching.
categories string Category to consider when fetching.

Example

client.fetchWalletTransactions({
  filters: {
    pageNumber: '1',
    count: '10',
  },
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • findTransaction({ transactionId })

Find a particular transaction.

Param Type Description
transactionId string, REQUIRED Transaction ID returned on charge request.

Example

client.findTransaction({
  transactionId: 'ATPid_SampleTxnId1',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

For more information, please read http://docs.africastalking.com/payments.

SMS Operations

  • fetchMessages({ lastReceivedId })

Manually retrieve your messages.

Param Type Description
lastReceivedId string, REQUIRED This is the id of the message that you last processed. Defaults to '0'.

Example

client.fetchMessages()
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • sendSms({ to, message, from, enqueue })

Send a message.

Param Type Description
to string, REQUIRED Recipients phone number.
message string, REQUIRED SMS content.
from string Shortcode or alphanumeric ID that is registered with Africa's Talking account.
enqueue string Set to true if you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.

Example

client.sendSms({
  to: '+254711111111',
  message: 'This is a test',
  enqueue: true,
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • sendPremiumSms({ to, message, from, enqueue, keyword, linkId, retryDurationInHours })

Send premium SMS.

Param Type Description
to string, REQUIRED Recipients phone number.
message string, REQUIRED SMS content.
from string Shortcode or alphanumeric ID that is registered with Africa's Talking account.
enqueue string Set to true if you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.
keyword string Your premium product keyword.
linkId string We forward the linkId to your application when the user send a message to your service.
retryDurationInHours string It specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber.

Example

client.sendPremiumSms({
  to: '+254718760882',
  from: 'testService',
  message: 'This is premium test',
  keyword: 'test',
  linkId: '76test',
  retryDurationInHours: 1,
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

premium subscriptions

  • createSubscription({ shortCode, keyword, phoneNumber, checkoutToken })

Create a premium subscription.

Param Type Description
shortCode string, REQUIRED This is the premium short code mapped to your account.
keyword string, REQUIRED A premium keyword under the above short code and mapped to your account.
phoneNumber string, REQUIRED The phone number to be subscribed.
checkoutToken string, REQUIRED This is a token used to validate the subscription request.

Example

client.createSubscription({
  shortCode: '1234',
  keyword: 'TESTKWD',
  phoneNumber: '+254711111111',
  checkoutToken: '12abvsfdhh63535',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • deleteSubscription({ shortCode, keyword, phoneNumber })

Deletes a premium subscription.

Param Type Description
shortCode string, REQUIRED This is the premium short code mapped to your account.
keyword string, REQUIRED A premium keyword under the above short code and mapped to your account.
phoneNumber string, REQUIRED The phone number to be subscribed.

Example

client.deleteSubscription({
  shortCode: '1234',
  keyword: 'TESTKWD',
  phoneNumber: '+254711111111',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • fetchSubscription({ shortCode, keyword, lastReceivedId })

Fetches premium subscriptions.

Param Type Description
shortCode string, REQUIRED This is the premium short code mapped to your account.
keyword string, REQUIRED A premium keyword under the above short code and mapped to your account.
lastReceivedId number ID of the subscription you believe to be your last. Set it to 0 to for the first time.

Example

client.fetchSubscription({
  shortCode: '1234',
  keyword: 'TESTKWD',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

For more information, please read:

Token Operations

  • createCheckoutToken(phoneNumber)

Create a new checkout token.

Param Type Description
shortCode string, REQUIRED The phone number you want to create a subscription for.

Example

client.createCheckoutToken('+254711111111')
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • generateAuthToken()

Generate an auth token to use for authentication instead of an API key.

Example

client.generateAuthToken()
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

Voice Operations

  • getNumQueuedCalls({ phoneNumbers })

Get queued calls.

Param Type Description
phoneNumbers string, REQUIRED Your Africa's Talking issued virtual phone number.

Example

client.getNumQueuedCalls({
  phoneNumbers: '254711111111'
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • makeCall({ callFrom, callTo, clientRequestId })

Initiate a phone call.

Param Type Description
callFrom string, REQUIRED Your Africa's Talking issued virtual phone number.
callTo string, REQUIRED Phone number to dial.
clientRequestId string Variable sent to your Events Callback URL that can be used to tag the call.

Example

client.makeCall({
  callFrom: '+254711111111',
  callTo: ['+254711111111', '+254722222222'],
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));
  • uploadMediaFile({ url })

Upload voice media file.

Param Type Description
url string, REQUIRED The url of the file to upload. Don’t forget to start with http://.

Example

client.uploadMediaFile({
  url: 'http://google.com',
})
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

For more information, please read http://docs.africastalking.com/voice.