简体   繁体   中英

Making PayPal API calls in PHP without cURL

I can't use cURL as Google App Engine doesn't support it.

I am trying to get the access token in step 2 of: https://developer.paypal.com/docs/integration/direct/make-your-first-call

I'm not sure how I should be structuring my call. I have this so far:

$data = array(
    'grant_type' => 'client_credentials',
    'client_id' => $sandbox_client_id,
    'secret' => $sandbox_secret

);


$data = json_encode($data);

$context = [
  'http' => [
    'method' => 'POST',
    'header' => 'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
        'Accept: application/json' . "\r\n" .
        'Accept-Language: en_US' . "\r\n"
    ,
    'content' => $data
  ]
];
$context = stream_context_create($context);

$response = file_get_contents('https://api.sandbox.paypal.com/v1/oauth2/token', false, $context);

echo $response;

Which returns this:

Warning: file_get_contents(https://api.sandbox.paypal.com/v1/oauth2/token): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in C:\folder\php\paypal\test.php on line 28

Any insight is appreciated!

I figured it out.

The client id and secret have to be put into a string separated by : then base64 encoded . That is then sent in the header .

This works:

$auth_string = $sandbox_client_id . ':' . $sandbox_secret;
$encoded_auth = base64_encode($auth_string);

$data = array(
    'grant_type' => 'client_credentials'


);

$http_query = http_build_query($data);
$context = [
  'http' => [
    'method' => 'POST',
    'header' => 'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
        'Accept: application/json' . "\r\n" .
        'Accept-Language: en_US' . "\r\n" .
        'Authorization: Basic ' . $encoded_auth
    ,
    'content' => $http_query
  ]
];


$context = stream_context_create($context);

$response = file_get_contents('https://api.sandbox.paypal.com/v1/oauth2/token', false, $context);

echo $response;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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