繁体   English   中英

使用PHP cURL在/ oauth2 / access_token上发布数据并以jSON形式获取数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM