早间
尝试使用PHP和PayPal API将自定义PayPal订阅添加到我的网站。我以前没有真正使用过PHP或Curl,所以这需要一段时间,但我已经设法编写了一个脚本,从沙箱中获得访问令牌,并链接到您可以订阅的现有订阅计划。下面的代码很有效。。。
curl_setopt($ch, CURLOPT_POSTFIELDS, "n {n "plan_id":$planID,n "start_time":$startTime,n "application_context": {n "brand_name": "Sleep Happy Mattress",n "locale": "en-US",n "shipping_preference": "SET_PROVIDED_ADDRESS",n "user_action": "SUBSCRIBE_NOW",n "payment_method": {n "payer_selected": "PAYPAL",n "payee_preferred": "IMMEDIATE_PAYMENT_REQUIRED"n },n "return_url": "https://example.com/returnUrl",n "cancel_url": "https://example.com/cancelUrl"n }n }");
然而,每当我试图将planID和start_time作为php变量包含在curl_setopt($ch,CURLOPT_POSTFIELDS)中时,我都会收到一个"请求格式不正确、语法不正确或违反模式"的错误。
$planID = 'P-25Y56437062492726MFWZ4GI';
$startTime = '2021-10-22T00:00:00Z';
//由curl生成到PHP:http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_POSTFIELDS, "n {n "plan_id": "P-25Y56437062492726MFWZ4GI",n "start_time": "2021-10-22T00:00:00Z",n "application_context": {n "brand_name": "Sleep Happy Mattress",n "locale": "en-UK",n "shipping_preference": "SET_PROVIDED_ADDRESS",n "user_action": "SUBSCRIBE_NOW",n "payment_method": {n "payer_selected": "PAYPAL",n "payee_preferred": "IMMEDIATE_PAYMENT_REQUIRED"n },n "return_url": "https://example.com/returnUrl",n "cancel_url": "https://example.com/cancelUrl"n }n }");
curl_setopt($ch, CURLOPT_POSTFIELDS, "n {n "plan_id":$planID,n "start_time":$startTime,n "application_context": {n "brand_name": "Sleep Happy Mattress",n "locale": "en-US",n "shipping_preference": "SET_PROVIDED_ADDRESS",n "user_action": "SUBSCRIBE_NOW",n "payment_method": {n "payer_selected": "PAYPAL",n "payee_preferred": "IMMEDIATE_PAYMENT_REQUIRED"n },n "return_url": "https://example.com/returnUrl",n "cancel_url": "https://example.com/cancelUrl"n }n }");
我的串联是错误的,还是变量需要先以某种方式进行操作,或者两者兼有??
非常感谢的帮助
Chris
创建如下JSON字符串:
$data = [
'plan_id' => $planID,
'start_time' => $startTime,
'application_context' => [
'brand_name' => 'Sleep Happy Mattress',
'locale' => 'en-US',
'shipping_preference' => 'SET_PROVIDED_ADDRESS',
'user_action' => 'SUBSCRIBE_NOW',
'payment_method' => [
'payer_selected' => 'PAYPAL',
'payee_preferred' => 'IMMEDIATE_PAYMENT_REQUIRED'
],
'return_url' => 'https://example.com/returnUrl',
'cancel_url' => 'https://example.com/cancelUrl'
],
];
然后你可以检查嵌套etc是否正确(请注意,我不知道上面的内容是否正确,我只是从你的问题中复制了它),如果你json_encode
它,你将创建格式良好的JSON。
$jsonEncoded = json_encode($data);
不要指定或包含start_time
,除非您希望在结账时不显示金额。
您的问题是没有在变量值周围加引号,这对于JSON字符串语法来说是必要的。观察:
"plan_id": "$planID",
使用json_encode()从数组对象构造字符串会更好。