Paypal-buttons支付 Spb支付
Smart Payment Buttons 简称:spb支付
话不多说 直接上demo
1.首先申请好paypal收款账户;
2.创建应用(分正式版live和沙盒环境)
创建完成后 会生成 Client ID 和 Secret
注意;这里是测试环境的参数 正式环境需要申请live
html代码
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script
<!-- client-id 沙盒环境填写sb live环境填写正常参数 -->
<script src="https://www.paypal.com/sdk/js?&client-id=sb¤cy=USD&locale=en_US" data-sdk-integration-source="button-factory"></script>
</script>
</head>
<body>
<div id="paypal-button-container"></div>
<script>
function initPayPalButton() {
var amount = ‘10.00’; // 金额
var elArr = [amount];
paypal.Buttons({
env: 'production',
style: {
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'paypal',
},
onInit: function (data, actions) {
actions.disable();
elArr.forEach(function (item) {
item.addEventListener('keyup', function (event) {
var result = elArr.every(validate);
if (result) {
actions.enable();
} else {
actions.disable();
}
});
});
},
onClick: function () {
if (amount.value.length < 1) {
alert("Amount required");
return false;
}
},
//创建订单 返回 orderId
createOrder: function (data, actions) {
$("#result").html("");
let total_amt = parseFloat(amount.value),
postData = new FormData();
postData.append('total_amt', total_amt);
return fetch(
'./createOrder.php',
{
method: 'POST',
body: postData
}
).then(function (response) {
return response.json();
}).then(function (resJson) {
return resJson.data.id;
});
},
// 捕获订单,传参orderId 验证后 返回 状态201 代表 支付成功
onApprove: function (data, actions) {
let postData = new FormData();
return fetch(
'./captureOrder.php',
{
method: 'POST',
body: JSON.stringify({
orderID: data.orderID
})
}
).then(function (res) {
return res.json();
}).then(function (details) {
console.log(details);
if (details.error) {
if (details.error === 'INSTRUMENT_DECLINED') {
alert('Your chosen funding source was declined and you will be redirected back to PayPal where you can choose a different funding source');
return actions.restart();
} else {
$("#result").html("<h2>" + details.msg + "</h2>");
}
} else {
if (details.msg == 'COMPLETED' || details.msg == 'PENDING') {
$("#result").html("<h2>" + "Transaction " + details.msg + "</h2>");
} else {
$("#result").html("<h2>" + details.msg + "</h2>");
}
}
});
},
onError: function (err) {
console.log(err);
$("#result").html(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
</body>
需要先引入PayPalCheckoutSdk
https://github.com/paypal/Checkout-PHP-SDK
创建订单代码:createOrder.php
<?php
require __DIR__ . '/vendor/autoload.php';
//这个cofig.php 声明了2个全局变量 clientId 和 clientSecret
require __DIR__ . '/config.php';
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
$environment = new SandboxEnvironment($con['clientId'], $con['clientSecret']);
$client = new PayPalHttpClient($environment);
//获取支付金额
$money=$_POST['total_amt'];
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = [
"intent" => "CAPTURE",
"purchase_units" => [[
"reference_id" => "test_ref_id1",
"amount" => [
"value" => $money,
"currency_code" => "USD"
]
]],
"application_context" => [
"user_action"=> 'CONTINUE',
// 注意这里:NO_SHIPPING 代表是数字产品 无账单地址;
"shipping_preference"=> 'NO_SHIPPING',
"cancel_url" => "https://oiren.com/captureOrder.php", //回调地址
"return_url" => "https://oiren.com/captureOrder.php"
]
];
try {
$response = $client->execute($request);
$res=array(
'ack'=>true,
'data'=>array("id"=>$response->result->id)
);
echo json_encode($res);
exit;
}catch (HttpException $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
捕获订单:captureOrder.php
<?php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/config.php';
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
$environment = new SandboxEnvironment($con['clientId'], $con['clientSecret']);
$client = new PayPalHttpClient($environment);
$content=file_get_contents("php://input");
$json=json_decode($content,true);
$orderID=$json['orderID'];
file_put_contents("1.txt",$orderID.PHP_EOL,FILE_APPEND);
$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(empty($response)){
$response = $client->execute($request);
}
if($response->statusCode == 201){
$aa['msg'] = 'COMPLETED';
}else{
$aa['msg'] == 'error';
}
// If call returns body in response, you can get the deserialized version from the result attribute of the response
echo json_encode($aa);
exit;
//验证通过获取到订单的详细信息可以写入到数据库
}catch (HttpException $ex) {
echo $ex->statusCode;
var_dump($ex->getMessage());
}
到这里支付流程就跑完了,
测试的时候可以先用palpay的测试账户 进行测试;
ps:测试环境请求的api接口不同,需修改api路径;
/vendor/paypal/paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/SandboxEnvironment.php
换到正式环境 不要忘记切换请求地址;
有问题可以给我留言;