基于Lumen-微信支付

用户在商家app内选择微信支付下单成功后,商家通过平台提供的接口获取到唤起微信支付的参数信息,然后在商家app内唤起微信支付,用户在微信内确认支付后会自动返回到用户app内。

微信支付调用流程

微信支付 调用流程

原图点击–> 业务流程

支付准备

请求参数列表

https://open.swiftpass.cn/openapi/doc?index_1=4&index_2=1&chapter_1=516&chapter_2=546

  • 请求url: https://pay.swiftpass.cn/pay/gateway

POST XML 内容体进行请求

直接上源码

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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<?php

// Weixin payment operations (Non-official)
// see docs: <https://open.swiftpass.cn/openapi>
// @caoxl

namespace App\Http\Controllers\Payment;

use
Illuminate\Support\Facades\Validator,
Illuminate\Http\Request,
App\Models\Finance\RefundLog;

use App\Traits\{Client, Tool};
use App\Models\User\{User, PaymentLog};

class Wxpay implements \App\Contract\PaymentMethod
{
use \App\Traits\CURL;

private $config = null;
private $amountEscape = 1;

/**
* @param array $params
* @return array|bool
*/
public function prepare(array &$params)
{
if (true !== ($configCheckRes = $this->checkConfig())) {
return $configCheckRes;
} elseif (true !== ($paramsValidateRes = $this->validate($params, [
'client' => 'required|in:wap,mobile',
'amount' => 'required|numeric|min:0.01',
'notify' => 'required|url',
'origin' => 'required',
'mid' => 'required|integer|min:1',
'desc' => 'required',
]))) {
return $paramsValidateRes;
}

if ('wap' == $params['client']) {
if (true !== ($hasReturnUrl = $this->validate($params, [
'wxuser_openid' => 'required',
'return' => 'required|url',
]))) {
return $hasReturnUrl;
}

/*if (!isset($params['wxuser_openid'])) {
if (false === ($openID = $this->findUserWxOpenID(
$params['mid']
))) {
return [
'err' => 5002,
'msg' => Tool::sysMsg('MISSING_WXUSER_OPENID'),
];
} else {
$params['wxuser_openid'] = $openID;
}
}*/
}

return $this->createPaymentLog($params);
}

/**
* @param int $uid
* @return bool
*/
protected function findUserWxOpenID(int $uid)
{
$user = User::find($uid);

if (!$user || !isset($user->wx_openid) || !$user->wx_openid) {
return false;
}

return $user->wx_openid;
}

/**
* @return array|bool
*/
protected function checkConfig()
{
$this->config = config('custom')['wxpay_wft'] ?? [];

if (! $this->config) {
return [
'err' => 5001,
'msg' => Tool::sysMsg('MISSING_WFT_WXPAY_CONFIG'),
];
} elseif (true !== ($configValidateRes = $this->validate($this->config, [
'gateway' => 'required|url',
'jspay_url' => 'required|url',
'appid_app' => 'required',
'appid_wap' => 'required',
'key_app' => 'required',
'key_wap' => 'required',
'mchid_app' => 'required',
'mchid_wap' => 'required',
]))) {
return $configValidateRes;
}

return true;
}

/**
* @param array $params
* @return array|bool
*/
protected function createPaymentLog(array &$params)
{
// Generate a trade no and create an payment log record of this user
$params['trade_no'] = $params['trade_no']
?? Tool::tradeNo($params['mid']);

$params['client_ip'] = Client::ip();

$data = [
'uid' => $params['mid'],
'from' => $params['origin'],
'payment' => 'wxpay',
'trade_no' => $params['trade_no'],
'amount' => $params['amount'],
'payed' => 0,
'clientip' => $params['client_ip'],
'dateline' => time(),
];

$_data = [
'__wx_client' => $params['client']
];

if (isset($params['order_id']) && $params['order_id']) {
$data['order_id'] = $params['order_id'];
}

if (isset($params['data'])
&& is_array($params['data'])
&& $params['data']
) {
$_data = array_merge($_data, $params['data']);
}

$data['data'] = json_encode(
$_data,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);

$paymentLoggedId = PaymentLog::insertGetId($data);

return $paymentLoggedId ? true : [
'err' => 5001,
'msg' => Tool::sysMsg('DATA_UPDATE_ERROR'),
];
}

/**
* @param array $params
* @param array $rules
* @return array|bool
*/
protected function validate(array $params, array $rules)
{
$validator = Validator::make($params, $rules);

if ($validator->fails()) {
return [
'err' => 400,
'msg' => $validator->errors()->first(),
];
}

return true;
}

/**
* @return string
*/
protected function nonceStr(): string
{
return mt_rand(time(), time()+rand());
}

/**
* @param array $params
* @param string $key
* @return string
*/
protected function sign(array $params, string $key): string
{
$sign = '';
ksort($params);
foreach ($params as $k => $v) {
if (is_scalar($v) && ('' != $v) && ('sign' != $k)) {
$sign .= $k.'='.$v.'&';
}
}
$sign .= 'key='.$key;
$sign = strtoupper(md5($sign));

return $sign;
}

/**
* @return RefundLog
*/
protected function refundLog()
{
return new RefundLog;
}

/**
* @param array $params
* @return array|bool
*/
public function refund(array $params)
{
if (true !== ($configCheckRes = $this->checkConfig())) {
return $configCheckRes;
} elseif (true !== ($legalParams = $this->validate($params, [
'paylog_id' => 'required|integer|min:1',
'id_type' => 'required|in:transaction_id,out_trade_no',
'trade_no' => 'required',
'amount' => 'required|numeric|min:0.01',
'operator' => 'required',
]))) {
return $legalParams;
}

$createAt = date('Y-m-d H:i:s');

try {
$paymentLog = PaymentLog::select('amount', 'data')
->whereLogId($params['paylog_id'])
->first();

if (! ($amountTotal = $paymentLog->amount)) {
return [
'err' => 5001,
'msg' => Tool::sysMsg('No_PAYMENT_LOG'),
];
}

if ($paymentLog->data
&& ($extra = json_decode($paymentLog->data, true))
&& isset($extra['__wx_client'])
&& ('wap' == $extra['__wx_client'])
) {
$wxClient = 'wap';
} else {
$wxClient = 'app';
}

// Check if all trade amount refunded already
$refundLog = $this->refundLog();
$refundedAmount = $refundLog->refundedAmount(
$params['paylog_id'],
'wxpay'
);

if ($refundedAmount->amountRefunded) {
$amountRefunded = floatval($refundedAmount->amountRefunded);
$amountTotal = floatval($amountTotal);
$amountCanBeRefunded = abs($amountTotal - $amountRefunded);

if ($amountTotal < $amountCanBeRefunded) {
return [
'err' => 5002,
'msg' => Tool::sysMsg('REFUND_AMOUNT_ILLEGAL'),
];
} elseif ($amountRefunded >= $amountTotal) {
return [
'err' => 5003,
'msg' => Tool::sysMsg('REFUNDED_ALL_ALREADY'),
];
}
}

$totalFee = $this->getIntFee($amountTotal);
$refundFee = $this->getIntFee($params['amount']);

if ((false === $totalFee) || (false === $refundFee)) {
return [
'err' => 5004,
'msg' => Tool::sysMsg('ILLEGAL_FEE_AMOUNT'),
];
}

$data = [
'service' => 'unified.trade.refund',
'mch_id' => $this->config['mchid_'.$wxClient],
'total_fee' => $totalFee,
'refund_fee' => $refundFee,
'op_user_id' => 'mch_wxpay_program', // static
'nonce_str' => $this->nonceStr(),
'out_refund_no' => Tool::tradeNo(0, '04'),
];
$data[$params['id_type']] = $params['trade_no'];
$data['sign'] = $this->sign(
$data,
$this->config['key_'.$wxClient]
);

$xml = Tool::arrayToXML($data);

$res = $this->requestHTTPApi(
$this->config['gateway'],
'POST', [
'Content-Type: application/xml; Charset=UTF-8',
],
$xml
);

$processAt = date('Y-m-d H:i:s');

$res['dat'] = Tool::xmlToArray($res['res']);

unset($res['res']);

// Check if sign is from swiftpass.cn (No need here anyway)
// $legalRet = $res['dat']['sign']==$this->sign($res['dat'])

$errMsg = $res['dat']['err_msg'] ?? false;

$reason = $params['reason']
?? Tool::sysMsg('REFUND_REASON_COMMON');

$_data = [
'refund_no' => $data['out_refund_no'],
'paylog_id' => $params['paylog_id'],
'amount' => $params['amount'],
'reason_request' => $reason,
'operator' => $params['operator'],
'create_at' => $createAt,
'process_at' => $processAt,
];

$refundSuccess = false;
if (isset($res['dat']['status'])
&& (0 == $res['dat']['status'])
&& isset($res['dat']['result_code'])
&& (0 == $res['dat']['result_code'])
&& isset($res['dat']['refund_id'])
) {
// Insert or update into refund log
$_data['status'] = 1;
$_data['out_refund_no'] = $res['dat']['refund_id'];

if (! $refundLog->insert($_data)) {
return [
'err' => '503X',
'msg' => Tool::sysMsg('DATA_UPDATE_ERROR'),
];
}

$refundSuccess = true;
}

if ($refundSuccess) {
return [
'err' => 0,
'msg' => 'ok',
];
} elseif ($errMsg) {
$_data['status'] = 2;
$_data['reason_fail'] = $errMsg;

if (! $refundLog->insert($_data)) {
return [
'err' => '503X',
'msg' => Tool::sysMsg('DATA_UPDATE_ERROR'),
];
}

return [
'err' => 5005,
'msg' => $errMsg,
];
} else {
return [
'err' => 5006,
'msg' => Tool::sysMsg('REFUND_REQUEST_FAILED'),
];
}

} catch (\Exception $e) {
return [
'err' => '500X',
'msg' => $e->getMessage(),
];
}
}

/**
* @param float $amount
* @return array|bool|float
*/
public function getIntFee(float $amount)
{
$amount = explode('.', $amount*100);
$amount = isset($amount[0]) ? intval($amount[0]) : false;

return $amount;
}

/**
* @param array $params
* @return array
*/
public function pay(array &$params): array
{
if (true !== ($prepareRes = $this->prepare($params))) {
return $prepareRes;
}

$this->amountEscape = in_array(
env('APP_ENV'), ['local', 'test', 'stage',]
) ? 1 : $this->getIntFee($params['amount']);

if (false === $this->amountEscape) {
return [
'err' => 5001,
'msg' => Tool::sysMsg('ILLEGAL_FEE_AMOUNT'),
];
}

$_params = [
'out_trade_no' => $params['trade_no'],
'body' => $params['desc'],
'total_fee' => $this->amountEscape,
'mch_create_ip' => $params['client_id'],
'notify_url' => $params['notify'],
'nonce_str' => $this->nonceStr(),
];

$fillPayDataHandler = 'fillPayDataFor'.ucfirst($params['client']);

if (! method_exists($this, $fillPayDataHandler)) {
return [
'err' => 5002,
'msg' => Tool::sysMsg('MISSING_PAY_METHOD_HANDLER'),
];
}

return $this->$fillPayDataHandler($_params, $params);
}

/**
* @param array $params
* @param array $_params
* @return array
*/
protected function fillPayDataForWap(array $params, array $_params)
{
$params['service'] = 'pay.weixin.jspay';
$params['sub_openid'] = $_params['wxuser_openid'];
$params['callback_url'] = $_params['return'];
$params['mch_id'] = $this->config['mchid_wap'];
$params['sub_appid'] = $this->config['appid_wap'];
$params['sign'] = $this->sign($params, $this->config['key_wap']);

$xml = Tool::arrayToXML($params);

$res = $this->requestHTTPApi(
$this->config['gateway'],
'POST', [
'Content-Type: application/xml; Charset=UTF-8',
],
$xml
);

if (! ($ret = Tool::xmlToArray($res['res']))
|| !isset($ret['token_id'])
|| !($tokenId = $ret['token_id'])
) {
return [
'err' => 5001,
'msg' => (
$ret['message'] ?? Tool::sysMsg('WXPAY_REQUEST_FAILED')
),
];
}

$res['dat']['url'] = base64_encode(
$this->config['jspay_url'].'?token_id='.$tokenId
);

unset($res['res']);

return $res;
}

/**
* @param array $params
* @param array $_params
* @return array
*/
protected function fillPayDataForMobile(array $params, array $_params)
{
$params['service'] = 'unified.trade.pay';
$params['mch_id'] = $this->config['mchid_app'];
$params['sub_appid'] = $this->config['appid_app'];
$params['sign'] = $this->sign($params, $this->config['key_app']);

$xml = Tool::arrayToXML($params);

$res = $this->requestHTTPApi(
$this->config['gateway'],
'POST', [
'Content-Type: application/xml; Charset=UTF-8',
],
$xml
);

$res['dat']['params'] = Tool::xmlToArray($res['res']);

// For IOS SDK use only
$res['dat']['params']['amount'] = $this->amountEscape;

unset($res['res']);

return $res;
}

/**
* @param $transHook
* @param string $client
* @return string
*/
public function payCallback($transHook, $client = 'app'): string
{
$params = [];

if (true === $this->tradeSuccess($params, $client)) {
// Update payment log
// Execute wxpay caller's transhook
// Find out the payment log
$paymentLog = PaymentLog::select(
'log_id', 'uid', 'amount', 'clientip'
)->whereTradeNoAndPayedAndPayment(
$params['out_trade_no'],
0,
'wxpay'
)->first();

if (!$paymentLog || !isset($paymentLog->uid)) {
return 'fail';
} elseif (!($user = User::find($paymentLog->uid))) {
return 'fail';
}

\DB::beginTransaction();

$timestamp = time();
// Execute transaction hook
$transHookSuccess = $transHook(
$user,
$paymentLog->amount,
'wxpay',
$paymentLog->clientip,
$timestamp
);

if ($transHookSuccess) {
// Update payment log
$updatedPayStatus = PaymentLog::whereLogId(
$paymentLog->log_id
)->update([
'payed' => 1,
'payedip' => $paymentLog->clientip,
'pay_trade_no' => $params['transaction_id'],
'payedtime' => $timestamp,
]);

if ($updatedPayStatus >= 0) {
\DB::commit();

return 'success';
}
}

\DB::rollBack();
}

return 'fail';
}

// Verify callback is from swiftpass.cn and payment is success
/**
* @param array $params
* @param string $client
* @return array|bool
*/
public function tradeSuccess(array &$params = [], $client = 'app')
{
$this->config = config('custom')['wxpay_wft'] ?? false;

if (!in_array($client, ['app', 'wap'])) {
return [
'err' => 5001,
'msg' => Tool::sysMsg('ILLEGAL_CLIENT_TYPE'),
];
}

if (true !== ($configValidateRes = $this->validate($this->config, [
'key_'.$client => 'required',
]))) {
return $configValidateRes;
}

$params = Tool::xmlToArray(file_get_contents('php://input'));

if ($params
&& is_array($params)
&& isset($params['sign'])
&& isset($params['result_code'])
&& isset($params['total_fee'])
&& ($params['sign'] == $this->sign(
$params,
$this->config['key_'.$client])
)
&& (0 == $params['status'])
&& (0 == $params['result_code'])
&& (0 < $params['total_fee'])
) {
return true;
}

return false;
}

/**
* @return float
*/
protected function getRefundFee()
{
return 0.008;
}
}

说明

  • \App\Contract\PaymentMethod - 见:基于Laravel/Lumen-支付宝支付(Alipay)

  • \App\Traits\CURL - 「代码复用」 CURL

  • public function prepare(array &params): 支付准备

  • protected function findUserWxOpendID(): 获得用户openid

  • protectec function checkConfig(): 检查配置

  • protected function createPaymentLog(array &$params): 生成支付日志

  • protected function validate(array $params, array $rules): 数据验证

  • protected function nonceStr(): string: 生成随机字符串

  • protected function sign(array $params, string $key): string: 生成签名

  • protected function refundLog(): 退款日志

  • public function refund(array $params): 微信退款

  • public function getIntFee(float $amount): 所有涉及到金额的单位都是分,最小的单位是1分,不能有小数出现

  • public function pay(array $params): array: 微信支付操作

  • protected function fillPayDataForWap(array $params, array $_params): 微信电脑端支付

  • protected function fillPayDataForMobile(array $params, array $_params): 微信手机端支付

  • public function payCallback($transHook, $client = 'app'):string: 微信支付回调

  • public function tradeSuccess(array &$params = [], $client = 'app'): 交易验证

  • protected function getRefundFee(): 获取退款金额

本文仅供参考, 请结合文档以及具体需求, 编写适合自己的代码.

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :