【发布时间】:2020-09-17 18:22:06
【问题描述】:
我承认,我已经在这方面工作了 3 天,来回翻阅文档,甚至通过 Postman 学会了如何创建自己的产品和计划。
所以我有一个完整的工作订阅按钮,现在我知道我需要保存订阅 ID 才能取消订阅,所以现在保存和加载完美。
令我难过的是,每次有人想取消订阅时,我都需要获取一个 AuthKey,因此我需要运行 2 个 cURL 命令、1 个 GET Auth Key 和 1 个 POST 取消订阅。我将如何在 PHP 中做到这一点?
当这些命令不运行任何数据时,我没有收到任何错误。
Paypal cURL 示例: https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_cancel
////////////////////////////// GET TEMP ACCESS TOKEN/////////////////////////////////
$ch = curl_init();
$clientId = "x";
$secret = "x";
$myIDKEY = "";
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);
$myIDKEY = $json->access_token;
}
curl_close($ch);
/////////////////////////////// SEND CANCEL POST ////////////////////////////////
$ch = curl_init();
$headers = [
'Authorization: Bearer '.$myIDKEY,
'Content-Type: application/json'
];
$postData = [
'reason' => 'clicked cancel subscription button'
];
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/billing/subscriptions/".$_SESSION['honeybeesubID']."/cancel");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $myIDKEY
非常感谢!
【问题讨论】:
-
您的代码给了我一个良好的开端,感谢 Sebastian。文档很难阅读……尤其是缺少 PHP 代码。您能指出如何创建订阅吗?你有没有从 paypal 页面实现现成的 Javascript 代码,然后用一些 webhook 来获取客户端的订阅 ID? ...在您的代码中,它被称为
$_SESSION['honeybeesubID']。我想在注册后将订阅 ID 保存在数据库中。 --developer.paypal.com/docs/business/subscriptions/… 的文档没有说明以后在哪里/如何获取客户 ID 以识别他。 -
好了,webhook URL 定义的PHP脚本可以读取
$data = json_decode(file_get_contents("php://input")); error_log(print_r($data, true));传入的数据 -
我现在已经写了一个完整的教程,因为这一切都很困难:stacklounge.de/6325/…
标签: php curl paypal paypal-subscriptions