我在PHP中使用Curl在我的网站中集成API。我将检索访问令牌并使用它来处理供应商的订单。
检索令牌:
function getToken() {
// authenticate and return $token
$ch = curl_init();
$api_token = $this->config['API'];
$ninjavan_id = $this->config['ID'];
$ninjavan_secret = $this->config['SECRET'];
curl_setopt($ch, CURLOPT_URL, $api_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"client_id\": \"$id\",
\"client_secret\": \"$secret\",
\"grant_type\": \"client_credentials\"
}");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response, true);
$file = 'key.txt';
$token = $json['access_token'];
file_put_contents('./modules/custommodule/key.txt', $token, LOCK_EX);
}
我能够成功检索令牌,我已经测试了代码。接下来将使用令牌。
处理订单:
$file = './modules/custommodule/key.txt';
$retrieved_token = file_get_contents($file);
do {
$retry = false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_order);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
//curl execution
}");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Bearer $retrieved_token"
));
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode === 401) { // unauthorized
getToken();
$retry = true;
}
}
while ($retry);
curl_close($ch);
file_put_contents('./modules/custommodule/response.txt', $response, LOCK_EX);
file_put_contents('./modules/custommodule/results.txt', $httpcode, LOCK_EX);
非常感谢任何帮助。如果您可以在到期时指出刷新令牌的指导,那将是完美的。
谢谢。
答案 0 :(得分:0)
简单,使用字符串变量插值:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Bearer {$token}"
));
至于处理刷新令牌,如果由于令牌过期而出现错误,则应在每次调用远程API后进行检查,并在这种情况下获取新令牌并重试该调用。如果为远程API创建某种代理,这种方法效果最佳,因此这种机制对调用代码变得透明。以下是如何执行此操作的非常粗略的示例:
var $token;
function getToken() {
// authenticate and return $token as you did before
}
function callAnApiMethod($param1, $param2) {
global $token;
do {
$retry = false;
$ch = curl_init();
// ...
// more setup things, using params of the function, etc.
// ...
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Bearer {$token}"
));
$res = curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] === 401) { // unauthorized
$token = getToken();
$retry = true;
}
} while ($retry);
return json_decode($res);
}
老实说,如果我尝试使用API,我将永远不会再遇到使用CURL的巨大麻烦,CURL非常笨重而且冗长。我会使用类似Guzzle的内容。
另外,正如@ Odyssey1111指出的那样,您可以使用数组表示法来表示您的JSON,然后使用json_encode来获取字符串:
$payload = [
'field' => 'value',
'arrayField' => [
'subfield' => 'subfieldValue',
]
];
$jsonStr = json_encode($payload);
这使您的代码更易于阅读和维护。