mxgel / mpesa
Safaricom M-Pesa 集成
v1.13
2018-05-16 07:19 UTC
Requires
- php: >=5.6
- guzzlehttp/guzzle: ^6.3
- illuminate/config: ~5.4|~5.5
- illuminate/support: ~5.4|~5.5
- nesbot/carbon: ~1.18
README
这是 Safaricom 的 Mpesa G2 API 的非官方实现
我该如何设置?
首选方式是通过 composer 安装:
composer require mxgel/mpesa
这就完成了。
身份验证
要与 daraja API 进行通信,您始终需要一个访问令牌。这个库已经为您简化了这一点。您只需向 execute 方法提供一个 Mxgel\MPesa\Auth\Auth
实例即可。例如:
/** * @var Auth */ private $auth; /** * @return \Mxgel\MPesa\Auth\Auth */ public function getAuth(): Auth { if (!$this->auth) { return $this->auth = new Mxgel\MPesa\Auth\Auth([ 'key' => config('key'), 'secret' => config('secret'), ]); } return $this->auth; }
MPESA Express
此 API 用于代表客户发起在线支付。
示例
使用 Mxgel\MPesa\Requests\LNMO
初始化支付的示例代码(在 Laravel 中)可能如下所示(使用 Mxgel\MPesa\Requests\LNMO
)。
$request = LNMO::make($amount, $phoneNumber, $shortCode, 'Wallet top up'); $request->setPassKey(config('LNMO_passkey')) ->setBusinessShortCode(config('LNMO_short_code')) ->setCallBackURL($callback); $resp = $request->execute($this->getAuth()); Log::info('STk data', $request->toArray()); //NOTE: For a real application, save this details in a data store
现在,我们需要编写一个回调函数,它将在客户请求完成后接收来自 Safaricom 的数据。 请记住将上述请求详细信息保存在数据存储中
以下是在 Laravel 中的回调示例。
为了方便处理接收到的数据,我们使用 Mxgel\MPesa\Responses\LNMOCallbackResponse
类。这个类移除了不必要的数据,只提供了核心信息。
// Assuming u have an Express model, u can have this. Log::debug('LNMO Data', $this->request->all()); $resp = new LNMOCallbackResponse($this->request->get('Body')); Express::whereMerchantRequestId($resp->getMerchantRequestID()) ->whereCheckoutRequestId($resp->getCheckoutRequestID()) ->whereConfirmed(false) // Ensure it's yet to be updated ->update([ 'receipt_number' => $resp->getMpesaReceiptNumber(), 'confirmed' => $resp->completed(), ]);
有时您可能想编写一个 cron 作业来更新未确认的交易。幸运的是,我们可以使用状态检查 API,而且非常简单。使用 Mxgel\MPesa\Requests\LNMQ
类如下所示
$request = new LNMQ([ 'businessShortCode' => $business_short_code, 'checkoutRequestID' => $checkout_request_id, 'passKey' => config('LNMO_passkey'), ]); // Remember our auth object? Yes, we need it. $resp = $request->execute($this->getAuth()); Log::info("Execute status with data: ", $request->toArray()); Log::info("Executed status check with response", $resp->toArray()); if ($resp->completed()) { // Your code here... }
此时,您的 STK 应该没有问题。