搭建外贸独立站商城肯定少不了支付环节,而目前使用最多的除了paypal外,第三方支付平台就stripe用的比较多,里面整合了很多支付方式。
以下是一个使用 PHP 的 Stripe 支付接口示例,用于创建一个简单的支付表单并处理支付请求:
以上示例代码假设您已经设置了 Stripe 的 API 密钥,并使用 Composer 安装了 Stripe PHP SDK。
请注意,在 `data-key` 属性中替换为您的 Stripe 公钥,并在 `setApiKey` 函数中替换为您的 Stripe 私钥。此外,您还可以根据您的需求自定义表单字段和错误处理逻辑。
1.设置支付参数
use Stripe;
public function _initialize()
{
parent::_initialize();
$PaymentModel = new PaymentModel();
$config = $PaymentModel->getCacheClass('stripe');
if(empty($config)) {
echo '支付参数未配置!';
exit();
} else {
$this->clientId = $config['app_id'];
$this->clientSecret = $config['app_key'];
}
$request = Request::instance();
$base_url = $request->domain();
$this->accept_url = $base_url.'/home/paypal/callback';
//如果是沙盒测试环境不设置,请注释掉
// $this->PayPal->setConfig(
// array(
// 'mode' => 'live',
// )
// );
}
2. 创建订单
function create (){
\Stripe\Stripe::setApiKey($this->clientSecret);//私钥
try {
$jsonStr = file_get_contents('php://input');
$jsonObj = json_decode($jsonStr);//获取页面参数
$arr=object_array($jsonObj);//转换为数组
$order_id=$arr['items'][0]['order_id'];//订单单号
$order = db('order')->where('order_id', $order_id)->find();//查找订单
//订单是否存在和支付状态
if(empty($order)) {
echo "can't find order!";
exit();
}
if($order['pay_status'] == 20) {
echo 'The order was paid!';
exit();
}
$request = Request::instance();
$base_url = $request->domain();//获取网址
$time=time();
//判断支付订单是不是已经生成
if(!$order['stripe_pay'] || $time-$order['stripe_time']>30*60){
$currency_list = ExchangeRateModel::getFront();
$currency = $currency_list['code'];
$total_amount_currency = $order['pay_price'];
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $total_amount_currency*100,//订单金额
'currency' => $currency,
'automatic_payment_methods' => [
'enabled' => true,
],
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
$transaction=explode('_secret_',$paymentIntent->client_secret);
$transaction_id=$transaction[0];
db('order')->where('order_id',$order_id)->update(['stripe_pay' => $paymentIntent->client_secret,'stripe_time'=>$time,'transaction_id'=>$transaction_id]);
}else{
$output = [
'clientSecret' => $order['stripe_pay'],
];
}
// Create a PaymentIntent with amount and currency
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}
3. 前端
创建订单成功会返回一个订单key
需要引入官方js
4. 回调
endpoint_secret: 在Webhook设置 回调的secret
public function callback()
{
$endpoint_secret = 'xxxxxxxxxxxxxx';
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
if( $payload){
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
}catch(\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
}
$log_name = "notify_url.log";
$this->log_result($log_name, 'pay-start|--'.$event->data->object->paymentIntent.'--|');
// Handle the event
switch ($event->type) {
case 'charge.succeeded':
$paymentIntent = $event->data->object;
//$payment=json_decode($paymentIntent);
$payID=$paymentIntent->payment_intent;
$order_no=db('order')->where('transaction_id',$payID)->value('order_no');
try {
$total_money = $event->amount/100;
// 实例化订单模型
$model = $this->getOrderModel($order_no, 10);
// 订单信息
$order = $model->getOrderInfo();
if(empty($order)){
echo 'Order not exist';
}
$update_data['transaction_id'] = $payID;
$status = $model->onPaySuccess(20, $update_data);
$this->log_result($log_name, 'order_no:'.$order_no.'pay|--'. $paymentIntent->payment_intent.'--|'.'status:'.$status);
if ($status == false) {
echo $model->getError();
}
} catch (Exception $e) {
$this->error('Pay Error!', 'home/member/order');
//echo $e . ',支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';
//exit();
}
break;
case 'charge.attached':
$paymentMethod = $event->data->object;
$this->log_result($log_name, 'pay-attached|--'.$event->type.'--|');
break;
// ... handle other event types
default:
$this->log_result($log_name, 'pay-fail|--'.$event->type.'--|');
echo 'Received unknown event type '.$event->type ;
}
}
请确保将上述代码与 Stripe 的最新版本和最佳实践相匹配,并根据您的情况进行自定义和测试。以确保支付交互的安全性和正确性。