This is a module to assist php developers in consuming Kopokopo's API
You can install the PHP SDK via composer.
The recommended way to install the SDK is with Composer.
composer require kopokopo/k2-connect-php
The package should be configured with your client id and client secret which you can get from your account on the kopokopo's app
//Store your client id and client secret as environment variables
//Including the kopokopo sdk
use Kopokopo\SDK\K2;
// do not hard code these values
$options = [
'clientId' => 'YOUR_CLIENT_ID',
'clientSecret' => 'YOUR_CLIENT_SECRET',
'apiKey' => 'YOUR_API_KEY',
'baseUrl' => 'https://sandbox.kopokopo.com'
];
$K2 = new K2($options);- Tokens :
$tokens = $K2->TokenService(); - Webhooks :
$webhooks = $K2->Webhooks(); - STK PUSH :
$stk = $K2->StkService(); - External Recipient :
$externalRecipientService = $K2->ExternalRecipientService(); - Settlement Transfer :
$transfer = $K2->SettlementTransferService(); - SendMoneyService :
$sendMoney = $K2->SendMoneyService(); - PollingService :
$polling = $K2->PollingService(); - ReversalService:
reversalService = $K2->ReversalService(); - PaymentLinkService:
paymentLinkService = $K2->PaymentLinkService();
You will need to pass an access token when sending data to Kopokopo's API.
This will return accessToken and expiresIn values
use Kopokopo\SDK\K2;
// Do not hard code these values
$options = [
'clientId' => 'YOUR_CLIENT_ID',
'clientSecret' => 'YOUR_CLIENT_SECRET',
'apiKey' => 'YOUR_API_KEY',
'baseUrl' => 'https://sandbox.kopokopo.com'
];
$K2 = new K2($options);
// Get one of the services
$tokens = $K2->TokenService();
// Use the service
$result = $tokens->getToken();
//print the result
print_r($result);- Consuming
// TODO: review this
$router->map('POST', '/webhook', function () {
global $K2;
global $response;
$webhooks = $K2->Webhooks();
$json_str = file_get_contents('php://input');
var_dump($json_str);
$response = $webhooks->webhookHandler($json_str, $_SERVER['HTTP_X_KOPOKOPO_SIGNATURE']);
echo json_encode($response);
});- Subscription
$webhooks = $K2->Webhooks();
//To subscribe to a webhook
$response = $webhooks->subscribe([
'eventType' => 'buygoods_transaction_received',
'url' => 'http://localhost:8000/webhook',
'scope' => 'till',
'scopeReference' => '000000',
'accessToken' => 'my_access_token',
'enableDarajaPayload' => 'false'
]);
print_r($response);$stk = $K2->StkService();
$result = $stk->initiateIncomingPayment([
'paymentChannel' => 'M-PESA STK Push',
'tillNumber' => 'K000000',
'firstName' => 'Jane',
'lastName' => 'Doe',
'phoneNumber' => '0712345678',
'amount' => 3455,
'email' => 'example@example.com',
'callbackUrl' => 'http://localhost:8000/test',
'accessToken' => 'myRand0mAcc3ssT0k3n',
]);
print_r($result);For other usage examples check out the example app available in this project.
The only supported ISO currency code at the moment is: KES
-
$TokenService->getToken()to get an access token.- The response will have the following structure
[ 'status' => 'success', 'data' => [ 'accessToken' => 'GT6576QGYdYh8i5s8DnxUQVphFewh-8eiO2', 'tokenType' => 'Bearer', 'expiresIn' => 3600, 'createdAt' => '2021-04-06T13:49:50+03:00' ] ]
NB: The access token is required to send subsequent requests
$TokenService->revokeToken(['accessToken' => 'myRand0mAcc3ssT0k3n'])to revoke an access token.
NB: The access token cannot be used to send subsequent requests
-
$TokenService->introspectToken(['accessToken' => 'myRand0mAcc3ssT0k3n'])to introspect a token. -
$TokenService->infoToken(['accessToken' => 'myRand0mAcc3ssT0k3n'])to get more information on a token
-
$StkService->initiateIncomingPayment([ stkOptions ]):stkOptions: An array of arrays containing the following keys:tillNumber: Your online payments short code from Kopo Kopo's DashboardREQUIREDfirstName: Customer's first namelastName: Customer's last namephoneNumber: Phone number to pull money from.REQUIREDemail: Customer's email addresscurrency: 3-digit ISO format currency code.REQUIREDamount: Amount to charge.REQUIREDcallbackUrl: Url that the result will be posted toREQUIREDpaymentChannel: Payment channel. Default is:"M-PESA STK Push".REQUIREDaccessToken: Gotten from theTokenServiceresponseREQUIREDmetadata: It is a hash containing a maximum of 5 key value pairs
-
$StkService->getStatus([location ]):location: The request location you get when you send a requestaccessToken: Gotten from theTokenServiceresponseREQUIRED
For more information, please read https://api-docs.kopokopo.com/#receive-payments-from-m-pesa-users-via-stk-push
-
ExternalRecipientService->addExternalRecipient([ externalRecipientOptions ]):externalRecipientOptions: An array of arrays containing the following keys:type: Recipient typeREQUIRED- Mobile Wallet Recipient(
mobile_wallet)firstName: Pay recipient's first nameREQUIREDlastName: Pay recipient's last nameREQUIREDphoneNumber: Pay recipient's phone numberREQUIREDemail: Pay recipient's email numbernetwork: Pay recipient's networkREQUIRED
- Bank Account Recipient(
bank_account)accountName: Pay recipient's account nameREQUIREDaccountNumber: Pay recipient's account numberREQUIREDbankBranchRef: Bank branch reference from the kopokopo dashboardREQUIREDsettlementMethod: Settlement methodREQUIRED
- External Till Recipient(
till)tillNumber: Pay recipient's till numberREQUIREDtillName: Pay recipient's till nameREQUIRED
- Paybill(
paybill)paybillName: Pay recipient's paybill nameREQUIREDpaybillNumber: Pay recipient's paybill numberREQUIREDpaybillAccountNumber: Pay recipient's account numberREQUIRED
- Mobile Wallet Recipient(
accessToken: Gotten from theTokenServiceresponseREQUIRED
-
ExternalRecipientService->getStatus([ location ]):location: The request location you get when you send a requestaccessToken: Gotten from theTokenServiceresponseREQUIRED
For more information, please read https://api-docs.kopokopo.com/#send-money
-
SettlementTransferService->createMerchantBankAccount([ accountOpts ]):accountOpts: An array of arrays containing the following keys:accountName: Settlement Account NameREQUIREDbankBranchRef: Settlement Bank Branch ReferenceREQUIREDaccountNumber: Settlement account numberREQUIREDsettlementMethod: Settlement methodREQUIREDaccessToken: Gotten from theTokenServiceresponseREQUIRED
-
SettlementTransferService->createMerchantWallet([ accountOpts ]):accountOpts: An array of arrays containing the following keys:phoneNumber: Phone number to settle toREQUIREDnetwork: Mobile money network to settle toREQUIREDaccessToken: Gotten from theTokenServiceresponseREQUIRED
-
SettlementTransferService->getStatus([ location ]):location: The request location you get when you send a requestaccessToken: Gotten from theTokenServiceresponseREQUIRED
For more information, please read api-docs#send_money
-
SendMoneyService->sendMoney([ sendMoneyOptions ]):sendMoneyOptions: An associative array containing the following keys:destinations: An array of nested associative arrays defining destination details.currency: 3-digit ISO format currency code.REQUIREDsourceIdentifier: The source of funds to transfer, i.e, till number ornullfor available balance.metadata: It is a hash containing a maximum of 5 key-value pairs.callbackUrl: URL that the result will be posted to.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
-
SendMoneyService->getStatus([ statusOptions ]):statusOptions: An associative array containing the following keys:location: The request location you get when you send a request.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
-
For more information, please read api-docs#send_money
-
PollingService->pollTransactions([ pollingOpts ]):pollingOpts: An array of arrays containing the following keys:fromTime: The starting time of the polling requesttoTime: The end time of the polling requestscope: The scope of the polling requestscopeReference: The scope referenceREQUIRED for the 'Till' scopecallbackUrl: Url that the result will be posted toREQUIREDaccessToken: Gotten from theTokenServiceresponseREQUIRED
-
PollingService->getStatus([ statusOpts ]):statusOpts: An array of arrays containing the following keys:location: The location url you got from the requestREQUIREDaccessToken: Gotten from theTokenServiceresponseREQUIRED
This works the same for all requests that you get a location response.
For more information, please read api-docs#polling
-
ReversalService->initiateReversal([ reversalOptions ]):reversalOptions: An associative array containing the following keys:transactionReference: Reference of the transaction to be reversed.REQUIREDreason: Reason for the reversal.REQUIREDmetadata: An associative array with a maximum of 5 key-value pairs.callbackUrl: URL that the result will be posted to.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
-
ReversalServices->getStatus([ statusOptions ]):statusOptionsAn associative array containing the following keys:location: The request location you get when you initiate a reversal request.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
-
PaymentLinkService->createPaymentLink([ paymentLinkOptions ]):paymentLinkOptions: An associative array containing the following keys:tillNumber: Till number for the M-PESA or Online Payments Account that will receive the payment.REQUIREDcurrency: 3-digit ISO format currency code.REQUIREDamount: The amount the customer will pay.REQUIREDpaymentReference: The merchant internal reference for the payment.note: Note for the customer as they make the payment.metadata: An associative array with a maximum of 5 key pairs.callbackUrl: URL that the payment link result will be posted to once a customer makes a payment.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
-
PaymentLinkService->cancelPaymentLink([ cancellationOptions ]):cancellationOptions: An associative array containing the following keys:location: The request location you get when you send a payment link request.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
-
PaymentLinkService->getStatus([ statusOptions ]):statusOptions: An associative array containing the following keys:location: The request location you get when you send a payment link request.REQUIREDaccessToken: Gotten from theTokenServiceresponse.REQUIRED
- All the post requests are asynchronous apart from
TokenService. This means that the result will be posted to your custom callback url when the request is complete. The immediate response of the post requests contain thelocationurl of the request you have sent which you can use to query the status.
Note: The asynchronous results are processed like webhooks.
- To access the different parts of the response or webhook payload passed, use the following keys to access:
-
getToken() successful response
acessTokentokenTypeexpiresIncreatedAt
-
introspectToken() successful response
activescopeclientIdtokenTypeexp- expiring timeiat- initiated at
-
infoToken() successful response
scopeexpiresInresourceOwnerIdapplicationIdtokenTypecreatedAt
-
Buygoods Received
idtopiccreatedAteventTyperesourceIdreferenceoriginationTimesenderPhoneNumberamountcurrencytillNumbersystemstatussenderFirstNamesenderMiddleNamesenderLastNamelinkSelflinkResource
-
B2b transaction received
idtopiccreatedAteventTyperesourceIdreferenceoriginationTimesendingTillamountcurrencytillNumbersystemstatuslinkSelflinkResource
-
Merchant to merchant transaction received
idtopiccreatedAteventTyperesourceIdoriginationTimesendingMerchantamountcurrencystatuslinkSelflinkResource
-
Buygoods transaction reversed
idtopiccreatedAteventTyperesourceIdreferenceoriginationTimesenderPhoneNumberamountcurrencytillNumbersystemstatussenderFirstNamesenderMiddleNamesenderLastNamelinkSelflinkResource
-
Transfer completed webhook
-
id -
topic -
createdAt -
eventType -
resourceId -
originationTime -
amount -
currency -
status -
disbursements -
linkSelf -
linkResource -
destinationReference -
destinationType -
if destination type is bank:
settlementMethodbankBranchRefaccountNameaccountNumber
-
if destination type is mobile wallet:
firstNamelastNamephoneNumbernetwork
-
-
Customer created webhook
idtopiccreatedAteventTypefirstNamemiddleNamelastNamephoneNumberlinkSelflinkResource
-
Send Money Result
idtypecreatedAtstatussourcedIdentifierdestinationscurrencytransferBatcheserrorsmetadatalinkSelfcallbackUrl
-
Stk Push Result
-
Successful result
idtypeinitiationTimestatuseventTyperesourceIdreferenceoriginationTimesenderPhoneNumberamountcurrencytillNumbersystemsenderFirstNamesenderMiddleNamesenderLastNameresourceStatuserrorsmetadatalinkSelfcallbackUrl
-
Unsuccessful result
idtypeinitiationTimestatuseventTyperesourceerrorsmetadatalinkSelfcallbackUrl
-
-
Polling Result
idtypestatusfromTimetoTimescopescopeReferencetransactionslinkSelfcallbackUrl
-
Reversal Result
idtypetransactionReferencestatusreasonreversalBulkPaymenterrorsmetadatacreatedAtcallbackUrllinkSelf
-
Payment Link Result
idtypestatuscurrencyamounttillNametillNumberpaymentReferencenotecreatedAtpaymentLinkerrorsmetadatacallbackUrllinkSelf
-
Webhook Subscription Status
idtypeeventTypewebhookUristatusscopescopeReference
-
Merchant Bank Account Status
idtypeaccountNumberaccountNamebankBranchRefsettlementMethodstatusaccountReference
-
Merchant Mobile Wallet Status
idtypefirstNamelastNamephoneNumbernetworkstatusaccountReference
-
Pay Recipient Status
-
id -
type -
recipientType -
status -
recipientReference -
If
recipientType == "Bank Account"accountNumberaccountNamebankBranchRefsettlementMethod
-
If
recipientType == "Mobile Wallet"firstNamelastNamephoneNumbernetworkemail
-
If
recipientType == "Till"tillNumbertillName
-
If
recipientType == "Paybill"paybillNamepaybillNumberpaybillAccountNumber
-
-
Send Money Status
- This payload is similar to
Send Money Resultpayload
- This payload is similar to
-
Stk Push Status
- Successful request
- This payload is similar to the successful result
- Failed request
- This payload is similar to failed result
- Pending request
idtypeinitiationTimestatuseventTyperesourceerrorsmetadatalinkSelfcallbackUrl
- Successful request
-
Polling Status
- This payload is the same as the
Pollingresult payload
- This payload is the same as the
-
Reversal Status
- This payload is similar to
Reversal Resultpayload
- This payload is similar to
-
Payment Link Status
- This payload is similar to
Payment Link Resultpayload
- This payload is similar to
-
errorCode -
errorMessage -
Token Error Responses
errorerrorDescription
For more information on the expected payloads and error codes, please read the api docs
We welcome those with open arms just make a pull request and we will review.
Run all tests:
$ composer install
$ php vendor/bin/phpunit tests --testdoxIf you find a bug, please file an issue on our issue tracker on GitHub.
k2-connect-php is MIT licensed. See LICENSE for details.