<?php
	$url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'; // live
	include 'connect.php';
	$timestamp = date('YmdHis');
	date_default_timezone_set('Africa/Nairobi');	
	$date = date('d-m-Y H:i:s', time());
//	$authenticationurl = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';  // sandbox

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);   //FOR LIVE
//	curl_setopt($curl, CURLOPT_URL, $authenticationurl);   //SANDBOX
	
	$credentials = base64_encode('OUcgVKCGwfzRGCsS2UkBvtNOGTdwmTdM:RGwGGt5CQG9jEp6Q');  // consumer key & secret

	curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.$credentials)); //setting a custom header
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);

	$curl_response = curl_exec($curl);
	$response_status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);   
	//response status code
	//echo $response_status_code.'<br><br>';
	$curl_response = json_decode($curl_response);
    $access_token=$curl_response->access_token;

	print_r($curl_response);
	echo '<br>';

?>
 
 <?php   
    include('connect.php');
    $query=mysqli_query($conn, "SELECT * FROM  accesstoken  where status = 1 ");
    $rows=mysqli_fetch_array($query);
    $exptime= $rows["expirytime"];
    date_default_timezone_set('Africa/Nairobi');	
	$date = date('d-m-Y H:i:s', time());
    $newTime = date("d-m-Y H:i:s",strtotime("+50 minutes", strtotime($date)));
    date_default_timezone_set('Africa/Nairobi');	
	$date = date('d-m-Y H:i:s', time());
    $curdate=$date;
    $mydate=$exptime;
  if($curdate>$mydate){
       $update_query = "UPDATE accesstoken SET token='$access_token',expirytime='$newTime',currenttime ='$date' where status = 1";
       mysqli_query($conn, $update_query);
  }
  else{
      
  }
  
    ?>