Paypal使用PHP cURL获取访问令牌

时间:2016-05-16 19:55:08

标签: php curl paypal

你好我正在使用其他人使用的代码,这些代码据说已经让它工作并且已经获取了他们的令牌信息。代码如下:

$ch = curl_init();
$clientId = "myclientid";
$secret = "mysecret";

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_SSLVERSION , 6); //NEW ADDITION
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);
}

curl_close($ch); //THIS CODE IS NOW WORKING!

我从Paypal API with PHP and cURL检索了这段代码,并看到它在其他人的代码中实现,所以我认为它有效。然而,即使我提供了正确的客户端ID和密码(也许最近的更新破坏了这段代码?),我只收到没有回应。)

Paypal提供的关于获取访问令牌的指南可在此处找到 - > https://developer.paypal.com/docs/integration/direct/make-your-first-call/ 然而,它演示了cURL中的解决方案,而不是通过PHP cURL扩展,因此它对我来说很难听。有什么帮助吗?

2 个答案:

答案 0 :(得分:4)

现在似乎要求声明要使用哪种类型的SSL版本,因此上面的代码将在插入curl_setopt($ch, CURLOPT_SSLVERSION , 6); //tlsv1.2时起作用。

答案 1 :(得分:2)

刚刚测试了 API,我可以确认此代码正在运行:

(无 SSL 选项)

    $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.sandbox.paypal.com/v1/oauth2/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_USERPWD => $PAYPAL_CLIENT_ID.":".$PAYPAL_SECRET,
    CURLOPT_POSTFIELDS => "grant_type=client_credentials",
    CURLOPT_HTTPHEADER => array(
    "Accept: application/json",
    "Accept-Language: en_US"
    ),
    ));

    $result= curl_exec($curl);

    $array=json_decode($result, true); 
    $token=$array['access_token'];

    echo "<pre>";
    print_r($array);