maina-david/multi-shortcode-mpesa 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

maina-david/multi-shortcode-mpesa

Composer 安装命令:

composer require maina-david/multi-shortcode-mpesa

包简介

Multiple shortcode mpesa integration

README 文档

README

This package seeks to help php developers implement the various Mpesa APIs without much hustle. It is based on the REST API whose documentation is available on https://developer.safaricom.co.ke.

It supports multiple shortcodes on both sandbox and production environments.

Installation

You can install the PHP SDK via composer or by downloading the source

Via Composer

The recommended way to install the SDK is with Composer.

composer require maina-david/multi-shortcode-mpesa

Optional: The service provider will automatically get registered. Or you may manually add the service provider in your config/app.php file:

'providers' => [
    // ...
    MainaDavid\MultiShortcodeMpesa\MpesaServiceProvider::class,
];

You should publish the shortcode migration and the config/multi-shortcode-mpesa.php config file with:

php artisan vendor:publish --provider="MainaDavid\MultiShortcodeMpesa\MpesaServiceProvider"

You can overwrite the default urls in config/multi-shortcode-mpesa.php file.

Clear your config cache. This package requires access to the multi-shortcode-mpesa config. Generally it's bad practice to do config-caching in a development environment. If you've been caching configurations locally, clear your config cache with either of these commands:

 php artisan optimize:clear
 # or
 php artisan config:clear

Run the migrations: After the config and migration have been published and configured, you can create the tables for this package by running:

 php artisan migrate

Usage

The SDK needs to be instantiated using one of your shortcode saved in the short_codes table and expects following values to be encrypted when storing them in the database for security reasons. It will decrypt the values, if unable it will throw an error.

  • consumer_key.
  • consumer_secret.
  • pass_key.
  • initiator_name.
  • initiator_password.

Example saving a shortcode to the database

use MainaDavid\MultiShortcodeMpesa\Models\ShortCode;

    /**
     * It validates the request, creates a new shortcode object, encrypts the sensitive data and saves it
     * to the database
     *
     * @param Request request The request object.
     *
     * @return A JSON response with a success message.
     */
    public function storeShortCode(Request $request)
    {
        /* Validating the request. */
        $request->validate([
            'environment' => 'required|in:sandbox,production',
            'direction' => 'required|in:c2b,b2c',
            'shortcode' => 'required|integer',
            'consumer_key' => 'required',
            'consumer_secret' => 'required',
            'pass_key' => 'required_if:direction,c2b',
            'initiator_name' => 'required_if:direction,b2c',
            'initiator_password' => 'required_if:direction,b2c',
        ]);

        $shortcode = new ShortCode();
        $shortcode->environment = $request->environment; //sandbox or production
        $shortcode->direction = $request->direction; // c2b or b2c
        $shortcode->shortcode = $request->shortcode; // mpesa shortcode
        $shortcode->consumer_key = encrypt($request->consumer_key); // shortcode consumer key
        $shortcode->consumer_secret = encrypt($request->consumer_secret); // shortcode consumer secret
        /* Checking if the request has a pass_key and if it does, it encrypts it and saves it to the database. */
        if ($request->has('pass_key')) {
            $shortcode->pass_key = encrypt($request->pass_key); // not required for b2c
        }
        /* Checking if the request has an initiator name and if it does, it encrypts it and saves it to the
        database. */
        if ($request->has('initiator_name')) {
            $shortcode->initiator_name = encrypt($request->initiator_name);  // shortcode api initiator
        }
        /* Checking if the request has an initiator password and if it does, it encrypts it and saves it to the
        database. */
        if ($request->has('initiator_password')) {
            $shortcode->initiator_password = encrypt($request->initiator_password); // shortcode initiator password
        }
        $shortcode->save();

        return response()->json([
            'success' => true,
            'message' => 'Shortcode saved successfully!'
        ], 200);
    }

You can use this SDK for either production or sandbox apps. For sandbox, the shortcode environment is ALWAYS sandbox

Authorization is done by the SDK for both sandbox and production environments. You can use multiple shortcodes with different environments seamlessly.

Content

  • stkPush($phonenumber, $amount, $reference = '', $description = ''): Initiates an STK push transaction

    • phonenumber: The phone number sending money. REQUIRED
    • amount: This is the Amount to be transacted. Only whole numbers are supported. REQUIRED
    • reference: This is an Identifier of the transaction for CustomerPayBillOnline transaction type. OPTIONAL
    • description: This is any additional comment that can be sent along with the request. OPTIONAL
  • stkPushQuery($CheckoutRequestID): Returns the status of the transaction

    • CheckoutRequestID: The unique identifier of the processed checkout transaction request. REQUIRED
  • b2c($commandID, $amount, $phonenumber, $remarks): Sends money from your business to a customer

    • commandID: Unique command that specifies B2C transaction type [SalaryPayment,BusinessPayment,PromotionPayment]. REQUIRED
    • phonenumber: Customer mobile number to receive the amount. REQUIRED
    • amount: The amount of money being sent to the customer. Only whole numbers are supported. REQUIRED
    • remarks: Any additional information to be associated with the transaction. REQUIRED
  • transactionStatus($TransactionID): It returns the status of a transaction

    • TransactionID: Unique identifier to identify a transaction on Mpesa. REQUIRED
  • reverseTransaction($TransactionID, $amount): It reverses a transaction

    • TransactionID: Unique identifier to identify a transaction on Mpesa. REQUIRED

Lipa na Mpesa Online

use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

// Phone numbers are transformed to the required format by the sdk so no worries about the formatting
$phonenumber = '0722123456';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

// Use stkpush service
$result = $mpesa->stkPush($phonenumber, $amount);

print_r($result);

Check the status of a Lipa Na M-Pesa Online Payment

use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$CheckoutRequestID = 'ws_CO_260520211133524545';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->stkPushQuery($CheckoutRequestID);

print_r($result);

Business to Customers (Pay Outs)

use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$phonenumber = '0722123456';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->b2c($commandID, $amount, $phonenumber, $remarks);

print_r($result);

Check the status of a transaction

use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$TransactionID = 'QWERTY123456789';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->transactionStatus($TransactionID);

print_r($result);

Reverse a transaction

use MainaDavid\MultiShortcodeMpesa\Mpesa;

// Mpesa shortcode
$shortcode = '12345';

$TransactionID = 'QWERTY123456789';

// Instantiate the class
$mpesa  = new Mpesa($shortcode);

$result = $mpesa->reverseTransaction($TransactionID);

print_r($result);

Example SDK responses

The SDK will return a response with either success or error in the below format.

Success response

{
  "status": "success",
  "data": {
    "ConversationID": "AG_20230108_2010364679d05de418cd",
    "OriginatorConversationID": "12425-164354829-1",
    "ResponseCode": "0",
    "ResponseDescription": "Accept the service request successfully."
  }
}

Error response

{
  "status": "error",
  "data": "Shortcode does not support Business to Customer!"
}

maina-david/multi-shortcode-mpesa 适用场景与选型建议

maina-david/multi-shortcode-mpesa 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 01 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「balance」 「mpesa」 「B2C」 「c2b」 「mpesa-express」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 maina-david/multi-shortcode-mpesa 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 maina-david/multi-shortcode-mpesa 我们能提供哪些服务?
定制开发 / 二次开发

基于 maina-david/multi-shortcode-mpesa 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 11
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 37
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-01-07