首页 > 解决方案 > 在 PHP 中连接 PayPal 以进行用户身份验证

问题描述

我正在尝试使用 PHP 和 CURL 在我的网站上实现“与 PayPal 连接”按钮。我已经设法接收到身份验证代码并使用此代码访问令牌,但我无法接收用户数据。我的 REST 应用程序已获批准,我应该能够收到用户电子邮件。我不想使用 PayPal PHP SDK,因为现在已弃用。

这是我的代码:

$pp_client_id = {my client id};
$pp_secret = {my secret};

$code = $_GET['code'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.paypal.com/v1/oauth2/token');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_USERPWD, $pp_client_id.':'.$pp_secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
   'grant_type'=>'authorization_code',
   'code'=> $code
)));

$res_authcode = curl_exec($ch);

if (empty($res_authcode)) {
   // print error
} else {
   $json_authcode = json_decode($res_authcode);
   $refresh_token = $json_authcode->refresh_token;
   curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
      'grant_type'=>'refresh_token',
      'refresh_token'=> $refresh_token
   )));

   $res_token = curl_exec($ch);

   if(empty($res_token)) {
      // print error
   } else {
     $json_token = json_decode($res_token);
     $access_token = $json_authcode->access_token;

     curl_setopt($ch, CURLOPT_URL, 'https://api.paypal.com/v1/oauth2/userinfo/?schema=paypalv1.1');
     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
       'access_token'=> $access_token
     )));

     $res_userinfo = curl_exec($ch);
 
     if(empty($res_userinfo)) {
       // print error
     } else {
       $json_userinfo = json_decode($res_userinfo);
       print_r($json_userinfo);
     }
   }
}

curl_close($ch);

我收到一条 RESOURCE_NOT_FOUND 消息。我应该对我的代码进行哪些更改以获取用户信息?

标签: phpcurlpaypal

解决方案


我终于设法解决了我的问题并通过 cURL 从 PayPal 接收用户信息。

我将连接 URL 和标头更改为:

curl_setopt($ch, CURLOPT_URL, 'https://api.paypal.com/v1/oauth2/token/userinfo?schema=openid');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'authorization: Bearer '.$access_token,
  'content-type: application/json'
));

$res_userinfo = curl_exec($ch);

推荐阅读