PayStripeApi.php
6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
<?php
/**
* @remark :
* @name :PayStripeApi.php
* @author :lyh
* @method :post
* @time :2024/12/24 10:35
*/
namespace App\Helper;
class PayStripeApi
{
private $secretKey;
//币种对应支付方式
public $currency_types = [
'usd' => ['card', 'alipay', 'wechat_pay', 'cashapp', 'link', 'afterpay_clearpay'],
'eur' => ['card', 'ideal', 'giropay', 'sofort', 'bancontact', 'klarna', 'link'],
'gbp' => ['card', 'apple_pay', 'google_pay', 'klarna', 'link', 'afterpay_clearpay'],
'aud' => ['card', 'afterpay_clearpay', 'apple_pay', 'google_pay'],
'cad' => ['card', 'apple_pay', 'google_pay', 'link'],
'sgd' => ['card', 'grabpay', 'fpx', 'wechat_pay', 'apple_pay', 'google_pay'],
'jpy' => ['card', 'apple_pay', 'google_pay'],
'cny' => ['alipay', 'wechat_pay'],
'brl' => ['card', 'boleto', 'pix'],
'mxn' => ['card', 'oxxo'],
'inr' => ['card', 'upi', 'netbanking'],
'php' => ['card', 'paymaya', 'gcash'],
'myr' => ['card', 'fpx'],
'thb' => ['card', 'promptpay'],
'idr' => ['card', 'bank_transfer'],
'zar' => ['card'],
'ngn' => ['card'],
'aed' => ['card', 'apple_pay', 'google_pay']
];
// 构造函数设置密钥
public function __construct()
{
$this->secretKey = 'sk_test_51MyseXIWCYVeLww1tbPZzRe1Qk4lS5d2VLiDjpju7G0ToiX1RJcFinQXNlftq9eCjZE0n2gjaz1mfy1g0mxTusdf00m636Gv62';
}
/**
* @remark :通用的 cURL 请求方法
* @name :sendRequest
* @author :lyh
* @method :post
* @time :2024/12/24 10:38
*/
private function sendRequest($url, $method = 'POST', $data = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$this->secretKey}",
"Content-Type: application/x-www-form-urlencoded"
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
} elseif ($method === 'GET') {
curl_setopt($ch, CURLOPT_HTTPGET, true);
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception('cURL Error: ' . curl_error($ch));
}
curl_close($ch);
return json_decode($response, true);
}
/**
* @remark :创建支付意图
* @name :createPaymentIntent
* @author :lyh
* @method :post
* @time :2024/12/24 10:38
*/
public function createPaymentIntent($amount, $currency = 'usd', $paymentMethodTypes = 'card')
{
$url = "https://api.stripe.com/v1/payment_intents";
$data = [
'amount' => $amount,
'currency' => $currency,
'payment_method_types[]' => $paymentMethodTypes,
];
return $this->sendRequest($url, 'POST', $data);
}
/**
* @remark :查询支付意图
* @name :retrievePaymentIntent
* @author :lyh
* @method :post
* @time :2024/12/24 10:38
*/
public function retrievePaymentIntent($paymentIntentId)
{
$url = "https://api.stripe.com/v1/payment_intents/{$paymentIntentId}";
return $this->sendRequest($url, 'GET');
}
/**
* @remark :创建退款
* @name :createRefund
* @author :lyh
* @method :post
* @time :2024/12/24 10:42
*/
public function createRefund($chargeId, $amount = null)
{
$url = "https://api.stripe.com/v1/refunds";
$data = ['charge' => $chargeId];
if ($amount) {
$data['amount'] = $amount;
}
return $this->sendRequest($url, 'POST', $data);
}
/**
* @remark :查询退款
* @name :retrieveRefund
* @author :lyh
* @method :post
* @time :2024/12/24 10:42
*/
public function retrieveRefund($refundId)
{
$url = "https://api.stripe.com/v1/refunds/{$refundId}";
return $this->sendRequest($url, 'GET');
}
/**
* @remark :处理 Webhook
* @name :handleWebhook
* @author :lyh
* @method :post
* @time :2024/12/24 10:43
*/
public static function handleWebhook()
{
try {
// Webhook 签名密钥(从 Stripe 仪表盘获取)
$endpointSecret = 'whsec_garhW2TrCIrduyM3rve9mFS2sn69B9Yt';
// 获取原始请求内容
$payload = request()->getContent();
// 获取 Stripe 签名头
$sigHeader = request()->header('Stripe-Signature');
// 验证签名
if (!self::verifySignature($payload, $sigHeader, $endpointSecret)) {
http_response_code(400);
throw new Exception('Invalid signature');
}
$event = json_decode($payload, true);
// 获取事件类型
$eventType = $event['type'];
$eventData = $event['data']['object'];
// 根据事件类型处理
switch ($eventType) {
case 'payment_intent.succeeded':
// 处理支付成功逻辑
@file_put_contents(storage_path('logs/lyh_error.log'), var_export($eventType, true) . PHP_EOL, FILE_APPEND);
@file_put_contents(storage_path('logs/lyh_error.log'), var_export($eventData, true) . PHP_EOL, FILE_APPEND);
$paymentIntentId = $eventData['id'];
break;
case 'payment_intent.payment_failed':
// 处理支付失败逻辑
$error = $eventData['last_payment_error'];
break;
case 'charge.refunded':
// 处理退款逻辑
$chargeId = $eventData['id'];
break;
default:
throw new Exception('Unhandled event type: ' . $eventType);
}
return $event;
} catch (Exception $e) {
throw new Exception('Webhook Error: ' . $e->getMessage());
}
}
/**
* @remark :验证签名
* @name :verifySignature
* @author :lyh
* @method :post
* @time :2024/12/24 15:55
*/
private function verifySignature($payload, $sigHeader, $endpointSecret)
{
// 获取 Stripe 签名
$signatures = [];
if (preg_match_all('/t=\d+,v1=([a-f0-9]+)/', $sigHeader, $matches)) {
$signatures = $matches[1];
}
// 计算签名哈希值
$expectedSignature = hash_hmac('sha256', $payload, $endpointSecret);
return in_array($expectedSignature, $signatures, true);
}
}