Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
send(message: String, recipients: List, senderId: Optional, enqueue: Optional): Send a bulk message to recipients, optionally from senderId (Short Code or Alphanumeric).
sendPremium(message: String, keyword: String, linkId: String, recipients: List, senderId: Optional, retryDurationInHours: Optional): Send a premium SMS
fetchMessages(lastReceivedId: Optional): Fetch your messages
fetchSubscriptions(shortCode: String, keyword: String, lastReceivedId: Optional): Fetch your premium subscription data
createSubscription(shortCode: String, keyword: String, phoneNumber: String, checkoutToken: String): Create a premium subscription
"""
import africastalking
import unittest
from test import USERNAME, API_KEY
africastalking.initialize(USERNAME, API_KEY)
token_service = africastalking.Token
service = africastalking.SMS
class TestSmsService(unittest.TestCase):
def test_send(self):
res = service.send('test_send()', ['+254718769882', '+254718769881'], enqueue=True, sender_id='AT2FA')
recipients = res['SMSMessageData']['Recipients']
assert len(recipients) == 2
assert recipients[0]['status'] == 'Success'
def test_heavy_single_send(self):
count = 100000
phone_numbers = list(map(lambda x: str("+254718" + str(x + count)), range(1, count)))
"""
Application
fetchApplicationData(): Fetch app info i.e. balance.
"""
import africastalking
import unittest
from test import USERNAME, API_KEY
africastalking.initialize(USERNAME, API_KEY)
service = africastalking.Application
class TestApplicationService(unittest.TestCase):
def test_fetch_account(self):
res = service.fetch_application_data()
assert res['UserData']['balance'] is not None
if __name__ == '__main__':
unittest.main()
"""
Airtime
send(phoneNumber: String, amount: String): Send airtime to a phone number.
send(recipients: Map): Send airtime to a bunch of phone numbers. The keys in the recipients map are phone
numbers while the values are airtime amounts.
"""
import africastalking
import unittest
import random
from test import USERNAME, API_KEY
africastalking.initialize(USERNAME, API_KEY)
service = africastalking.Airtime
class TestAirtimeService(unittest.TestCase):
def test_send_single(self):
currency_code = "KES"
amount = str(random.randint(10, 1000))
phone = '+254718763456'
idempotency_key = 'req-1234'
res = service.send(phone_number=phone, amount=amount, currency_code=currency_code, idempotency_key=idempotency_key)
assert res['numSent'] == 1
def test_send_multiple(self):
res = service.send(recipients=[
{'phoneNumber': '+2348160663047', 'amount': str(random.randint(1, 10)), 'currency_code': 'USD'},
mobileB2C(productName: String, consumers: List): Send mobile money to consumers.
mobileB2B(productName: String, recipient: Business): Send mobile money to a business.
walletTransfer(productName: String, targetProductCode: Integer, amount: String, metadata: Map)
topupStash(productName: String, amount: String, metadata: Map)
"""
import africastalking
import unittest
import random
import time
from test import USERNAME, API_KEY
africastalking.initialize(USERNAME, API_KEY)
service = africastalking.Payment
class TestPaymentService(unittest.TestCase):
def test_mobile_checkout(self):
res = service.mobile_checkout(product_name='TestProduct', phone_number='+254718769882', currency_code="USD", amount=10)
assert res['status'] == 'PendingConfirmation'
def test_mobile_b2c(self):
consumer = {
'name': 'Salama',
'phoneNumber': '+254718769882',
'currencyCode': 'KES',
'amount': 892,
# Optionals
"""
Token
createCheckoutToken(phoneNumber: String): Create a new checkout token for phoneNumber
generateAuthToken(): Generate an auth token to us for authentication instead of the API key.
"""
import africastalking
import unittest
from test import USERNAME, API_KEY
africastalking.initialize(USERNAME, API_KEY)
service = africastalking.Token
class TestTokenService(unittest.TestCase):
def test_create_checkout_token(self):
res = service.create_checkout_token("+254718769882")
assert res['token'] != "None"
def test_generate_auth_token(self):
res = service.generate_auth_token()
assert res['lifetimeInSeconds'] == 3600
if __name__ == '__main__':
unittest.main()
import os
from flask import Flask, request, render_template
from flask_restful import Resource, Api
import africastalking
app = Flask(__name__)
api = Api(app)
username = os.getenv('user_name', 'sandbox')
api_key = os.getenv('api_key', 'fake')
africastalking.initialize(username, api_key)
sms = africastalking.SMS
airtime = africastalking.Airtime
payment = africastalking.Payment
@app.route('/')
def index():
return render_template('index.html')
class send_sms(Resource):
def get(self):
return {'hello': 'world'}
def post(self):
number = str(request.form['number'])
return sms.send("Test message", [number])
api.add_resource(send_sms, '/sms')
def main():
africastalking.initialize(os.getenv('USERNAME', 'sandbox'), os.getenv('API_KEY', 'fake'))
sms = africastalking.SMS
def on_finish(error, data):
if error is not None:
raise error
print('\nAsync Done with -> ' + str(data['SMSMessageData']['Message']))
# Send SMS asynchronously
sms.send('Hello Async', ['+254718769882'], callback=on_finish)
print('Waiting for async result....')
# Send SMS synchronously
result = sms.send('Hello Sync Test', ['+254718769882'])
print('\nSync Done with -> ' + result['SMSMessageData']['Message'])