ongudidan/mpesa-sdk 问题修复 & 功能扩展

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

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

ongudidan/mpesa-sdk

Composer 安装命令:

composer require ongudidan/mpesa-sdk

包简介

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 http://developer.safaricom.co.ke.

README 文档

README

Overview

mpesa-sdk is a lightweight PHP SDK that simplifies integration with Safaricom's M-Pesa Daraja API. It supports B2C, B2B, C2B, STK Push, reversals, transaction status, account balance, and more.

This SDK is framework-agnostic, meaning you can use it with Laravel, Symfony, Yii, CodeIgniter, or even plain/vanilla PHP.

📦 Installation

Install via Composer:

composer require ongudidan/mpesa-sdk

⚙️ Configuration

You'll need:

  • Consumer Key & Consumer Secret — from Safaricom Developer Portal
  • An M-Pesa API User (Initiator) created from your Safaricom Business account
  • Password for that Initiator

You can pass credentials directly in the data array or load them using environment variables/configuration.

🚀 Usage Examples

✅ B2C (Business to Customer)

Send funds from your BusinessShortCode to a customer's phone.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'Initiator' => 'API user created on Safaricom Business dashboard',
    'InitiatorPassword' => 'Password of the API user',
    'CommandID' => 'BusinessPayment', // or SalaryPayment, PromotionPayment
    'Amount' => '100', // Amount to send
    'PartyA' => '600XXX', // Your BusinessShortCode
    'PartyB' => '2547XXXXXXXX', // Customer phone number
    'Remarks' => 'Salary payment',
    'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
    'ResultURL' => 'https://yourdomain.com/result',
    'Occasion' => 'JunePayroll',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->b2c($data);

💼 Account Balance

Check your Paybill/Till balance.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'IdentifierType' => '4', // 1: BusinessShortCode, 2: Till, 4: Org
    'PartyA' => '600XXX', // Your BusinessShortCode or organization ID
    'Initiator' => 'API user created on dashboard',
    'InitiatorPassword' => 'Password of the API user',
    'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
    'ResultURL' => 'https://yourdomain.com/result',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->accountBalance($data);

🔍 Transaction Status

Check the status of a transaction.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'TransactionID' => 'OEI2AK4Q16', // M-Pesa transaction ID
    'PartyA' => '600XXX', // Your BusinessShortCode
    'IdentifierType' => '4', // 1: MSISDN (Phone number), 2: Till 4: Paybill, etc.
    'Initiator' => 'API user',
    'InitiatorPassword' => 'Password of the API user',
    'ResultURL' => 'https://yourdomain.com/result',
    'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->transactionStatus($data);

🏢 B2B (Business to Business)

Send money from your organization to another.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'Initiator' => 'API user',
    'InitiatorPassword' => 'Password of the API user',
    'CommandID' => 'BusinessPayBill', // or MerchantToMerchantTransfer
    'SenderIdentifierType' => '4',
    'RecieverIdentifierType' => '4',
    'Amount' => '1000',
    'PartyA' => '600XXX', // Your BusinessShortCode
    'PartyB' => '600YYY', // Recipient BusinessShortCode
    'AccountReference' => 'Invoice#234',
    'Remarks' => 'B2B Payment',
    'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
    'ResultURL' => 'https://yourdomain.com/result',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->b2b($data);

👥 C2B (Customer to Business Simulation)

Simulate a customer payment to your BusinessShortCode.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'BusinessShortCode' => '600XXX',
    'CommandID' => 'CustomerPayBillOnline', // or CustomerBuyGoodsOnline
    'Amount' => '500',
    'Msisdn' => '2547XXXXXXXX', // Customer phone
    'BillRefNumber' => 'INV2024',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->c2b($data);

📲 STK Push (Lipa Na M-Pesa)

Trigger a payment prompt on a customer's phone.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'BusinessShortCode' => '174379',
    'LipaNaMpesaPasskey' => 'your_lnm_passkey',
    'TransactionType' => 'CustomerPayBillOnline',
    'Amount' => '100',
    'PartyA' => '2547XXXXXXXX', // Customer phone
    'PartyB' => '174379', // Your BusinessShortCode
    'PhoneNumber' => '2547XXXXXXXX',
    'CallBackURL' => 'https://yourdomain.com/callback',
    'AccountReference' => 'Ref001',
    'TransactionDesc' => 'Payment for services',
    'Remarks' => 'Online Payment',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->STKPushSimulation($data);

📡 STK Push Query

Query the status of an STK Push request.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'CheckoutRequestID' => 'ws_CO_123456789',
    'BusinessShortCode' => '174379',
    'LipaNaMpesaPasskey' => 'your_lnm_passkey',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->STKPushQuery($data);

🔄 Reversal

Reverse a transaction.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'CommandID' => 'TransactionReversal',
    'TransactionID' => 'OEI2AK4Q16',
    'Amount' => '100',
    'ReceiverParty' => '600XXX', //your BusinessShortCode
    'RecieverIdentifierType' => '11', //11: when using BusinessShortCode
    'ResultURL' => 'https://yourdomain.com/result',
    'QueueTimeOutURL' => 'https://yourdomain.com/timeout',
    'Remarks' => 'Refund for duplicate payment',
    'Occasion' => 'ErroneousPayment',
    'Initiator' => 'API user',
    'InitiatorPassword' => 'Password of the API user',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->reversal($data);

🔐 Register Validation & Confirmation URLs

Register endpoints to handle C2B payments.

$mpesa = new \Mpesa\Mpesa();

$data = [
    'BusinessShortCode' => '600XXX',
    'ResponseType' => 'Completed',
    'ConfirmationURL' => 'https://yourdomain.com/confirmation',
    'ValidationURL' => 'https://yourdomain.com/validation',
    'environment' => 'sandbox or live',
    'consumer_key' => 'your_consumer_key',
    'consumer_secret' => 'your_consumer_secret',
];

$response = $mpesa->registerUrl($data);

📥 Handle Callback Data

Get Data from Callback:

$mpesa = new \Mpesa\Mpesa();
$data = $mpesa->getDataFromCallback();

Send Callback Response:

$mpesa = new \Mpesa\Mpesa();
$mpesa->finishTransaction(); // success
$mpesa->finishTransaction(false); // failure

📥 Handling M-PESA Daraja Callback Responses

To log the response from any M-PESA Daraja callback (e.g., C2B Confirmation, C2B Validation, STK Push, etc.), you can use the following snippet in your callback.php (or any relevant endpoint). This helps with debugging and record-keeping.

<?php
// callback.php

// Capture raw POST data from Daraja
$callbackData = file_get_contents('php://input');

// Optional: Decode JSON for easier inspection
// $decoded = json_decode($callbackData, true);

// Define log file location (you can customize path)
$logFile = __DIR__ . '/M_PESAConfirmationResponse.json';

// Append the raw callback data with a newline for separation
file_put_contents($logFile, $callbackData . PHP_EOL, FILE_APPEND);

// You can add any additional logic to handle the data here

✅ Best Practices:

  • Always log the full callback for reference during development and support.
  • Use different log files per endpoint if needed, like STKCallback.json, C2BValidation.json, etc.
  • Avoid exposing these logs publicly—store them securely or behind server-level access control.

📘 More Info

🛠 Contributing

Pull requests and suggestions welcome! Let’s improve mobile money in PHP together.

ongudidan/mpesa-sdk 适用场景与选型建议

ongudidan/mpesa-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 100 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 04 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 ongudidan/mpesa-sdk 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: Unknown
  • 更新时间: 2025-04-21