Functions.php
12.7 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
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
<?php
declare(strict_types=1);
namespace Yansongda\Pay;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Yansongda\Pay\Contract\ConfigInterface;
use Yansongda\Pay\Direction\NoHttpRequestDirection;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\Exception;
use Yansongda\Pay\Exception\InvalidConfigException;
use Yansongda\Pay\Exception\InvalidParamsException;
use Yansongda\Pay\Exception\InvalidResponseException;
use Yansongda\Pay\Exception\ServiceNotFoundException;
use Yansongda\Pay\Plugin\ParserPlugin;
use Yansongda\Pay\Plugin\Wechat\PreparePlugin;
use Yansongda\Pay\Plugin\Wechat\RadarSignPlugin;
use Yansongda\Pay\Plugin\Wechat\WechatPublicCertsPlugin;
use Yansongda\Pay\Provider\Wechat;
use Yansongda\Supports\Str;
if (!function_exists('should_do_http_request')) {
function should_do_http_request(string $direction): bool
{
return NoHttpRequestDirection::class !== $direction
&& !in_array(NoHttpRequestDirection::class, class_parents($direction));
}
}
if (!function_exists('get_tenant')) {
function get_tenant(array $params = []): string
{
return strval($params['_config'] ?? 'default');
}
}
if (!function_exists('get_alipay_config')) {
/**
* @throws ContainerException
* @throws ServiceNotFoundException
*/
function get_alipay_config(array $params = []): array
{
$alipay = Pay::get(ConfigInterface::class)->get('alipay');
return $alipay[get_tenant($params)] ?? [];
}
}
if (!function_exists('get_public_cert')) {
function get_public_cert(string $key): string
{
return Str::endsWith($key, ['.cer', '.crt', '.pem']) ? file_get_contents($key) : $key;
}
}
if (!function_exists('get_private_cert')) {
function get_private_cert(string $key): string
{
if (Str::endsWith($key, ['.crt', '.pem'])) {
return file_get_contents($key);
}
return "-----BEGIN RSA PRIVATE KEY-----\n".
wordwrap($key, 64, "\n", true).
"\n-----END RSA PRIVATE KEY-----";
}
}
if (!function_exists('verify_alipay_sign')) {
/**
* @throws ContainerException
* @throws InvalidConfigException
* @throws ServiceNotFoundException
* @throws InvalidResponseException
*/
function verify_alipay_sign(array $params, string $contents, string $sign): void
{
$public = get_alipay_config($params)['alipay_public_cert_path'] ?? null;
if (empty($public)) {
throw new InvalidConfigException(Exception::ALIPAY_CONFIG_ERROR, 'Missing Alipay Config -- [alipay_public_cert_path]');
}
// 优化publickey判断
if (!Str::endsWith($public, ['.cer', '.crt', '.pem']) && stripos($public, '-----BEGIN PUBLIC KEY-----') === false) {
$public = "-----BEGIN PUBLIC KEY-----\n".
wordwrap($public, 64, "\n", true).
"\n-----END PUBLIC KEY-----";
}
$result = 1 === openssl_verify(
$contents,
base64_decode($sign),
get_public_cert($public),
OPENSSL_ALGO_SHA256
);
if (!$result) {
throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, 'Verify Alipay Response Sign Failed', func_get_args());
}
}
}
if (!function_exists('get_wechat_config')) {
/**
* @throws ContainerException
* @throws ServiceNotFoundException
*/
function get_wechat_config(array $params): array
{
$wechat = Pay::get(ConfigInterface::class)->get('wechat');
return $wechat[get_tenant($params)] ?? [];
}
}
if (!function_exists('get_wechat_base_uri')) {
/**
* @throws ContainerException
* @throws ServiceNotFoundException
*/
function get_wechat_base_uri(array $params): string
{
$config = get_wechat_config($params);
return Wechat::URL[$config['mode'] ?? Pay::MODE_NORMAL];
}
}
if (!function_exists('get_wechat_sign')) {
/**
* @throws ContainerException
* @throws ServiceNotFoundException
* @throws InvalidConfigException
*/
function get_wechat_sign(array $params, string $contents): string
{
$privateKey = get_wechat_config($params)['mch_secret_cert'] ?? null;
if (empty($privateKey)) {
throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Missing Wechat Config -- [mch_secret_cert]');
}
$privateKey = get_private_cert($privateKey);
openssl_sign($contents, $sign, $privateKey, 'sha256WithRSAEncryption');
return base64_encode($sign);
}
}
if (!function_exists('get_wechat_sign_v2')) {
/**
* @throws ContainerException
* @throws ServiceNotFoundException
* @throws InvalidConfigException
*/
function get_wechat_sign_v2(array $params, array $payload, bool $upper = true): string
{
$key = get_wechat_config($params)['mch_secret_key_v2'] ?? null;
if (empty($key)) {
throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Missing Wechat Config -- [mch_secret_key_v2]');
}
ksort($payload);
$buff = '';
foreach ($payload as $k => $v) {
$buff .= ('sign' != $k && '' != $v && !is_array($v)) ? $k.'='.$v.'&' : '';
}
$sign = md5($buff.'key='.$key);
return $upper ? strtoupper($sign) : $sign;
}
}
if (!function_exists('verify_wechat_sign')) {
/**
* @param ResponseInterface|ServerRequestInterface $message
*
* @throws ContainerException
* @throws InvalidConfigException
* @throws InvalidResponseException
* @throws ServiceNotFoundException
* @throws InvalidParamsException
*/
function verify_wechat_sign(MessageInterface $message, array $params): void
{
if ($message instanceof ServerRequestInterface && 'localhost' === $message->getUri()->getHost()) {
return;
}
$wechatSerial = $message->getHeaderLine('Wechatpay-Serial');
$timestamp = $message->getHeaderLine('Wechatpay-Timestamp');
$random = $message->getHeaderLine('Wechatpay-Nonce');
$sign = $message->getHeaderLine('Wechatpay-Signature');
$body = (string) $message->getBody();
$content = $timestamp."\n".$random."\n".$body."\n";
$public = get_wechat_config($params)['wechat_public_cert_path'][$wechatSerial] ?? null;
if (empty($sign)) {
throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, '', ['headers' => $message->getHeaders(), 'body' => $body]);
}
$public = get_public_cert(
empty($public) ? reload_wechat_public_certs($params, $wechatSerial) : $public
);
$result = 1 === openssl_verify(
$content,
base64_decode($sign),
$public,
'sha256WithRSAEncryption'
);
if (!$result) {
throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, '', ['headers' => $message->getHeaders(), 'body' => $body]);
}
}
}
if (!function_exists('encrypt_wechat_contents')) {
function encrypt_wechat_contents(string $contents, string $publicKey): ?string
{
if (openssl_public_encrypt($contents, $encrypted, get_public_cert($publicKey), OPENSSL_PKCS1_OAEP_PADDING)) {
return base64_encode($encrypted);
}
return null;
}
}
if (!function_exists('reload_wechat_public_certs')) {
/**
* @throws ContainerException
* @throws InvalidConfigException
* @throws ServiceNotFoundException
* @throws InvalidParamsException
* @throws InvalidResponseException
*/
function reload_wechat_public_certs(array $params, ?string $serialNo = null): string
{
$data = Pay::wechat()->pay(
[PreparePlugin::class, WechatPublicCertsPlugin::class, RadarSignPlugin::class, ParserPlugin::class],
$params
)->get('data', []);
foreach ($data as $item) {
$certs[$item['serial_no']] = decrypt_wechat_resource($item['encrypt_certificate'], $params)['ciphertext'] ?? '';
}
$wechatConfig = get_wechat_config($params);
Pay::get(ConfigInterface::class)->set(
'wechat.'.get_tenant($params).'.wechat_public_cert_path',
((array) ($wechatConfig['wechat_public_cert_path'] ?? [])) + ($certs ?? [])
);
if (!is_null($serialNo) && empty($certs[$serialNo])) {
throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Get Wechat Public Cert Error');
}
return $certs[$serialNo] ?? '';
}
}
if (!function_exists('get_wechat_public_certs')) {
/**
* @throws ContainerException
* @throws InvalidConfigException
* @throws ServiceNotFoundException
* @throws InvalidParamsException
* @throws InvalidResponseException
*/
function get_wechat_public_certs(array $params = [], ?string $path = null): void
{
reload_wechat_public_certs($params);
$config = get_wechat_config($params);
if (empty($path)) {
var_dump($config['wechat_public_cert_path']);
return;
}
foreach ($config['wechat_public_cert_path'] as $serialNo => $cert) {
file_put_contents($path.'/'.$serialNo.'.crt', $cert);
}
}
}
if (!function_exists('decrypt_wechat_resource')) {
/**
* @throws ContainerException
* @throws InvalidConfigException
* @throws InvalidResponseException
* @throws ServiceNotFoundException
*/
function decrypt_wechat_resource(array $resource, array $params): array
{
$ciphertext = base64_decode($resource['ciphertext'] ?? '');
$secret = get_wechat_config($params)['mch_secret_key'] ?? null;
if (strlen($ciphertext) <= Wechat::AUTH_TAG_LENGTH_BYTE) {
throw new InvalidResponseException(Exception::INVALID_CIPHERTEXT_PARAMS);
}
if (is_null($secret) || Wechat::MCH_SECRET_KEY_LENGTH_BYTE != strlen($secret)) {
throw new InvalidConfigException(Exception::WECHAT_CONFIG_ERROR, 'Missing Wechat Config -- [mch_secret_key]');
}
switch ($resource['algorithm'] ?? '') {
case 'AEAD_AES_256_GCM':
$resource['ciphertext'] = decrypt_wechat_resource_aes_256_gcm($ciphertext, $secret, $resource['nonce'] ?? '', $resource['associated_data'] ?? '');
break;
default:
throw new InvalidResponseException(Exception::INVALID_REQUEST_ENCRYPTED_METHOD);
}
return $resource;
}
}
if (!function_exists('decrypt_wechat_resource_aes_256_gcm')) {
/**
* @return array|string
*
* @throws InvalidResponseException
*/
function decrypt_wechat_resource_aes_256_gcm(string $ciphertext, string $secret, string $nonce, string $associatedData)
{
$decrypted = openssl_decrypt(
substr($ciphertext, 0, -Wechat::AUTH_TAG_LENGTH_BYTE),
'aes-256-gcm',
$secret,
OPENSSL_RAW_DATA,
$nonce,
substr($ciphertext, -Wechat::AUTH_TAG_LENGTH_BYTE),
$associatedData
);
if ('certificate' !== $associatedData) {
$decrypted = json_decode(strval($decrypted), true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new InvalidResponseException(Exception::INVALID_REQUEST_ENCRYPTED_DATA);
}
}
return $decrypted;
}
}
if (!function_exists('get_unipay_config')) {
/**
* @throws ContainerException
* @throws ServiceNotFoundException
*/
function get_unipay_config(array $params): array
{
$unipay = Pay::get(ConfigInterface::class)->get('unipay');
return $unipay[get_tenant($params)] ?? [];
}
}
if (!function_exists('verify_unipay_sign')) {
/**
* @throws ContainerException
* @throws InvalidConfigException
* @throws InvalidResponseException
* @throws ServiceNotFoundException
*/
function verify_unipay_sign(array $params, string $contents, string $sign): void
{
if (empty($params['signPubKeyCert'])
&& empty($public = get_unipay_config($params)['unipay_public_cert_path'] ?? null)) {
throw new InvalidConfigException(Exception::UNIPAY_CONFIG_ERROR, 'Missing Unipay Config -- [unipay_public_cert_path]');
}
$result = 1 === openssl_verify(
hash('sha256', $contents),
base64_decode($sign),
get_public_cert($params['signPubKeyCert'] ?? $public ?? ''),
'sha256'
);
if (!$result) {
throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, 'Verify Unipay Response Sign Failed', func_get_args());
}
}
}