![](/img/trans.png)
[英]PHP cURL send oauth2.0 access_token in header and POST json data
[英]Using PHP cURL to POST data on /oauth2/access_token and GET data as jSON
我已經按照有關如何驗證用戶的Path API的步驟進行操作。 在教程身份驗證過程中,用戶將開始重定向到以下URL並提示授予訪問權限:
https://partner.path.com/oauth2/authenticate?response_type=code&client_id=THE_CLIENT_ID
然后,服務器將通過URL地址作為授權代碼給出響應(我已經完成了這一步並獲得了代碼 )。
正如docs所解釋的,只要使用Client ID和Client Secret(獲取access_token),就應該使用/ oauth2 / access_token將代碼交換為訪問令牌。
但是我不知道如何通過cURL將數據發布到服務器,我已經嘗試了太多curl_setopt()選項和組合,但是仍然沒有任何幫助。
在文檔中,“請求”如下所示:
POST /oauth2/access_token HTTP/1.1
Host: partner.path.com
Content-Type: application/x-www-form-urlencoded
Content-Length: <LENGTH>
grant_type=authorization_code&client_id=CLIENT&client_secret=SECRET&code=CODE
和cURL格式是這樣的:
curl -X POST \
-F 'grant_type=authorization_code' \
-F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'code=CODE' \
https://partner.path.com/oauth2/access_token
服務器將給出如下響應:
HTTP/1.1 201 CREATED
Content-Type: application/json
Content-Length: <LENGTH>
{
"code": 201,
"type": "CREATED"
"reason": "Created",
"access_token": <ACCESS_TOKEN>,
"user_id": <USER_ID>,
}
要使用cURL在PHP中執行POST請求,您可以執行以下操作:
$handle = curl_init('https://partner.path.com/oauth2/access_token');
$data = array('grant_type' => 'authorization_code', 'client_id' => 'CLIENT', 'client_secret' => 'SECRET', 'code' => 'CODE');
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($handle);
然后,您可以使用json_decode($json_encoded)
從服務器響應中獲取關聯數組。
不知道您是否已經解決了這個問題,因為我看到它是從前不久開始的,但是我只是遇到了這個問題,這就是我如何解決的。
$code = $_GET['code'];
$url = 'https://YourPath/token?response_type=token&client_id='.$client_id.'&client_secret='.$client_secret.'&grant_type=authorization_code&code='.$code.'&redirect_uri='.$redirect_uri;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST,true);
$exec = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info);
curl_close($ch);
$json = json_decode($exec);
if (isset($json->refresh_token)){
global $refreshToken;
$refreshToken = $json->refresh_token;
}
$accessToken = $json->access_token;
$token_type = $json->token_type;
print_r($json->access_token);
print_r($json->refresh_token);
print_r($json->token_type);
希望能有所幫助
除了福克斯·威爾遜答案:
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.