Passed
Pull Request — master (#994)
by Songda
02:19
created

get_provider_config()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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