使用PHP中的REST API进行Paypal付款

8

我不清楚如何将这个代码示例放入PHP的CURL结构中,特别是-d句柄。

curl -v https://api.sandbox.paypal.com/v1/payments/payment \
-H 'Content-Type:application/json' \
-H 'Authorization:Bearer EOjEJigcsRhdOgD7_76lPfrr45UfuI43zzNzTktUk1MK' \
-d '{
  "intent":"sale",
  "redirect_urls":{
    "return_url":"http://<return URL here>",
    "cancel_url":"http://<cancel URL here>"
  },
  "payer":{
    "payment_method":"paypal"
  },
  "transactions":[
    {
      "amount":{
        "total":"7.47",
        "currency":"USD"
      },
      "description":"This is the payment transaction description."
    }
  ]
}'

我曾使用下面的测试调用,但不知道如何将其扩展到上述示例中。
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.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, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

$result = curl_exec($ch);

if(empty($result))die("Error: No response.");
else
{
    $json = json_decode($result);
    print_r($json->access_token);
}
1个回答

16

你可以尝试类似以下的方式,-d 后面跟的是你想要发送的数据,使用 CURLOPT_HTTPHEADER 可以设置自定义的请求头。

$data = '{
  "intent":"sale",
  "redirect_urls":{
    "return_url":"http://<return URL here>",
    "cancel_url":"http://<cancel URL here>"
  },
  "payer":{
    "payment_method":"paypal"
  },
  "transactions":[
    {
      "amount":{
        "total":"7.47",
        "currency":"USD"
      },
      "description":"This is the payment transaction description."
    }
  ]
}';

curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Authorization: Bearer EOjEJigcsRhdOgD7_76lPfrr45UfuI43zzNzTktUk1MK", 
  "Content-length: ".strlen($data))
);

看看这里的选项,例如如果您不需要返回头信息,请设置curl_setopt($ch, CURLOPT_HEADER, false);http://php.net/manual/en/function.curl-setopt.php


这是一个完整的解决方案吗?我没有得到回应。我已经将授权更改为从代码中检索的类型和访问令牌,其非常类似于第一个示例中的代码。 - RevNoah
它只返回0,请为正确的代码提供建议。 - Shalini
1
对于那些遇到“无响应”错误的人:如果您使用旧版本的PHP,由于OpenSSL握手问题,它将无法正常工作。我刚刚测试了php 5.3.x,它不起作用,切换到PHP版本5.6.28,它可以正常工作,因为它具有更新的OpenSSL版本......即使您使用curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);仍然不会起作用。 - Catluc
1
可以运行。谢谢。 - Jackson
使用这个例子时,我遇到了一个奇怪的错误(NSS:找不到客户端证书(未指定昵称),好像访问令牌丢失了一样)。移除 Content-length 标头后问题就解决了。 - IanS
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接