Skip to main content

Official Africa's Talking Python SDK

Project description

image0

The SDK provides convenient access to the Africa’s Talking APIs to python apps.

Documentation

Take a look at the API docs here.

Install

$ pip  install africastalking # python 2.7.x

OR

$ python -m pip install africastalking # python 2.7.x

OR

$ pip3 install africastalking # python 3.6.x

OR

$ python3 -m pip install africastalking # python 3.6.x

Usage

The package needs to be configured with your app 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

# import package
import africastalking


# Initialize SDK
username = "YOUR_USERNAME"    # use 'sandbox' for development in the test environment
api_key = "YOUR_API_KEY"      # use your sandbox app API key for development in the test environment
africastalking.initialize(username, api_key)


# Initialize a service e.g. SMS
sms = africastalking.SMS


# Use the service synchronously
response = sms.send("Hello Message!", ["+2547xxxxxx"])
print(response)

# Or use it asynchronously
def on_finish(error, response):
    if error is not None:
        raise error
    print(response)

sms.send("Hello Message!", ["+2547xxxxxx"], callback=on_finish)

See example for more usage examples.

Initialization

Initialize the SDK by calling africastalking.initialize(username, api_key). After initialization, you can get instances of offered services as follows:

Services

All methods are synchronous (i.e. will block current thread) but provide asynchronous variants that take a callback function (error: AfricasTalkingException, data: dict).

The synchronous variant always return and instance a dict while the async one returns a Thread.

All phone numbers use the international format. e.g. +234xxxxxxxx.

All amount strings contain currency code as well. e.g. UGX 443.88.

ApplicationService

  • fetch_application_data(): Get app balance info.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
application = africastalking.Application
res = application.fetch_application_data()

AirtimeService

  • send(phone_number: str, amount: str): Send airtime to a phone number. An example amount would be KES 150.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
airtime = africastalking.Airtime
res = airtime.send(phone_number='+254718769882', amount='KES 908')
  • send(recipients: [dict]): Send airtime to a list of phone numbers. The keys in the recipients dictionary are phone numbers while the values are airtime amounts. The amounts need to have currency info e.g. UXG 4265.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
airtime = africastalking.Airtime
res = airtime.send(recipients=[
            {'phoneNumber': '+2348160663047', 'amount': 'NGN 1535' },
            {'phoneNumber': '+254718769881', 'amount': 'KES 733'},
])

For more information about status notification, please read http://docs.africastalking.com/airtime/callback

SmsService

  • send(message: str, recipients: [str], sender_id: str = None, enqueue: bool = False): Send a bulk message to recipients, optionally from sender_id (Short Code or Alphanumeric).

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
sms = africastalking.SMS
res = sms.send(message='hello', recipients=['+254718769882'])
  • send_premium(message: str, keyword: str, link_id: str, recipients: [str]): Send a premium SMS

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
sms = africastalking.SMS
res = sms.send_premium(message='hello', keyword='music', link_id='233dddd', recipients=['+254718769882'])
  • fetch_messages(last_received_id: int = 0): Fetch your messages

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
sms = africastalking.SMS
res = sms.fetch_messages()
  • fetch_subscriptions(short_code: str, keyword: str, last_received_id: int = 0): Fetch your premium subscription data

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
sms = africastalking.SMS
res = sms.fetch_subscriptions(short_code='6673', keyword='music')
  • create_subscription(short_code: str, keyword: str, phone_number: str, checkout_token: str): Create a premium subscription

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
sms = africastalking.SMS
token = africastalking.Token
res = token.create_checkout_token(phone_number='+254718767882')
checkout_token = res['token']
res = sms.create_subscription(short_code='6673', keyword='music', phone_number='+254718767882', checkout_token=checkout_token)

For more information on:

PaymentService

  • card_checkout(product_name: str, currency_code:str, amount: float, payment_card: dict, narration: str, metadata: dict = {}): Initiate card checkout.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
card = {
    'number': '3234324235452345',
    'countryCode': 'NG',
    'cvvNumber': 3343,
    'expiryMonth': 3, # 1-12
    'expiryYear': 2022, # > 2018
    'authToken': '3322' # card pin
}
res = payment.card_checkout(product_name='TestProduct', currency_code='NGN', amount=7822, payment_card=card, narration='Small Chops Checkout')
  • validate_card_checkout(transaction_id: str, otp: str): Validate a card checkout

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
res = payment.validate_card_checkout(transaction_id='ATId_3829u49283u423u', otp='233333')
  • bank_checkout(product_name: str, currency_code: str, amount: float, bank_account: dict, narration: str, metadata: dict = {}): Initiate bank checkout.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
account = {
    'accountNumber': '3234324235452345',
    'bankCode': payment.BANK['FCMB_NG'],
    'accountName': 'Fake Bob Naija',
    # Optional YYYY-MM-DD // required only for Zenith Nigeria
    #'dateOfBirth': '2000-01-01'
}
res = payment.bank_checkout(product_name='TestProduct', currency_code='NGN', amount=7822, bank_account=account, narration='Small Chops Checkout')
  • validate_bank_checkout(transaction_id: str, otp: str): Validate a bank checkout

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
res = payment.validate_bank_checkout(transaction_id='ATId_3829u492SQSW383u423u', otp='AA22w33')
  • bank_transfer(product_name: str, recipients: [dict]): Move money form payment wallet to bank account.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
recipients = [
    {
      "bankAccount": {
        "accountNumber": "3234324235452345",
        "bankCode": payment.BANK['FCMB_NG'],
        "accountName": "Fake Bob Naija"
      },
      "currencyCode": "NGN",
      "amount": 332434,
      "narration": "Some description",
      "metadata": {}
    }
]
res = payment.bank_transfer(product_name='TestProduct', recipients=recipients)
  • wallet_transfer(product_name: str, target_product_code: int, currency_code: str, amount: float, metadata: dict): Transfer money from one Payment Product to another Payment Product hosted on Africa’s Talking.

.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
res = payment.wallet_transfer(product_name='TestProduct', target_product_code=2009, currency_code='KES', amount=7732, metadata={'ID': '23GG')
  • topup_stash(product_name: str, currency_code: str, amount: float, metadata: dict): Move money from a Payment Product to an app’s stash.

.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
res = payment.topup_stash(product_name='TestProduct', currency_code='KES', amount=7732, metadata={'ID': '23GG')
  • mobile_checkout(product_name: str, phone_number: str, currency_code: str, amount: float, metadata: dict = {}): Initiate mobile checkout. An example amount would be KES 323

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
res = payment.mobile_checkout(product_name='TestProduct', currency_code='KES', amount=565)
  • mobile_b2c(product_name: str, consumers: [dict]): Send mobile money to consumer. Each consumer is a dict of this format:

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
consumers = [
    {

      "name": "Bob Mwangi",
      "phoneNumber": "+254718769882",
      "currencyCode": "KES",
      "amount": 6766.88,
      "providerChannel": "1212",
      "reason": 'SalaryPayment',
      "metadata": {}
    }
]
res = payment.mobile_b2c(product_name='TestProduct', consumers=consumers)
  • mobile_b2b(product_name: str, business: dict): Send mobile money to business.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
payment = africastalking.Payment
business = {
  "currencyCode": "KES",
  "amount": 6766.88,
  "destinationChannel": "1212",
  "destinationAccount": "ABC",
  "provider": 'Mpesa',
  "transferType": 'BusinessBuyGoods',
  "metadata": {}
}
res = payment.mobile_b2b(product_name='TestProduct', business=business)

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

VoiceService

  • call(source: str, destination: str): Initiate a phone call

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
voice = africastalking.Voice
res = voice.call(source="+254718769881", destination="+254718769880")
  • fetch_queued_calls(phone_number: str): Get queued calls

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
voice = africastalking.Voice
res = voice.fetch_queued_calls(phone_number="+2548933373")
  • upload_media_file(phone_number: str, url: str): Upload voice media file

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
voice = africastalking.Voice
res = voice.upload_media_file(phone_number="+2548933373", url="https://www.my-site.zr/my_fil.mp3")

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

TokenService

  • create_checkout_token(phone_number: str): Create a new checkout token for phone_number.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
token = africastalking.Token
res = token.create_checkout_token("+254787633677")
  • generate_auth_token(): Generate an auth token to use for authentication instead of an API key.

import africastalking
africastalking.initialize(username='sandbox', api_key='someKey')
token = africastalking.Token
res = token.generate_auth_token()

UssdService

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

Development

$ git clone https://github.com/aksalj/africastalking-python.git
$ cd africastalking-python
$ touch .env

Make sure your .env file has the following content then run python -m unittest discover -v

# AT API
USERNAME=sandbox
API_KEY=some_key

Issues

If you find a bug, please file an issue on our issue tracker on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

africastalking-1.1.2.tar.gz (13.9 kB view details)

Uploaded Source

File details

Details for the file africastalking-1.1.2.tar.gz.

File metadata

File hashes

Hashes for africastalking-1.1.2.tar.gz
Algorithm Hash digest
SHA256 78a978727be7aab0d19401a68fc43f2ad81c85cefadf6e0f5e36f37bd88f5ff7
MD5 402c986abdf005029c3cdae3c1ee3c1a
BLAKE2b-256 e0c67d3108ec3d1452d8e402cc8bb9e918d3d74d1ce7fcdaaf94c87ac6163199

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page