#php #model-view-controller #paypal #sdk
#php #model-view-controller #paypal #sdk
Вопрос:
Я пытаюсь реализовать интеграцию на стороне сервера для смарт-кнопок paypal. Я пытался исправить это уже несколько дней. Я новичок в этом, это личный проект, я пытаюсь учиться.
Я продолжаю получать «Ошибка: ожидается передача идентификатора заказа» каждый раз, когда нажимаю на кнопку paypal. Чего мне не хватает?
Это мой код на стороне клиента:
paypal.Buttons({
// Customize button (optional)
style: {
color: 'blue',
shape: 'pill',
},
//Set up a payment
// This function sets up the details of the transaction, including the amount and line item details.
createOrder: function(){
return fetch('<?php echo URLROOT; ?>/libraries/Paypal.php', {
method: 'post',
headers: {
'content-type': 'application/json',
},
}).then(function(res){
//console.log(res.json());
return res.text();
}).then(function(data){
return data.orderID; // Use the same key name for order ID on the client and server
});
},
// Execute the payment
onApprove: function (data) {
//This function captures the funds from the transaction.
return fetch('<?php echo URLROOT; ?>/libraries/Paypal.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
}).then(function (res) {
return res.json();
}).then(function(orderData){
if (errorDetail amp;amp; errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg = 'nn' errorDetail.description;
if (orderData.debug_id) msg = ' (' orderData.debug_id ')';
return alert(msg);
}
alert('Transaction completed by ' orderData.payer.name.given_name);
});
},
onError: function (err){
alert('An Error occured ' err);
}
}).render('#payment-btn');
Это моя серверная часть:
// Creating an environment
$clientId = "HIDDEN";
$clientSecret = "HIDDEN";
$environment = new SandboxEnvironment($clientId, $clientSecret);
$client = new PayPalHttpClient($environment);
// Construct a request object and set desired parameters
// Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
use PayPalCheckoutSdkOrdersOrdersCreateRequest;
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'locale' => 'en-US',
'return_url' => URLROOT.'/bookings/payment',
'cancel_url' => URLROOT.'/bookings/payment'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'EUR',
'value' => $_SESSION["total-price"]
)
)
)
);
try {
// Call API with your client and get a response for your call
$response = $client->execute($request);
return $response->resu<
// If call returns body in response, you can get the deserialized version from the result attribute of the response
print_r($response);
}catch (HttpException $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
use PayPalCheckoutSdkOrdersOrdersCaptureRequest;
// Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders
// $response->result->id gives the orderId of the order created above
//$orderId = $response->result->id;
$request = new OrdersCaptureRequest($orderId);
$request->prefer('return=representation');
try {
// Call API with your client and get a response for your call
$response = $client->execute($request);
// If call returns body in response, you can get the deserialized version from the result attribute of the response
print_r($response);
}catch (HttpException $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
Ответ №1:
Что именно вы возвращаете со своего сервера клиенту? Регистрировали ли вы это либо на стороне сервера, либо проще, используя вкладку «Сеть» инструментов разработчика вашего браузера?
В вашем клиентском коде у вас есть:
return data.orderID; // Use the same key name for order ID on the client and server
Где, в частности, вы устанавливаете ключ «OrderID» со значением «id», возвращаемым API PayPal? Я не вижу, чтобы это где-либо происходило.
Если ваш сервер просто извергает JSON API PayPal, измените свой код на стороне клиента return data.id
на instead, поскольку id
ключ — это то, что используется API PayPal v2 / checkout / orders.
Вот самый простой пример, на котором будет основан ваш HTML / JS: https://developer.paypal.com/demo/checkout/#/pattern/server
Комментарии:
1. Я определенно потратил на это слишком много времени, это было очень просто. Кстати, я не знал об инструменте «Сеть», который также очень помог. Спасибо, действительно ценю.