By admin |
define("TOKEN_URL", 'http://example.com/oauth2/token');
define("UPDATE_URL", 'http://example.com/api/order/update-status');
//第一步:调用token接口,获取token。
$data = array(
    'grant_type' => 'client_credentials',
    'client_id' => 'your_client_id',
    'client_secret' => 'your_client_secret',
    'scope' => 'basic', //这里可以根据设置好的scope灵活填写。
);
$fields_string = '';
foreach ($data as $key => $value) {
    $fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, TOKEN_URL);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$resp = json_decode($result, TRUE);
print_r($resp);
$access_token = $resp['access_token'];

//第二步:使用上一部获取的token,进行接口请求。
$fields = array(
  'order_id' => 888,
  'status' => 'pending' 
);
$header = array(
  'Content-Type: application/json',
  'Authorization:' . $resp['token_type'] . ' ' . $resp['access_token'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, UPDATE_URL);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$decode = json_decode($result, TRUE);
curl_close($ch);
print_r($decode);