PHP code example of sparkworld / laravel-kopokopo-mpesa

1. Go to this page and download the library: Download sparkworld/laravel-kopokopo-mpesa library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sparkworld / laravel-kopokopo-mpesa example snippets


//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);

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);

// 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);
});

$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'
]);

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' => '[email protected]',
                'callbackUrl' => 'http://localhost:8000/test',
                'accessToken' => 'myRand0mAcc3ssT0k3n',
            ]);
print_r($result);

  [ 'status' => 'success',
    'data' => [
      'accessToken' => 'GT6576QGYdYh8i5s8DnxUQVphFewh-8eiO2',
      'tokenType' => 'Bearer',
      'expiresIn' => 3600,
      'createdAt' => '2021-04-06T13:49:50+03:00'
    ]
  ]