get_public_cert()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

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