Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paypal get access token with PHP cURL

Tags:

php

curl

paypal

hello i'm using code used by other people who supposedly have gotten it to work and have gotten their token information retrieved. The code is as follows:

$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!

I retrieved this code from Paypal API with PHP and cURL and have seen it implemented in some others peoples code so i assume that it works. However i'm only receiving no response even though i am supplying the correct client id and secret (maybe a recent update has broken this code?).

The guide provided by Paypal on getting the access token is found here-> https://developer.paypal.com/docs/integration/direct/make-your-first-call/ however it demonstrates the solution in cURL and not through the PHP cURL extension so its alittle cryptic to me. Any help?

like image 768
DiscreteTomatoes Avatar asked May 16 '16 19:05

DiscreteTomatoes


2 Answers

Well it seems that it is now a requirement to declare what type of SSL Version to use, thus the code above will work when curl_setopt($ch, CURLOPT_SSLVERSION , 6); //tlsv1.2 is inserted.

like image 55
DiscreteTomatoes Avatar answered Oct 02 '22 01:10

DiscreteTomatoes


Just tested the API and I can confirm this code is working :

(No SSL options)

    $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);
like image 37
jirarium Avatar answered Oct 02 '22 01:10

jirarium