Skip to content

Kotlin Multiplatform wrapper for Daraja(M-Pesa) API for Kotlin and Swift clients

Notifications You must be signed in to change notification settings

VictorKabata/DarajaMultiplatform

Repository files navigation

Daraja Multiplatform

⚠️Work in progress - Sandbox Mode⚠️

Kotlin multiplatform wrapper for Mpesa API dubbed Daraja API (Daraja means bridge in Swahili) that supports integration with your Android(Kotlin/Java), iOS(Swift) and JVM applications.

M-PESA is a mobile money transfer service in Kenya that allows users to store and transfer money through their mobile phones.

Table of Content

Prerequisite

To get started, you’ll need to create an account on the Daraja API portal to use the Daraja API. How to get started with Daraja API.

After successfully creating an account on the Daraja API portal and creating a new Daraja app, you’ll need to add your consumer key, consumer secret and pass key obtained from the Daraja API portal to your project.

Features

The SDK offers the following functionalities from the Daraja API:

  • Authorization - Gives you a time bound access token to call allowed APIs.
  • M-Pesa Express - Merchant initiated online payments.
  • M-Pesa Express Query - Check the status of a Lipa Na M-Pesa Online Payment(M-Pesa Express).
  • Dynamic QR - Generates a dynamic M-PESA QR code.
  • Customer To Business (C2B)
  • Business To Customer (B2C) - Transact between an M-Pesa short code to a phone number registered on M-Pesa.
  • Transaction Status - Check the status of a transaction.
  • Account Balance - Enquire the balance on an M-Pesa BuyGoods (Till Number)
  • Reversal - Reverses an M-Pesa transaction.
  • Tax Remittance - This API enables businesses to remit tax to Kenya Revenue Authority (KRA).
  • Business Pay Bill - Pay bills directly from your business account to a pay bill number, or a paybill store.
  • Business Buy Goods - Pay for goods and services directly from your business account to a till number or merchant store number.

Usage

Android - Kotlin

Setting Up

  • In your android application project-level gradle file add the following dependency:
Kotlin
  dependencies {
    implementation("io.github.victorkabata:daraja-multiplatform:0.9.3")
}
Groovy
  dependencies {
    implementation 'io.github.victorkabata:daraja-multiplatform:0.9.3'
}
  • Add your consumer secret, consumer key and pass key to your project. You can get them from the Daraja API portal.

You should not add your daraja API environment variables in a production application because it is a vulnerability to expose your environment secrets/variables in your version control system. Ideally, you should add them to your local.properties files as demonstrated in the sample android application.

  • Create an instance of the Daraja object by passing the daraja environment variables. The daraja object provides functions to request for an access token and initiate M-Pesa express STK request.
val daraja: Daraja = Daraja.Builder()
    .setConsumerSecret("your_consumer_secret")
    .setConsumerKey("your_consumer_key")
    .setPassKey("your_pass_key")
    .isProduction() // Optional. Will default to sandbox_mode = true
    .build()

Network logging is enabled by default when using Daraja Multiplatform. in sandbox/testing mode. The logs can be accessed from the logcat in Android Studio under the Daraja Multiplatform tag.

Network logs are disabled in production mode.

Request Access Token

  • To request an access token from Daraja API, invoke the authorization function:
val accessTokenResult: DarajaResult<DarajaToken> = daraja.authorization()

accessTokenResult
    .onSuccess { accessToken ->
        // Successfully fetched daraja access token
    }
    .onFailure { error ->
        // Failure fetching daraja access token
    }

Initiate M-Pesa Express STK Request

  • To initiate M-Pesa Express(Lipa na M-Pesa Online) STK request, invoke the mpesaExpress function:
val darajaPaymentResponse: DarajaResult<MpesaExpressResponse> = daraja.mpesaExpress(
    businessShortCode = "174379",
    amount = 1,
    phoneNumber = "07xxxxxxxx",
    transactionDesc = "M-Pesa payment",
    callbackUrl = "your_callback_url",
    accountReference = "CompanyName"
)

darajaPaymentResponse.onSuccess { paymentResponse ->
    // Successfully requested M-Pesa STK request
}.onFailure { error ->
    // Failed to request M-Pesa STK
}

Query M-Pesa Express STK

  • To check the status of M-Pesa Express(Lipa na M-Pesa Online) STK request, invoke the mpesaExpressQuery function:
val darajaMpesaExpressQuery:DarajaResult<QueryMpesaExpressResponse> = daraja.mpesaExpressQuery(
    businessShortCode = "174379",
    timeStamp = "20160216165627",
    checkOutRequestID = "ws_CO_260520211133524545"
)

darajaMpesaExpressQuery.onSuccess{ mpesaExpressQuery->
    // Successfully request M-Pesa STK request status
}.onFailure{ error->
    // Failed to request M-Pesa STK status
}

Customer To Business(C2B)

  • To register the C2B validation and confirmation URL, invoke the c2bRegistration function:
val darajaC2BRegistrationResponse: DarajaResult<C2BResponse> = daraja.c2bRegistration(
    confirmationURL = "https://mydomain.com/confirmation",
    responseType = C2BResponseType.COMPLETED, // C2BResponseType.CANCELLED
    businessShortCode = 600981,
    validationURL = "https://mydomain.com/validation"
)

darajaC2BRegistrationResponse.onSuccess {
    // Successfully registered  confirmation and validation URL
}.onFailure {
    // Failure registering confirmation and validation URL
}
  • To initiate a Customer to Business paybill, invoke the c2b function:
val c2bResponse: DarajaResult<C2BResponse> = daraja.c2b(
    amount = 1,
    billReferenceNumber = "600977",
    transactionType = DarajaTransactionType.CustomerBuyGoodsOnline, // DarajaTransactionType.CustomerPayBillOnline
    phoneNumber = "0708374149",
    businessShortCode = "600977" //Optional when using CustomerBuyGoodsOnline
)

c2bResponse.onSuccess {
    // Successfully invoked C2B request
}.onFailure {
    // Failure invoking C2B request
}

Account Balance

Request the account balance of a short code. This can be used for both B2C, buy goods and pay bill accounts.

    val accountBalanceResponse = daraja.accountBalance(
    initiator = "testapi",
    initiatorPassword = "Safaricom999!*!",
    partyA = 600987,
    identifierType = DarajaIdentifierType.TILL_NUMBER,
    queueTimeOutURL = "https://mydomain.com/AccountBalance/queue/",
    resultURL = "https://mydomain.com/AccountBalance/result/"
)

accountBalanceResponse.onSuccess {
    // Successfully request account balance
}.onFailure {
    // Failed to request account balance
}

iOS - Swift

Setting Up

  • To add DarajaMultiplatform package to your Xcode Project, open your Xcode project, navigate to the File tab within the macOS bar and click Select Packages then **Add Package Dependency **. Enter the package name ie. DarajaMultiplatform or the URL package GitHub URL:
https://github.com/VictorKabata/DarajaSwiftPackage.git
add_spm.mp4
  • Create an instance of the Daraja object by passing the daraja environment variables. The daraja object provides functions to request for an access token and initiate M-Pesa express STK request.
var daraja=Daraja(
        consumerKey: "your_consumer_key",
        consumerSecret: "your_customer_secret",
        passKey:"your_pass_key",
        environment: DarajaEnvironment.sandboxEnvironment
        )

Network logging is enabled by default when using Daraja Multiplatform. in sandbox/testing mode. The logs can be accessed from the logs in XCode IDE

Network logs are strictly disabled in production mode ie. DarajaEnvironment.productionEnvironment

Request Access Token

  • To request an access token from Daraja API, invoke the authorization function:
var accessTokenResult = daraja.authorization()

accessTokenResult.onSuccess(action: { accessToken in
    // Successfully fetched daraja access token
        // Successfully fetched the access token
    }).onFailure(action: { error in
     // Failure fetching daraja access token
    })

Initiate M-Pesa Express STK Request

  • To initiate M-Pesa Express(Lipa na M-Pesa Online) STK request, invoke the mpesaExpress function:
var darajaResponse = daraja.mpesaExpress(
  businessShortCode: "174379",
  amount: 1,
  phoneNumber: "07xxxxxxxx",
  transactionType: DarajaTransactionType.customerpaybillonline, transactionDesc: "M-Pesa payment",
  callbackUrl: "https://mydomain.com/path",
  accountReference: "Company name")

  darajaResponse.onSuccess(action: { data in
    // Successfully requested M-Pesa STK request
    })
    .onFailure(action: { error in
    // Failed to request M-Pesa STK
    })

Query M-Pesa Express STK

  • To check the status of M-Pesa Express(Lipa na M-Pesa Online) STK request, invoke the mpesaExpressQuery function:
var mpesaExpressQuery = daraja.mpesaExpressQuery(
    businessShortCode: "174379",
    timestamp: "20160216165627",
    checkoutRequestID: "ws_CO_260520211133524545"
)

mpesaExpressQuery.onSuccess(action:{ data in
// Successfully requested M-Pesa STK request status
})
.onFailure(action: {error in
// Failed to request M-Pesa STK status
})

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •