The SDK provides convenient access to the Africa's Talking API from applications written in Java.
Android Users: Remember your API key has to be kept secret; hard-coding it into an apk you publish is a security risk. So on Android, use the Android SDK instead.
Take a look at the API docs here.
You can depend on the .jar through Maven (from http://dl.bintray.com/africastalking/java
):
<dependency>
<groupId>com.africastalking</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
or sbt:
resolvers += "africastalking maven repository" at "http://dl.bintray.com/africastalking/java"
// Get all services
libraryDependencies += "com.africastalking" % "core" % "3.4.0"
or Gradle:
repositories {
maven {
url "http://dl.bintray.com/africastalking/java"
}
}
dependencies{
// Get all services
compile 'com.africastalking:core:3.4.0'
}
The SDK needs to be initialized with your app username and API key, which you get from the dashboard.
You can use this SDK for either production or sandbox apps. For sandbox, the app username is ALWAYS
sandbox
// Initialize
String username = "YOUR_USERNAME"; // use 'sandbox' for development in the test environment
String apiKey = "YOUR_API_KEY"; // use your sandbox app API key for development in the test environment
AfricasTalking.initialize(username, apiKey);
// Initialize a service e.g. SMS
SmsService sms = AfricasTalking.getService(AfricasTalking.SERVICE_SMS);
// Use the service
List<Recipient> response = sms.send("Hello Message!", new String[] {"+2547xxxxxx"}, true);
See example for more usage examples.
The following static methods are available on the AfricasTalking
class to initialize the library:
-
initialize(string username, String apiKey)
: Initialize the library. -
setLogger(Logger)
: Set logging object. -
getService(Service.class | AfricasTalking.SERVICE_*)
: Get an instance to a given service by name or by class:- SMS Service:
AfricasTalking.getService(AfricasTalking.SERVICE_SMS)
- Airtime Service:
AfricasTalking.getService(AfricasTalking.SERVICE_AIRTIME)
- Payment Service:
AfricasTalking.getService(AfricasTalking.SERVICE_PAYMENT)
- Voice Service:
AfricasTalking.getService(AfricasTalking.SERVICE_VOICE)
- Token Service:
AfricasTalking.getService(AfricasTalking.SERVICE_TOKEN)
- Application Service:
AfricasTalking.getService(AfricasTalking.SERVICE_APPLICATION)
- SMS Service:
Note on USSD: For more information, please read http://docs.africastalking.com/ussd
All methods are synchronous (i.e. will block current thread) but provide asynchronous variants that take a com.africastalking.Callback<?>
as the last argument.
All phone numbers use the international format. e.g. +234xxxxxxxx
.
fetchApplicationData()
: Get app information. e.g. balance
-
send(String phoneNumber, String currencyCode, float amount)
: Send airtime to a phone number. Example amount would beKES 150
. -
send(HashMap<String,String> recipients)
: Send airtime to many of phone numbers. The keys in therecipients
map are phone numbers while the values are airtime amounts. The amounts need to have currency info e.g.UXG 4265
.
For more information about status notification, please read http://docs.africastalking.com/airtime/callback
-
send(String message, String from, String[] recipients, boolean enqueue)
: Send a message.message
: SMS contentfrom
: Shortcode or alphanumeric ID that is registered with Africa's Talking account.recipients
: An array of phone numbers.enqueue
: Set to true if you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.
-
sendPremium(String message, String keyword, String linkId, long retryDurationInHours, String[] recipients)
: Send a premium SMSmessage
: SMS contentkeyword
: You premium product keywordlinkId
: "[...] We forward thelinkId
to your application when the user send a message to your service"retryDurationInHours
: "It specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber"recipients
: An array of phon numbers.
-
fetchMessages(long lastReceivedId)
: Fetch your messageslastReceivedId
: "This is the id of the message that you last processed". Defaults to0
-
fetchSubscriptions(String shortCode, String keyword, long lastReceivedId)
: Fetch your premium subscription data.shortCode
: This is the premium short code mapped to your account.keyword
: A premium keyword under the above short code and mapped to your account.lastReceivedId
: "This is the id of the message that you last processed". Defaults to0
-
createSubscription(String shortCode, String keyword, String phoneNumber, String checkoutToken)
: Create a premium subscription.shortCode
: This is the premium short code mapped to your account.keyword
: A premium keyword under the above short code and mapped to your account.phoneNumber
: The phone number to be subscribedcheckoutToken
: This is a token used to validate the subscription request. SeeTokenService
-
deleteSubscription(String shortCode, String keyword, String phoneNumber)
: Remove a phone number from a premium subscription.shortCode
: This is the premium short code mapped to your account.keyword
: A premium keyword under the above short code and mapped to your account.phoneNumber
: The phone number to be unsubscribed
For more information on:
- How to receive SMS: http://docs.africastalking.com/sms/callback
- How to get notified of delivery reports: http://docs.africastalking.com/sms/deliveryreports
- How to listen for subscription notifications: http://docs.africastalking.com/subscriptions/callback
-
cardCheckoutCharge(String productName, String currencyCode, float amount, PaymentCard paymentCard, String narration, Map metadata)
: Initiate card checkout charge.productName
: Your payment productcurrencyCode
: Currency code e.g. NGNamount
: Amount to chargepaymentCard
: Card to charge. See PaymentCard class.narration
: Checkout descriptionmetadata
: Additional info to go with the checkout
-
cardCheckoutValidate(String transactionId, String otp)
: Validate a card checkouttransactionId
: Transaction ID returned on charge requestotp
: A user-provided OTP
-
bankCheckoutCharge(String productName, String currencyCode, float amount, BankAccount bankAccount, String narration, Map metadata)
: Initiate bank checkout.productName
: Your payment productcurrencyCode
: Currency code e.g. NGNamount
: Amount to chargebankAccount
: Bank account to charge. See BankAccount class.narration
: Checkout descriptionmetadata
: Additional info to go with the checkout
-
bankCheckoutValidate(String transactionId, String otp)
: Validate a bank checkouttransactionId
: Transaction ID returned on charge requestotp
: A user-provided OTP
-
bankTransfer(String productName, List<Bank> recipients)
: Move money form payment wallet to bank accountproductName
: Your payment productrecipients
: A list of banks to transfer to. See Bank class
-
mobileCheckout(String productName, String phoneNumber, String currencyCode, float amount)
: Initiate mobile checkout.productName
: Your payment productphoneNumber
: Mobile wallet to chargecurrencyCode
: Currency code e.g. KESamount
: Amount to charge
-
mobileB2C(String productName, List<Consumer> recipients)
: Send mobile money to consumer.productName
: Your payment productrecipients
: A list of consumers that will receive the money. See Consumer class.
-
mobileB2B(String productName, Business recipient)
: Send mobile money to business.productName
: Your payment productrecipient
: A business recipint of the money. See Business class
-
walletTransfer(String productName, long targetProductCode, String currencyCode, float amount, HashMap<String, String> metadata)
: Move money form one payment product to another.productName
: Your payment producttargetProductCode
: ID of recipient payment product on Africa's TalkingcurrencyCode
: Currency code e.g. RWFamount
: Amount to transfermetadata
: Additional info to go with the transfer
-
topupStash(String productName, String currencyCode, float amount, HashMap<String, String> metadata)
: Move money from payment product to app's stash.productName
: Your payment productcurrencyCode
: Currency code e.g. KESamount
: Amount to transfermetadata
: Additional info to go with the transfer
-
fetchProductTransactions(String productName, HashMap<String, String> filters)
: Fetch payment product transactions.-
productName
: Your payment product -
filters
: Query filters. Includes:pageNumber
: Page number to fetch results from. Starts from1
.REQUIRED
count
: Number of results to fetch.REQUIRED
startDate
: Start Date to consider when fetching.endDate
: End Date to consider when fetching.category
: Category to consider when fetching.prodiver
: Provider to consider when fetching.status
: Status to consider when fetching.source
: Source to consider when fetching.destination
: Destination to consider when fetching.providerChannel
: Provider channel to consider when fetching.
-
-
findTransaction(String transactionId)
: Find a particular transaction. -
fetchWalletTransactions(HashMap<String, String> filters)
: Fetch wallet transactions.filters
: Query filter. Includes:pageNumber
: Page number to fetch results from. Starts from1
.REQUIRED
count
: Number of results to fetch.REQUIRED
startDate
: Start Date to consider when fetching.endDate
: End Date to consider when fetching.categories
: Comma delimited list of categories to consider when fetching.
-
fetchWalletBalance()
: Fetch your wallet's balance
For more information, please read http://docs.africastalking.com/payments
-
call(String phoneNumber)
: Initiate a phone callphoneNumber
: Phone number to call
-
fetchQueuedCalls(String phoneNumber)
: Get queued calls on a phone number.phoneNumber
: Your Africa's Talking issued virtual phone number
-
uploadMediaFile(String phoneNumber, String url)
: Upload voice media filephoneNumber
: Your Africa's Talking issued virtual phone numberurl
: URL to your media file.
-
ActionBuilder
: Build voice xml when callback URL receives aPOST
from Africa's Talking-
say()
: Add aSay
action. -
play()
: Add aPlay
action. -
getDigits()
: Add aGetDigits
action. -
dial()
: Add aDial
action. -
conference()
: Add aConferemce
action. -
record()
: Add aRecord
action. -
enqueue()
: Add aEnqueue
action. -
dequeue()
: Add aDequeue
action. -
reject()
: Add aReject
action. -
redirect()
: Add aRedirect
action. -
build()
: Finally build the xml
-
For more information, please read http://docs.africastalking.com/voice
-
createCheckoutToken(String phoneNumber)
: Create a new checkout token forphoneNumber
. -
generateAuthToken()
: Generate an auth token to use for authentication instead of an API key.
$ git clone https://github.com/aksalj/africastalking-java.git
$ cd africastalking-java
$ touch local.properties
Make sure your local.properties
file has the following content then run ./gradlew build
# AT API
api.username=sandbox
api.key=some_key
# Bintray
bintray.user=fake
bintray.key=fake
bintray.repo=fake
bintray.organization=fake
bintray.package=fake
bintray.groupId=fake
bintray.version=fake
bintray.vscUrl=fake
If you find a bug, please file an issue on our issue tracker on GitHub.