Africa's Talking Node.js SDK

repository·develop·Indexed 41 days ago

https://github.com/africastalkingltd/africastalking-node.js

Official Node.js API wrapper for Africa's Talking, providing access to SMS, Airtime, Voice, USSD, WhatsApp, Mobile Data, Insights, and Token services. Version 0.8.3 supports sending standard and premium SMS, distributing airtime and data bundles, managing voice calls with XML helpers, and checking SIM swap states.

Tokens
8K
Snippets
25
Records
31
Agent score
50%

What's inside Africa's Talking

  1. How to access Africa's Talking services

    develop

    Once the SDK is initialized, you can access various services through the AfricasTalking instance. Each service is available as a property on the object returned by the initialization function.

    Available services include:

    • SMS Service: AfricasTalking.SMS
    • Airtime Service: AfricasTalking.AIRTIME
    • Mobile Data Service: AfricasTalking.MOBILE_DATA
    • Voice Service: AfricasTalking.VOICE
    • USSD API: AfricasTalking.USSD
    • Token Service: AfricasTalking.TOKEN
    • Insights: AfricasTalking.INSIGHTS
    • WhatsApp: AfricasTalking.WHATSAPP
    • Application Service: AfricasTalking.APPLICATION
  2. Initialize the Africa's Talking SDK

    develop

    To use the SDK, you must initialize it by passing a credentials object to the required module. The credentials object must contain your username and apiKey obtained from the Africa's Talking dashboard.

    Sandbox Environment: If you are developing in the sandbox/test environment, the username must ALWAYS be set to 'sandbox'.

    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);
  3. Send an SMS using the SMS service

    develop

    To send an SMS, access the SMS service from your initialized AfricasTalking instance and call the .send(options) method. The method returns a Promise that resolves with the response or rejects with an error.

    const credentials = {
        apiKey: 'YOUR_API_KEY',
        username: 'YOUR_USERNAME',
    };
    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);
        });
  4. Use the WhatsApp service

    develop

    The WhatsApp service allows sending messages and managing templates.

    Send WhatsApp Messages

    • sendMessage({ body, waNumber, phoneNumber }): Sends a message to a recipient.

    Parameters:

    • waNumber (REQUIRED): The WhatsApp number associated with your account.
    • phoneNumber (REQUIRED): The recipient's number.
    • body: An object defining the message type:
      • Simple Text: { message: 'text' }
      • Media: { mediaType: 'Image'|'Video'|'Audio'|'Document'|'Voice', url: '...', caption: '...' }
      • Interactive List: Contains action (buttons, sections, rows, product_items), body, header, and footer.
      • Interactive Buttons: Contains action (buttons), body, header, and footer.
      • Template: { templateId: '...', headerValue: '...', bodyValues: [...] }

    Manage Templates

    • createTemplate({ component, waNumber, name, language, category }): Creates a new message template.
      • waNumber (REQUIRED): Your account's WhatsApp number.
      • name (REQUIRED): Unique template name.
      • language (REQUIRED): ISO 639-1 code.
      • category: MARKETING, UTILITY, or AUTHENTICATION.
      • components: Object defining header, body, footer, and buttons (including types like PHONE_NUMBER, URL, FLOW, COPY_CODE, or QUICK_REPLY).
  5. Use the Voice service

    develop

    The Voice service handles phone calls and media uploads.

    Call Management

    • call({ callFrom, callTo, clientRequestId }): Initiate a call.
      • callFrom (REQUIRED): Your Africa's Talking issued virtual phone number.
      • callTo (REQUIRED): Comma-separated string of phone numbers to call.
      • clientRequestId: Tag used in your callback URL.
    • fetchQuedCalls({ phoneNumber }): Get queued calls for a specific virtual number.
    • uploadMediaFile({ phoneNumber, url }): Upload a voice media file to a virtual number.

    Voice XML Helpers

    The SDK provides helpers to construct XML for responding to Africa's Talking API POST requests (callbacks). Remember to always return an HTTP 200 response to the API.

    Available Helpers: Say, Play, GetDigits, Dial, Record, Enqueue, Dequeue, Conference, Redirect, Reject

  6. Use the MobileData service

    develop

    The MobileData service manages mobile data bundles.

    Send Mobile Data

    • send({ productName, recipients }): Sends data bundles to recipients.

    Parameters:

    • productName: The application's product name.
    • recipients (REQUIRED): An array of objects containing:
      • phoneNumber (REQUIRED): Recipient's phone number.
      • quantity (REQUIRED): Numeric value for the amount of data.
      • unit (REQUIRED): Units (MB or GB).
      • validity (REQUIRED): Period of validity (Day, Week, BiWeek, Month, or Quarterly).
      • metadata (REQUIRED): A JSON object for associated metadata.

    Other Methods

    • findTransaction({ transactionId }): Find a specific mobile data transaction.
    • fetchWalletBalance(): Fetch the mobile data product balance.
    await mobileData.send({
      productName: 'MyDataApp',
      recipients: [{
        phoneNumber: '+234xxxxxxxxxx',
        quantity: 1,
        unit: 'GB',
        validity: 'Month',
        metadata: { userId: '123' }
      }]
    });
  7. Use other Africa's Talking services

    develop

    The SDK provides access to several other specialized services:

    • USSD: For USSD application logic.
    • Token: generateAuthToken() generates an auth token for authentication instead of using an API key.
    • Insights: checkSimSwapState([phoneNumbers]) checks the SIM swap state for one or more phone numbers.
    • Application: fetchApplicationData() retrieves application information, such as account balance.
  8. Use the Airtime service

    develop

    The Airtime service allows you to send airtime to recipients and check transaction statuses.

    Send Airtime

    • send({ recipients }): Sends airtime to multiple phone numbers.

    Parameters:

    • recipients (REQUIRED): An array of objects containing:
      • phoneNumber (REQUIRED): Recipient's phone number.
      • currencyCode (REQUIRED): 3-digit ISO format currency code.
      • amount (REQUIRED): Amount to charge.
    • maxNumRetry (OPTIONAL): Maximum number of retries for failed deliveries. The default retry period is 8 hours with retries every 60 seconds. For example, maxNumRetry: 4 means retries occur every 60 seconds for the next 4 hours.
    await airtime.send({
      recipients: [
        {
          phoneNumber: '+234xxxxxxxxxx',
          currencyCode: 'KES',
          amount: 100
        }
      ],
      maxNumRetry: 4
    });
  9. Use the SMS service

    develop

    The SMS service allows you to send standard messages, premium messages, and manage subscriptions. All methods are asynchronous and phone numbers must use the international format (e.g., +234xxxxxxxx).

    Standard SMS

    • send({ to, senderId, message, enqueue }): Send an SMS to a single number or an array of numbers.
    • send([{ to, senderId, message, enqueue }]): Send multiple SMSes using an array of objects.

    Parameters:

    • to (REQUIRED): Recipient phone number or array of numbers.
    • senderId: Registered shortcode or alphanumeric ID.
    • message (REQUIRED): The SMS content.
    • enqueue: Boolean. If true, messages are delivered without waiting for telco acknowledgement.

    Premium SMS

    • sendPremium({ to, from, message, enqueue, keyword, linkId, retryDurationInHours }): Send premium SMS.
      • keyword: Your premium product keyword.
      • linkId: Forwarded to your application when a user sends a message.
      • retryDurationInHours: Number of hours to retry subscription messages if undelivered.
    • fetchMessages({ lastReceivedId }): Manually retrieve messages. lastReceivedId defaults to 0.
    • fetchSubscription({ shortCode, keyword, lastReceivedId }): Fetch premium subscription data. shortCode and keyword are REQUIRED.
    • createSubscription({ shortCode, keyword, phoneNumber }): Create a premium subscription. shortCode, keyword, and phoneNumber are REQUIRED.
    // Example: Sending a single SMS
    await sms.send({
      to: '+234xxxxxxxxxx',
      message: 'Hello from Africa\'s Talking!',
      senderId: 'MY_SENDER_ID'
    });
  10. Manage SMS subscriptions

    develop

    The SMS service allows you to manage user subscriptions to specific keywords and shortcodes (often used for opt-in/opt-out flows).

    • createSubscription(params): Registers a phone number to a shortCode and keyword.
    • fetchSubscription(params): Retrieves active subscriptions. Can be filtered by lastReceivedId to paginate or fetch new updates.
    • deleteSubscription(params): Removes a subscription for a specific phoneNumber, shortCode, and keyword.

    Subscription Parameter Requirements:

    • shortCode: The shortcode string (required).
    • keyword: The keyword string (required).
    • phoneNumber: The recipient's phone number (required for create/delete).
    • lastReceivedId: Used in fetchSubscription to track progress.
    // Create a subscription
    await sms.createSubscription({
      shortCode: '12345',
      keyword: 'JOIN',
      phoneNumber: '2547XXXXXXXX'
    });
    
    // Delete a subscription
    await sms.deleteSubscription({
      shortCode: '12345',
      keyword: 'JOIN',
      phoneNumber: '2547XXXXXXXX'
    });