Passed
Pull Request — master (#993)
by Songda
11:53
created

get_douyin_config()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Yansongda\Artful\Contract\ConfigInterface;
10
use Yansongda\Artful\Exception\ContainerException;
11
use Yansongda\Artful\Exception\InvalidConfigException;
12
use Yansongda\Artful\Exception\InvalidParamsException;
13
use Yansongda\Artful\Exception\ServiceNotFoundException;
14
use Yansongda\Artful\Plugin\AddPayloadBodyPlugin;
15
use Yansongda\Artful\Plugin\ParserPlugin;
16
use Yansongda\Artful\Plugin\StartPlugin;
17
use Yansongda\Pay\Exception\DecryptException;
18
use Yansongda\Pay\Exception\Exception;
19
use Yansongda\Pay\Exception\InvalidSignException;
20
use Yansongda\Pay\Plugin\Wechat\AddRadarPlugin;
21
use Yansongda\Pay\Plugin\Wechat\ResponsePlugin;
22
use Yansongda\Pay\Plugin\Wechat\V3\AddPayloadSignaturePlugin;
23
use Yansongda\Pay\Plugin\Wechat\V3\WechatPublicCertsPlugin;
24
use Yansongda\Pay\Provider\Alipay;
25
use Yansongda\Pay\Provider\Unipay;
26
use Yansongda\Pay\Provider\Wechat;
27
use Yansongda\Supports\Collection;
28
29
use function Yansongda\Artful\get_radar_body;
30
use function Yansongda\Artful\get_radar_method;
31
32
function get_tenant(array $params = []): string
33
{
34
    return strval($params['_config'] ?? 'default');
35
}
36
37
function get_public_cert(string $key): string
38
{
39
    return is_file($key) ? file_get_contents($key) : $key;
40
}
41
42
function get_private_cert(string $key): string
43
{
44
    if (is_file($key)) {
45
        return file_get_contents($key);
46
    }
47
48
    return "-----BEGIN RSA PRIVATE KEY-----\n".
49
        wordwrap($key, 64, "\n", true).
50
        "\n-----END RSA PRIVATE KEY-----";
51
}
52
53
function get_radar_url(array $config, ?Collection $payload): ?string
54
{
55
    return match ($config['mode'] ?? Pay::MODE_NORMAL) {
56
        Pay::MODE_SERVICE => $payload?->get('_service_url') ?? $payload?->get('_url') ?? null,
57
        Pay::MODE_SANDBOX => $payload?->get('_sandbox_url') ?? $payload?->get('_url') ?? null,
58
        default => $payload?->get('_url') ?? null,
59
    };
60
}
61
62
/**
63
 * @throws ContainerException
64
 * @throws ServiceNotFoundException
65
 */
66
function get_alipay_config(array $params = []): array
67
{
68
    $alipay = Pay::get(ConfigInterface::class)->get('alipay');
69
70
    return $alipay[get_tenant($params)] ?? [];
71
}
72
73
function get_alipay_url(array $config, ?Collection $payload): string
74
{
75
    $url = get_radar_url($config, $payload) ?? '';
76
77
    if (str_starts_with($url, 'http')) {
78
        return $url;
79
    }
80
81
    return Alipay::URL[$config['mode'] ?? Pay::MODE_NORMAL];
82
}
83
84
/**
85
 * @throws InvalidConfigException
86
 * @throws InvalidSignException
87
 */
88
function verify_alipay_sign(array $config, string $contents, string $sign): void
89
{
90
    if (empty($sign)) {
91
        throw new InvalidSignException(Exception::SIGN_EMPTY, '签名异常: 验证支付宝签名失败-支付宝签名为空', func_get_args());
92
    }
93
94
    $public = $config['alipay_public_cert_path'] ?? null;
95
96
    if (empty($public)) {
97
        throw new InvalidConfigException(Exception::CONFIG_ALIPAY_INVALID, '配置异常: 缺少支付宝配置 -- [alipay_public_cert_path]');
98
    }
99
100
    $result = 1 === openssl_verify(
101
        $contents,
102
        base64_decode($sign),
103
        get_public_cert($public),
104
        OPENSSL_ALGO_SHA256
105
    );
106
107
    if (!$result) {
108
        throw new InvalidSignException(Exception::SIGN_ERROR, '签名异常: 验证支付宝签名失败', func_get_args());
109
    }
110
}
111
112
/**
113
 * @throws ContainerException
114
 * @throws ServiceNotFoundException
115
 */
116
function get_wechat_config(array $params = []): array
117
{
118
    $wechat = Pay::get(ConfigInterface::class)->get('wechat');
119
120
    return $wechat[get_tenant($params)] ?? [];
121
}
122
123
function get_wechat_method(?Collection $payload): string
124
{
125
    return get_radar_method($payload) ?? 'POST';
126
}
127
128
/**
129
 * @throws InvalidParamsException
130
 */
131
function get_wechat_url(array $config, ?Collection $payload): string
132
{
133
    $url = get_radar_url($config, $payload);
134
135
    if (empty($url)) {
136
        throw new InvalidParamsException(Exception::PARAMS_WECHAT_URL_MISSING, '参数异常: 微信 `_url` 或 `_service_url` 参数缺失:你可能用错插件顺序,应该先使用 `业务插件`');
137
    }
138
139
    if (str_starts_with($url, 'http')) {
140
        return $url;
141
    }
142
143
    return Wechat::URL[$config['mode'] ?? Pay::MODE_NORMAL].$url;
144
}
145
146
/**
147
 * @throws InvalidParamsException
148
 */
149
function get_wechat_body(?Collection $payload): mixed
150
{
151
    $body = get_radar_body($payload);
152
153
    if (is_null($body)) {
154
        throw new InvalidParamsException(Exception::PARAMS_WECHAT_BODY_MISSING, '参数异常: 微信 `_body` 参数缺失:你可能用错插件顺序,应该先使用 `AddPayloadBodyPlugin`');
155
    }
156
157
    return $body;
158
}
159
160
function get_wechat_type_key(array $params): string
161
{
162
    $key = ($params['_type'] ?? 'mp').'_app_id';
163
164
    if ('app_app_id' === $key) {
165
        $key = 'app_id';
166
    }
167
168
    return $key;
169
}
170
171
/**
172
 * @throws InvalidConfigException
173
 */
174
function get_wechat_sign(array $config, string $contents): string
175
{
176
    $privateKey = $config['mch_secret_cert'] ?? null;
177
178
    if (empty($privateKey)) {
179
        throw new InvalidConfigException(Exception::CONFIG_WECHAT_INVALID, '配置异常: 缺少微信配置 -- [mch_secret_cert]');
180
    }
181
182
    $privateKey = get_private_cert($privateKey);
183
184
    openssl_sign($contents, $sign, $privateKey, 'sha256WithRSAEncryption');
185
186
    return base64_encode($sign);
187
}
188
189
/**
190
 * @throws InvalidConfigException
191
 */
192
function get_wechat_sign_v2(array $config, array $payload, bool $upper = true): string
193
{
194
    $key = $config['mch_secret_key_v2'] ?? null;
195
196
    if (empty($key)) {
197
        throw new InvalidConfigException(Exception::CONFIG_WECHAT_INVALID, '配置异常: 缺少微信配置 -- [mch_secret_key_v2]');
198
    }
199
200
    ksort($payload);
201
202
    $buff = '';
203
204
    foreach ($payload as $k => $v) {
205
        $buff .= ('sign' != $k && '' != $v && !is_array($v)) ? $k.'='.$v.'&' : '';
206
    }
207
208
    $sign = md5($buff.'key='.$key);
209
210
    return $upper ? strtoupper($sign) : $sign;
211
}
212
213
/**
214
 * @throws ContainerException
215
 * @throws DecryptException
216
 * @throws InvalidConfigException
217
 * @throws InvalidParamsException
218
 * @throws InvalidSignException
219
 * @throws ServiceNotFoundException
220
 */
221
function verify_wechat_sign(ResponseInterface|ServerRequestInterface $message, array $params): void
222
{
223
    if ($message instanceof ServerRequestInterface && 'localhost' === $message->getUri()->getHost()) {
224
        return;
225
    }
226
227
    $wechatSerial = $message->getHeaderLine('Wechatpay-Serial');
228
    $timestamp = $message->getHeaderLine('Wechatpay-Timestamp');
229
    $random = $message->getHeaderLine('Wechatpay-Nonce');
230
    $sign = $message->getHeaderLine('Wechatpay-Signature');
231
    $body = (string) $message->getBody();
232
233
    $content = $timestamp."\n".$random."\n".$body."\n";
234
    $public = get_wechat_config($params)['wechat_public_cert_path'][$wechatSerial] ?? null;
235
236
    if (empty($sign)) {
237
        throw new InvalidSignException(Exception::SIGN_EMPTY, '签名异常: 微信签名为空', ['headers' => $message->getHeaders(), 'body' => $body]);
238
    }
239
240
    $public = get_public_cert(
241
        empty($public) ? reload_wechat_public_certs($params, $wechatSerial) : $public
242
    );
243
244
    $result = 1 === openssl_verify(
245
        $content,
246
        base64_decode($sign),
247
        $public,
248
        'sha256WithRSAEncryption'
249
    );
250
251
    if (!$result) {
252
        throw new InvalidSignException(Exception::SIGN_ERROR, '签名异常: 验证微信签名失败', ['headers' => $message->getHeaders(), 'body' => $body]);
253
    }
254
}
255
256
/**
257
 * @throws InvalidConfigException
258
 * @throws InvalidSignException
259
 */
260
function verify_wechat_sign_v2(array $config, array $destination): void
261
{
262
    $sign = $destination['sign'] ?? null;
263
264
    if (empty($sign)) {
265
        throw new InvalidSignException(Exception::SIGN_EMPTY, '签名异常: 微信签名为空', $destination);
266
    }
267
268
    $key = $config['mch_secret_key_v2'] ?? null;
269
270
    if (empty($key)) {
271
        throw new InvalidConfigException(Exception::CONFIG_WECHAT_INVALID, '配置异常: 缺少微信配置 -- [mch_secret_key_v2]');
272
    }
273
274
    if (get_wechat_sign_v2($config, $destination) !== $sign) {
275
        throw new InvalidSignException(Exception::SIGN_ERROR, '签名异常: 验证微信签名失败', $destination);
276
    }
277
}
278
279
function encrypt_wechat_contents(string $contents, string $publicKey): ?string
280
{
281
    if (openssl_public_encrypt($contents, $encrypted, get_public_cert($publicKey), OPENSSL_PKCS1_OAEP_PADDING)) {
282
        return base64_encode($encrypted);
283
    }
284
285
    return null;
286
}
287
288
function decrypt_wechat_contents(string $encrypted, array $config): ?string
289
{
290
    if (openssl_private_decrypt(base64_decode($encrypted), $decrypted, get_private_cert($config['mch_secret_cert'] ?? ''), OPENSSL_PKCS1_OAEP_PADDING)) {
291
        return $decrypted;
292
    }
293
294
    return null;
295
}
296
297
/**
298
 * @throws ContainerException
299
 * @throws DecryptException
300
 * @throws InvalidConfigException
301
 * @throws InvalidParamsException
302
 * @throws ServiceNotFoundException
303
 */
304
function reload_wechat_public_certs(array $params, ?string $serialNo = null): string
305
{
306
    $data = Pay::wechat()->pay(
307
        [StartPlugin::class, WechatPublicCertsPlugin::class, AddPayloadBodyPlugin::class, AddPayloadSignaturePlugin::class, AddRadarPlugin::class, ResponsePlugin::class, ParserPlugin::class],
308
        $params
309
    )->get('data', []);
0 ignored issues
show
Bug introduced by
The method get() does not exist on Psr\Http\Message\MessageInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

309
    )->/** @scrutinizer ignore-call */ get('data', []);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
310
311
    $wechatConfig = get_wechat_config($params);
312
313
    foreach ($data as $item) {
314
        $certs[$item['serial_no']] = decrypt_wechat_resource($item['encrypt_certificate'], $wechatConfig)['ciphertext'] ?? '';
315
    }
316
317
    Pay::get(ConfigInterface::class)->set(
318
        'wechat.'.get_tenant($params).'.wechat_public_cert_path',
319
        ((array) ($wechatConfig['wechat_public_cert_path'] ?? [])) + ($certs ?? []),
320
    );
321
322
    if (!is_null($serialNo) && empty($certs[$serialNo])) {
323
        throw new InvalidConfigException(Exception::CONFIG_WECHAT_INVALID, '配置异常: 获取微信 wechat_public_cert_path 配置失败');
324
    }
325
326
    return $certs[$serialNo] ?? '';
327
}
328
329
/**
330
 * @throws ContainerException
331
 * @throws DecryptException
332
 * @throws InvalidConfigException
333
 * @throws InvalidParamsException
334
 * @throws ServiceNotFoundException
335
 */
336
function get_wechat_public_certs(array $params = [], ?string $path = null): void
337
{
338
    reload_wechat_public_certs($params);
339
340
    $config = get_wechat_config($params);
341
342
    if (empty($path)) {
343
        var_dump($config['wechat_public_cert_path']);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($config['wechat_public_cert_path']) looks like debug code. Are you sure you do not want to remove it?
Loading history...
344
345
        return;
346
    }
347
348
    foreach ($config['wechat_public_cert_path'] as $serialNo => $cert) {
349
        file_put_contents($path.'/'.$serialNo.'.crt', $cert);
350
    }
351
}
352
353
/**
354
 * @throws InvalidConfigException
355
 * @throws DecryptException
356
 */
357
function decrypt_wechat_resource(array $resource, array $config): array
358
{
359
    $ciphertext = base64_decode($resource['ciphertext'] ?? '');
360
    $secret = $config['mch_secret_key'] ?? null;
361
362
    if (strlen($ciphertext) <= Wechat::AUTH_TAG_LENGTH_BYTE) {
363
        throw new DecryptException(Exception::DECRYPT_WECHAT_CIPHERTEXT_PARAMS_INVALID, '加解密异常: ciphertext 位数过短');
364
    }
365
366
    if (is_null($secret) || Wechat::MCH_SECRET_KEY_LENGTH_BYTE != strlen($secret)) {
367
        throw new InvalidConfigException(Exception::CONFIG_WECHAT_INVALID, '配置异常: 缺少微信配置 -- [mch_secret_key]');
368
    }
369
370
    $resource['ciphertext'] = match ($resource['algorithm'] ?? '') {
371
        'AEAD_AES_256_GCM' => decrypt_wechat_resource_aes_256_gcm($ciphertext, $secret, $resource['nonce'] ?? '', $resource['associated_data'] ?? ''),
372
        default => throw new DecryptException(Exception::DECRYPT_WECHAT_DECRYPTED_METHOD_INVALID, '加解密异常: algorithm 不支持'),
373
    };
374
375
    return $resource;
376
}
377
378
/**
379
 * @throws DecryptException
380
 */
381
function decrypt_wechat_resource_aes_256_gcm(string $ciphertext, string $secret, string $nonce, string $associatedData): array|string
382
{
383
    $decrypted = openssl_decrypt(
384
        substr($ciphertext, 0, -Wechat::AUTH_TAG_LENGTH_BYTE),
385
        'aes-256-gcm',
386
        $secret,
387
        OPENSSL_RAW_DATA,
388
        $nonce,
389
        substr($ciphertext, -Wechat::AUTH_TAG_LENGTH_BYTE),
390
        $associatedData
391
    );
392
393
    if (false === $decrypted) {
394
        throw new DecryptException(Exception::DECRYPT_WECHAT_ENCRYPTED_DATA_INVALID, '加解密异常: 解密失败,请检查微信 mch_secret_key 是否正确');
395
    }
396
397
    if ('certificate' !== $associatedData) {
398
        $decrypted = json_decode($decrypted, true);
399
400
        if (JSON_ERROR_NONE !== json_last_error()) {
401
            throw new DecryptException(Exception::DECRYPT_WECHAT_ENCRYPTED_DATA_INVALID, '加解密异常: 待解密数据非正常数据');
402
        }
403
    }
404
405
    return $decrypted;
406
}
407
408
/**
409
 * @throws ContainerException
410
 * @throws DecryptException
411
 * @throws InvalidConfigException
412
 * @throws InvalidParamsException
413
 * @throws ServiceNotFoundException
414
 */
415
function get_wechat_serial_no(array $params): string
416
{
417
    if (!empty($params['_serial_no'])) {
418
        return $params['_serial_no'];
419
    }
420
421
    $config = get_wechat_config($params);
422
423
    if (empty($config['wechat_public_cert_path'])) {
424
        reload_wechat_public_certs($params);
425
426
        $config = get_wechat_config($params);
427
    }
428
429
    mt_srand();
430
431
    return strval(array_rand($config['wechat_public_cert_path']));
432
}
433
434
/**
435
 * @throws InvalidParamsException
436
 */
437
function get_wechat_public_key(array $config, string $serialNo): string
438
{
439
    $publicKey = $config['wechat_public_cert_path'][$serialNo] ?? null;
440
441
    if (empty($publicKey)) {
442
        throw new InvalidParamsException(Exception::PARAMS_WECHAT_SERIAL_NOT_FOUND, '参数异常: 微信公钥序列号为找到 -'.$serialNo);
443
    }
444
445
    return $publicKey;
446
}
447
448
/**
449
 * @throws InvalidConfigException
450
 */
451
function get_wechat_miniprogram_pay_sign(array $config, string $url, string $payload): string
452
{
453
    if (empty($config['mini_app_key_virtual_pay'])) {
454
        throw new InvalidConfigException(Exception::CONFIG_WECHAT_INVALID, '配置异常: 缺少微信配置 -- [mini_app_key_virtual_pay]');
455
    }
456
457
    return hash_hmac('sha256', $url.'&'.$payload, $config['mini_app_key_virtual_pay']);
458
}
459
460
function get_wechat_miniprogram_user_sign(string $sessionKey, string $payload): string
461
{
462
    return hash_hmac('sha256', $payload, $sessionKey);
463
}
464
465
/**
466
 * @throws ContainerException
467
 * @throws ServiceNotFoundException
468
 */
469
function get_unipay_config(array $params = []): array
470
{
471
    $unipay = Pay::get(ConfigInterface::class)->get('unipay');
472
473
    return $unipay[get_tenant($params)] ?? [];
474
}
475
476
/**
477
 * @throws InvalidConfigException
478
 * @throws InvalidSignException
479
 */
480
function verify_unipay_sign(array $config, string $contents, string $sign, ?string $signPublicKeyCert = null): void
481
{
482
    if (empty($sign)) {
483
        throw new InvalidSignException(Exception::SIGN_EMPTY, '签名异常: 银联签名为空', func_get_args());
484
    }
485
486
    if (empty($signPublicKeyCert) && empty($public = $config['unipay_public_cert_path'] ?? null)) {
487
        throw new InvalidConfigException(Exception::CONFIG_UNIPAY_INVALID, '配置异常: 缺少银联配置 -- [unipay_public_cert_path]');
488
    }
489
490
    $result = 1 === openssl_verify(
491
        hash('sha256', $contents),
492
        base64_decode($sign),
493
        get_public_cert($signPublicKeyCert ?? $public ?? ''),
494
        'sha256'
495
    );
496
497
    if (!$result) {
498
        throw new InvalidSignException(Exception::SIGN_ERROR, '签名异常: 验证银联签名失败', func_get_args());
499
    }
500
}
501
502
/**
503
 * @throws InvalidParamsException
504
 */
505
function get_unipay_url(array $config, ?Collection $payload): string
506
{
507
    $url = get_radar_url($config, $payload);
508
509
    if (empty($url)) {
510
        throw new InvalidParamsException(Exception::PARAMS_UNIPAY_URL_MISSING, '参数异常: 银联 `_url` 参数缺失:你可能用错插件顺序,应该先使用 `业务插件`');
511
    }
512
513
    if (str_starts_with($url, 'http')) {
514
        return $url;
515
    }
516
517
    return Unipay::URL[$config['mode'] ?? Pay::MODE_NORMAL].$url;
518
}
519
520
/**
521
 * @throws InvalidParamsException
522
 */
523
function get_unipay_body(?Collection $payload): string
524
{
525
    $body = get_radar_body($payload);
526
527
    if (is_null($body)) {
528
        throw new InvalidParamsException(Exception::PARAMS_UNIPAY_BODY_MISSING, '参数异常: 银联 `_body` 参数缺失:你可能用错插件顺序,应该先使用 `AddPayloadBodyPlugin`');
529
    }
530
531
    return $body;
532
}
533
534
/**
535
 * @throws InvalidConfigException
536
 */
537
function get_unipay_sign_qra(array $config, array $payload): string
538
{
539
    $key = $config['mch_secret_key'] ?? null;
540
541
    if (empty($key)) {
542
        throw new InvalidConfigException(Exception::CONFIG_UNIPAY_INVALID, '配置异常: 缺少银联配置 -- [mch_secret_key]');
543
    }
544
545
    ksort($payload);
546
547
    $buff = '';
548
549
    foreach ($payload as $k => $v) {
550
        $buff .= ('sign' != $k && '' != $v && !is_array($v)) ? $k.'='.$v.'&' : '';
551
    }
552
553
    return strtoupper(md5($buff.'key='.$key));
554
}
555
556
/**
557
 * @throws InvalidConfigException
558
 * @throws InvalidSignException
559
 */
560
function verify_unipay_sign_qra(array $config, array $destination): void
561
{
562
    $sign = $destination['sign'] ?? null;
563
564
    if (empty($sign)) {
565
        throw new InvalidSignException(Exception::SIGN_EMPTY, '签名异常: 银联签名为空', $destination);
566
    }
567
568
    $key = $config['mch_secret_key'] ?? null;
569
570
    if (empty($key)) {
571
        throw new InvalidConfigException(Exception::CONFIG_UNIPAY_INVALID, '配置异常: 缺少银联配置 -- [mch_secret_key]');
572
    }
573
574
    if (get_unipay_sign_qra($config, $destination) !== $sign) {
575
        throw new InvalidSignException(Exception::SIGN_ERROR, '签名异常: 验证银联签名失败', $destination);
576
    }
577
}
578
579
/**
580
 * @throws ContainerException
581
 * @throws ServiceNotFoundException
582
 */
583
function get_douyin_config(array $params = []): array
584
{
585
    $wechat = Pay::get(ConfigInterface::class)->get('douyin');
586
587
    return $wechat[get_tenant($params)] ?? [];
588
}
589