static-variables / jweb /ac1 /src /api /mpesa_service.php
fellybikush's picture
Upload 99 files
0dff816 verified
raw
history blame
2.69 kB
<?php
class MpesaService {
private $consumerKey = "your_consumer_key";
private $consumerSecret = "your_consumer_secret";
private $shortcode = "174379"; // Lipa Na M-Pesa shortcode
private $passkey = "your_passkey";
private $phoneNumber = "0756709823"; // Your M-Pesa number
public function initiateSTKPush($userPhone, $amount, $userId) {
$access_token = $this->getAccessToken();
$url = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
$timestamp = date('YmdHis');
$password = base64_encode($this->shortcode . $this->passkey . $timestamp);
$callback_url = 'https://yourdomain.com/mpesa_callback.php';
$curl_post_data = array(
'BusinessShortCode' => $this->shortcode,
'Password' => $password,
'Timestamp' => $timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $amount,
'PartyA' => $userPhone,
'PartyB' => $this->shortcode,
'PhoneNumber' => $userPhone,
'CallBackURL' => $callback_url,
'AccountReference' => 'JMOTORS' . $userId,
'TransactionDesc' => 'JMotors Deposit'
);
$data_string = json_encode($curl_post_data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $access_token
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
private function getAccessToken() {
$url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Basic ' . base64_encode($this->consumerKey . ':' . $this->consumerSecret)
));
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result, true);
return $result['access_token'];
}
}
?>