使用PHP在没有卷标的情况下进行PayPal API调用
问题描述:
由于Google App Engine不支持,我无法使用cURL。使用PHP在没有卷标的情况下进行PayPal API调用
我想获得在步骤2中的访问令牌:https://developer.paypal.com/docs/integration/direct/make-your-first-call
我不知道我应该怎么构建我的电话。我有这个至今:
$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;
它返回这样的:
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
任何有识之士的赞赏!
答
我想通了。
client id
和secret
必须放入由:
,然后base64 encoded
分开的字符串中。然后发送到header
。
这工作:
$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;