npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

daraja-multiplatform

v0.0.2

Published

Kotlin Multiplatform API wrapper for the M-Pesa/Daraja API

Downloads

35

Readme

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:

  • [x] Authorization - Gives you a time bound access token to call allowed APIs.
  • [x] M-Pesa Express - Merchant initiated online payments.
  • [x] Dynamic QR - Generates a dynamic M-PESA QR code.
  • [x] Customer To Business (C2B)
  • [ ] Business To Customer (B2C) - Transact between an M-Pesa short code to a phone number registered on M-Pesa.
  • [x] Transaction Status - Check the status of a transaction.
  • [x] 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:
  dependencies {
    implementation("io.github.victorkabata:daraja-multiplatform:0.9.3")
}
  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<DarajaPaymentResponse> = 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
    }

Generate Dynamic QR Code

  • Generate a dynamic m-pesa qr code
val darajaQrCode: DarajaResult<DynamicQrResponse> = daraja.generateDynamicQr(
    merchantName = "TEST SUPERMARKET",
    referenceNumber = "Invoice Test",
    amount = 1,
    transactionCode = DarajaTransactionCode.BG,
    cpi = "373132",
    size = 400
)

darajaQrCode.onSuccess {
    // Successfully generated a QR code in base64 string format
}.onFailure {
    // Failed to generate a QR code
}

Query M-Pesa Transaction

  • To check the status of an M-pesa transaction, invoke the transactionStatus function:
val darajaTransactionResponse: DarajaResult<DarajaTransactionResponse> = daraja.transactionStatus(
    businessShortCode = "174379",
    checkoutRequestID = "ws_CO_20122022180112029708374149"
)

darajaTransactionResponse
    .onSuccess { transactionResponse ->
        // Successfully fetched M-pesa transaction status
    }.onFailure { error ->
        // Failure fetching M-pesa transaction 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

https://github.com/VictorKabata/DarajaSwiftPackage/assets/39780120/b9283612-3c5e-4100-aff8-c2c0d9f31863

  • 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
    })

Generate Dynamic QR Code

  • Generate a dynamic m-pesa qr code
var darajaQrCode= daraja.generateDynamicQr(
    merchantName = "TEST SUPERMARKET",
    referenceNumber = "Invoice Test",
    amount = 1,
    transactionCode = DarajaTransactionCode.BG,
    cpi = "373132",
    size = 400
)

darajaQrCode.onSuccess(action:{data in 
// Successfully generated a QR code in base64 string format
})
.onFailure(action: {error in 
// Failed to generate a QR code
})

Query M-Pesa Transaction

  • To check the status of an M-pesa transaction, invoke the transactionStatus function:
var darajaTransactionResponse = daraja.transactionStatus(
  businessShortCode: "174379", checkoutRequestID: "ws_CO_20122022180112029708374149")

darajaTransactionResponse.onSuccess(action: { data in
  // Successfully fetched M-pesa transaction status
}).onFailure(action: { error in
  // Failure fetching M-pesa transaction status
})

Account Balance

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

    var 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(action: { data in
    // Successfully request account balance
}).onFailure(action: { error in
    // Failed to request account balance
})