Browse Source

参考wasywechat

master
wuliangbo 4 years ago
parent
commit
a59c9b51f3
  1. 3
      composer.json
  2. 57
      src/Kernel/AopClient.php
  3. 3
      src/Kernel/BaseClient.php
  4. 67
      src/Kernel/Helpers.php
  5. 1
      src/Payment/Query/Client.php
  6. 1
      tests/test.php

3
composer.json

@ -13,13 +13,14 @@ @@ -13,13 +13,14 @@
"ext-fileinfo": "*",
"ext-openssl": "*",
"ext-simplexml": "*",
"ext-mcrypt": "*",
"guzzlehttp/guzzle": "^6.2",
"pimple/pimple": "^3.0",
"symfony/cache": "^3.3 || ^4.0",
"symfony/http-foundation": "^2.7 || ^3.0 || ^4.0",
"symfony/psr-http-message-bridge": "^0.3 || ^1.0",
"symfony/event-dispatcher": "^5.0",
"monolog/monolog": "^1.22 || ^2.0"
"monolog/monolog": "^1.22 || ^2.0"cd
},
"autoload": {
"psr-4": {

57
src/Kernel/AopClient.php

@ -8,7 +8,8 @@ use EasyAlipay\Kernel\Exceptions\InvalidConfigException; @@ -8,7 +8,8 @@ use EasyAlipay\Kernel\Exceptions\InvalidConfigException;
use EasyAlipay\Kernel\Exceptions\InvalidSignException;
use EasyAlipay\Kernel\Support\Collection;
use EasyAlipay\Kernel\Traits\SingData;
use Exception;
use function EasyAlipay\Kernel\encrypt;
use function EasyAlipay\Kernel\decrypt;
class AopClient extends BaseClient
{
@ -117,18 +118,7 @@ class AopClient extends BaseClient @@ -117,18 +118,7 @@ class AopClient extends BaseClient
$apiParams = $request->getApiParas();
if (method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
$sysParams["encrypt_type"] = $this->encryptType;
if ($this->checkEmpty($apiParams['biz_content'])) {
throw new InvalidArgumentException(" api request Fail! The reason : encrypt request is not supperted!");
}
if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
throw new InvalidArgumentException(" encryptType and encryptKey must not null! ");
}
if ("AES" != $this->encryptType) {
throw new InvalidArgumentException("加密类型只支持AES");
}
// 执行加密
$enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
$apiParams['biz_content'] = $enCryptContent;
$apiParams['biz_content'] = $this->encryptCode($apiParams['biz_content']);
}
//签名
$sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
@ -136,16 +126,47 @@ class AopClient extends BaseClient @@ -136,16 +126,47 @@ class AopClient extends BaseClient
$result = $this->httpPost($requestUrl, $apiParams);
$apiName = $request->getApiMethodName();
$method = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
if (!isset($result[$this->SIGN_NODE_NAME]) || $result[$method]['code'] != '10000') {
$content = $result[$method];
if (method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
$enCryptContent = $this->encryptCode($apiParams['biz_content'],'decrypt');
$content = json_decode($enCryptContent, 1);
}
if (!isset($result[$this->SIGN_NODE_NAME]) || $content['code'] != '10000') {
throw new BadRequestException(
'Get Alipay API Error:' . $result[$method]['msg'] .
(isset($result[$method]['sub_code']) ? (' - ' . $result[$method]['sub_code']) : '')
'Get Alipay API Error:' . $content['msg'] .
(isset($content['sub_code']) ? (' - ' . $content['sub_code']) : '')
);
}
if (!$this->verify($result[$method], $result[$this->SIGN_NODE_NAME], $this->alipayrsaPublicKey, $this->signType)) {
if (!$this->verify($content, $result[$this->SIGN_NODE_NAME], $this->alipayrsaPublicKey, $this->signType)) {
throw new InvalidSignException('签名失败');
}
return new Collection($result[$method]);
return new Collection($content);
}
/**
* 加密|解密
* @param $content
* @param string $operation
* @return false|string
* @throws InvalidArgumentException
*/
public function encryptCode($content, string $operation = 'encrypt')
{
if ($this->checkEmpty($content)) {
throw new InvalidArgumentException("content Fail!");
}
if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
throw new InvalidArgumentException(" encryptType and encryptKey must not null! ");
}
if ("AES" != $this->encryptType) {
throw new InvalidArgumentException("加密类型只支持AES");
}
if ($operation == 'encrypt') {
$enCryptContent = encrypt($content, $this->encryptKey);
} else {
$enCryptContent = decrypt($content, $this->encryptKey);
}
return $enCryptContent;
}
/**

3
src/Kernel/BaseClient.php

@ -166,7 +166,7 @@ class BaseClient @@ -166,7 +166,7 @@ class BaseClient
protected function registerHttpMiddlewares()
{
// retry
$this->pushMiddleware($this->retryMiddleware(), 'retry');
// $this->pushMiddleware($this->retryMiddleware(), 'retry');
// log
$this->pushMiddleware($this->logMiddleware(), 'log');
}
@ -199,7 +199,6 @@ class BaseClient @@ -199,7 +199,6 @@ class BaseClient
if ($retries < $this->app->config->get('http.max_retries', 1) && $response && $body = $response->getBody()) {
// Retry on server errors
$response = json_decode($body, true);
if (!empty($response['errcode']) && in_array(abs($response['errcode']), [40001, 40014, 42001], true)) {
$this->accessToken->refresh();
$this->app['logger']->debug('Retrying with refreshed access token.');

67
src/Kernel/Helpers.php

@ -1,82 +1,33 @@ @@ -1,82 +1,33 @@
<?php
/**
* Created by PhpStorm.
* User: wuliangbo
* Date: 2020/1/6
* Time: 15:25
*/
namespace EasyAlipay\Kernel;
/**
* 加密方法
* @param string $str
* @param $str
* @param $screct_key
* @return string
*/
function encrypt($str, $screct_key)
{
//AES, 128 模式加密数据 CBC
$screct_key = base64_decode($screct_key);
$str = trim($str);
$str = addPKCS7Padding($str);
//设置全0的IV
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv_size = openssl_cipher_iv_length('AES-128-CBC');
$iv = str_repeat("\0", $iv_size);
$encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC, $iv);
$encrypt_str = openssl_encrypt($str,"AES-128-CBC",$screct_key,OPENSSL_RAW_DATA,$iv);
return base64_encode($encrypt_str);
}
/**
* 解密方法
* @param string $str
* @return string
* @param $str
* @param $screct_key
* @return false|string
*/
function decrypt($str, $screct_key)
{
//AES, 128 模式加密数据 CBC
$str = base64_decode($str);
$screct_key = base64_decode($screct_key);
//设置全0的IV
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv_size = openssl_cipher_iv_length('AES-128-CBC');
$iv = str_repeat("\0", $iv_size);
$decrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC, $iv);
$decrypt_str = stripPKSC7Padding($decrypt_str);
$decrypt_str = openssl_decrypt($str,"AES-128-CBC",$screct_key,OPENSSL_RAW_DATA,$iv);
return $decrypt_str;
}
/**
* 填充算法
* @param string $source
* @return string
*/
function addPKCS7Padding($source)
{
$source = trim($source);
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($source) % $block);
if ($pad <= $block) {
$char = chr($pad);
$source .= str_repeat($char, $pad);
}
return $source;
}
/**
* 移去填充算法
* @param string $source
* @return string
*/
function stripPKSC7Padding($source)
{
$char = substr($source, -1);
$num = ord($char);
if ($num == 62) return $source;
$source = substr($source, 0, -$num);
return $source;
}

1
src/Payment/Query/Client.php

@ -23,6 +23,7 @@ class Client extends AopClient @@ -23,6 +23,7 @@ class Client extends AopClient
$queryContentBuilder = new AlipayTradeQueryContentBuilder();
$queryContentBuilder->setOutTradeNo($out_trade_no);
$request = new AopRequest ();
$request->setNeedEncrypt(1);
$request->setBizContent($queryContentBuilder->getBizContent());
$request->setApiMethodName("alipay.trade.query");
return($this->execute($request, NULL, NULL)) ;

1
tests/test.php

@ -6,7 +6,6 @@ $options = [ @@ -6,7 +6,6 @@ $options = [
'app_id' => '2018070360570197',
'gateway_url' => "https://openapi.alipaydev.com/gateway.do",//示例中使用的是沙箱环境网关,线上gateway_url:https://openapi.alipay.com/gateway.do
'sign_type' => "RSA2",
'charset' => "UTF-8",
'encrypt_key' =>'oZXL/lMFlvG818o1jbgM2w==',
'response_type' => 'collection',
'alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsDos+q5ZZa2JWtNLNluV8R6WqJSPUcJ39HpflCb8AEpSLTcjxsWG0RG3nvv7xBAHEOSRET8dTKPoWZXy1TAstv7WY4epiWZwogRzpNEPRbKyEBmbzkiOENW/27IdD6GFQ6e+MPE/BOPqd+hjR5SFghrQNpwZECWuCDFpsJq9G7EtTBUB1av52o/wYqWU1eCeUq+3MrtAD7p0Sh2V/B9jdmkpZhwGI/yHL23MHJI5J2aCNCfEQF520IHwHELrIq7xRv2hVE53APB/dueTTsIKNIWnbA8QbK3MUOgykG80UVxtZMl14Y3eB7RyzY70I5NimszSTSG6OQ2P78PMZjd77wIDAQAB',

Loading…
Cancel
Save