以下是一個使用 PHP 的 Stripe 支付接口示例,用于創(chuàng)建一個簡單的支付表單并處理支付請求:
以上示例代碼假設您已經(jīng)設置了 Stripe 的 API 密鑰,并使用 Composer 安裝了 Stripe PHP SDK。
請注意,在 `data-key` 屬性中替換為您的 Stripe 公鑰,并在 `setApiKey` 函數(shù)中替換為您的 Stripe 私鑰。此外,您還可以根據(jù)您的需求自定義表單字段和錯誤處理邏輯。
1.設置支付參數(shù)
use Stripe;
public function _initialize()
{
parent::_initialize();
$PaymentModel = new PaymentModel();
$config = $PaymentModel->getCacheClass('stripe');
if(empty($config)) {
echo '支付參數(shù)未配置!';
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';
//如果是沙盒測試環(huán)境不設置,請注釋掉
// $this->PayPal->setConfig(
// array(
// 'mode' => 'live',
// )
// );
}
2. 創(chuàng)建訂單 function create (){
\Stripe\Stripe::setApiKey($this->clientSecret);//私鑰
try {
$jsonStr = file_get_contents('php://input');
$jsonObj = json_decode($jsonStr);//獲取頁面參數(shù)
$arr=object_array($jsonObj);//轉(zhuǎn)換為數(shù)組
$order_id=$arr['items'][0]['order_id'];//訂單單號
$order = db('order')->where('order_id', $order_id)->find();//查找訂單
//訂單是否存在和支付狀態(tài)
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();//獲取網(wǎng)址
$time=time();
//判斷支付訂單是不是已經(jīng)生成
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. 前端創(chuàng)建訂單成功會返回一個訂單key
需要引入官方js
4. 回調(diào)endpoint_secret: 在Webhook設置 回調(diào)的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 的最新版本和最佳實踐相匹配,并根據(jù)您的情況進行自定義和測試。以確保支付交互的安全性和正確性。
如沒特殊注明,文章均為方維網(wǎng)絡原創(chuàng),轉(zhuǎn)載請注明來自http://www.sdlwjx666.com/news/6917.html