以下(xià)是一個(gè)使用(yòng) PHP 的(de) Stripe 支付接口示例,用(yòng)于創建一個(gè)簡單的(de)支付表單并處理(lǐ)支付請求:
以上示例代碼假設您已經設置了(le) Stripe 的(de) API 密鑰,并使用(yòng) Composer 安裝了(le) Stripe PHP SDK。
請注意,在 `data-key` 屬性中替換爲您的(de) Stripe 公鑰,并在 `setApiKey` 函數中替換爲您的(de) Stripe 私鑰。此外,您還(hái)可(kě)以根據您的(de)需求自定義表單字段和(hé)錯誤處理(lǐ)邏輯。
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();//查找訂單
//訂單是否存在和(hé)支付狀态
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. 前端創建訂單成功會返回一個(gè)訂單key
需要引入官方js
4. 回調endpoint_secret: 在Webhook設置 回調的(de)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;
// 實例化(huà)訂單模型
$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 . '】,支付人(rén)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 的(de)最新版本和(hé)最佳實踐相匹配,并根據您的(de)情況進行自定義和(hé)測試。以确保支付交互的(de)安全性和(hé)正确性。
如沒特殊注明(míng),文章(zhāng)均爲方維網絡原創,轉載請注明(míng)來(lái)自