支付宝支付使用证书方式进行支付的类
# 安装支付宝官方sdk
composer require alipaysdk/easysdk:^2.0
1
# 支付调用类
<?php
/**
* Created by PhpStorm
* @Author: wangwin
* @Date: 2024/10/17
* @Time: 11:35
* @Version: 1.0
*/
namespace app\cyyutils\ali;
use Alipay\EasySDK\Kernel\EasySDKKernel;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;
use app\cyyutils\ali\transfer\Client as TransferClient;
use Exception;
use Yii;
class AlipayService
{
private $config;
/**
* @var EasySDKKernel
*/
protected $kernel;
public function __construct(array $options = [])
{
$this->config = new Config();
$this->setOptions($options);
Factory::setOptions($this->config);
}
/**
* @return EasySDKKernel
*/
public function getKernel()
{
if (!$this->kernel) {
$this->kernel = new EasySDKKernel($this->config);
}
return $this->kernel;
}
private function setOptions(array $options)
{
$defaultOptions = $this->getDefaultOptions();
$this->config->protocol = $options['protocol'] ?? $defaultOptions['protocol'];
$this->config->gatewayHost = $options['gatewayHost'] ?? $defaultOptions['gatewayHost'];
$this->config->signType = $options['signType'] ?? $defaultOptions['signType'];
$this->config->appId = $options['appId'] ?? $defaultOptions['appId'];
$this->config->merchantPrivateKey = $options['merchantPrivateKey'] ?? $defaultOptions['merchantPrivateKey'];
$this->config->alipayCertPath = $options['alipayCertPath'] ?? $defaultOptions['alipayCertPath'];
$this->config->alipayRootCertPath = $options['alipayRootCertPath'] ?? $defaultOptions['alipayRootCertPath'];
$this->config->merchantCertPath = $options['merchantCertPath'] ?? $defaultOptions['merchantCertPath'];
$this->config->notifyUrl = $options['notifyUrl'] ?? $defaultOptions['notifyUrl'];
}
private function getDefaultOptions()
{
$certPath = Yii::getAlias('@app').'/data/cert';
return [
'protocol' => 'https',
'gatewayHost' => 'openapi.alipay.com',
'signType' => 'RSA2',
'appId' => '666666666',
'merchantPrivateKey' => file_get_contents($certPath.'/private.key'),
'alipayCertPath' => $certPath.'/alipayCertPublicKey_RSA2.crt',
'alipayRootCertPath' => $certPath.'/alipayRootCert.crt',
'merchantCertPath' => $certPath.'/appCertPublicKey_2021003175608318.crt',
'notifyUrl' => '',
];
}
/**
* 转账
* @return TransferClient
*/
public function transfer(): TransferClient
{
return new TransferClient($this->getKernel());
}
/**
* 支付
* @param $subject
* @param $outTradeNo
* @param $totalAmount
* @param $buyerId
* @return array
*/
public function createPayment($subject, $outTradeNo, $totalAmount, $buyerId)
{
try {
// 发起API调用
$result = Factory::payment()->common()->create($subject, $outTradeNo, $totalAmount, $buyerId);
$responseChecker = new ResponseChecker();
// 处理响应
if ($responseChecker->success($result)) {
return [
'success' => true,
'message' => "调用成功",
'data' => $result
];
} else {
return [
'success' => false,
'message' => "调用失败,原因:".$result->msg.",".$result->subMsg
];
}
} catch (Exception $e) {
return [
'success' => false,
'message' => "调用失败,".$e->getMessage()
];
}
}
}
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
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
# 转账transfer类client
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace app\cyyutils\ali\transfer;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use AlibabaCloud\Tea\Request;
use AlibabaCloud\Tea\Tea;
use Alipay\EasySDK\Kernel\EasySDKKernel;
use Alipay\EasySDK\Payment\Common\Models\AlipayTradeCancelResponse;
use Alipay\EasySDK\Payment\Wap\Models\AlipayTradeWapPayResponse;
use app\cyyutils\ali\transfer\models\AlipayTransferResponse;
use Exception;
class Client
{
/**
* @var EasySDKKernel
*/
protected $_kernel;
public function __construct($kernel)
{
$this->_kernel = $kernel;
}
/**
* 单次转账
* @param $account
* @param $accountName
* @param $outBizNo
* @param $transAmount
* @param $payeeInfo
* @param $orderTitle
* @param $remark
* @return AlipayTransferResponse
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function payByAccount($account, $accountName, $outBizNo, $transAmount, $payeeInfo = [], $orderTitle = '', $remark = '')
{
$_runtime = [
"ignoreSSL" => $this->_kernel->getConfig("ignoreSSL"),
"httpProxy" => $this->_kernel->getConfig("httpProxy"),
"connectTimeout" => 15000,
"readTimeout" => 15000,
"retry" => [
"maxAttempts" => 0
]
];
$_lastRequest = null;
$_lastException = null;
$_now = time();
$_retryTimes = 0;
while (Tea::allowRetry(@$_runtime["retry"], $_retryTimes, $_now)) {
if ($_retryTimes > 0) {
$_backoffTime = Tea::getBackoffTime(@$_runtime["backoff"], $_retryTimes);
if ($_backoffTime > 0) {
Tea::sleep($_backoffTime);
}
}
$_retryTimes = $_retryTimes + 1;
try {
$_request = new Request();
$systemParams = [
"method" => "alipay.fund.trans.uni.transfer",
"app_id" => $this->_kernel->getConfig("appId"),
"timestamp" => $this->_kernel->getTimestamp(),
"format" => "json",
"version" => "1.0",
"alipay_sdk" => $this->_kernel->getSdkVersion(),
"charset" => "UTF-8",
"sign_type" => $this->_kernel->getConfig("signType"),
"app_cert_sn" => $this->_kernel->getMerchantCertSN(),
"alipay_root_cert_sn" => $this->_kernel->getAlipayRootCertSN()
];
$payeeInfo = [
"identity" => $account, // 必填:收款方标识(支付宝用户 UID)
"name" => $accountName,
"identity_type" => "ALIPAY_LOGON_ID", // 必填:标识类型(支持 ALIPAY_USER_ID, ALIPAY_LOGON_ID, ALIPAY_OPEN_ID)
];
$bizParams = [
"out_biz_no" => $outBizNo,
"trans_amount" => $transAmount,
"biz_scene" => "DIRECT_TRANSFER",
"product_code" => "TRANS_ACCOUNT_NO_PWD",
"order_title" => $orderTitle,
"payee_info" => $payeeInfo,
"remark" => $remark,
];
$textParams = [];
$_request->protocol = $this->_kernel->getConfig("protocol");
$_request->method = "POST";
$_request->pathname = "/gateway.do";
$_request->headers = [
"host" => $this->_kernel->getConfig("gatewayHost"),
"content-type" => "application/x-www-form-urlencoded;charset=utf-8"
];
$_request->query = $this->_kernel->sortMap(Tea::merge([
"sign" => $this->_kernel->sign($systemParams, $bizParams, $textParams, $this->_kernel->getConfig("merchantPrivateKey"))
], $systemParams, $textParams));
$_request->body = $this->_kernel->toUrlEncodedRequestBody($bizParams);
$_lastRequest = $_request;
$_response = Tea::send($_request, $_runtime);
$respMap = $this->_kernel->readAsJson($_response, "alipay.fund.trans.uni.transfer");
if ($this->_kernel->isCertMode()) {
if ($this->_kernel->verify($respMap, $this->_kernel->extractAlipayPublicKey($this->_kernel->getAlipayCertSN($respMap)))) {
return json_decode($respMap['http_body'], true)['alipay_fund_trans_uni_transfer_response'] ?? [];
// return AlipayTransferResponse::fromMap($this->_kernel->toRespModel($respMap));
}
} else {
if ($this->_kernel->verify($respMap, $this->_kernel->getConfig("alipayPublicKey"))) {
return json_decode($respMap['http_body'], true)['alipay_fund_trans_uni_transfer_response'] ?? [];
// return AlipayTransferResponse::fromMap($this->_kernel->toRespModel($respMap));
}
}
throw new TeaError([
"message" => "验签失败,请检查支付宝公钥设置是否正确。"
]);
} catch (Exception $e) {
if (! ($e instanceof TeaError)) {
$e = new TeaError([], $e->getMessage(), $e->getCode(), $e);
}
if (Tea::isRetryable($e)) {
$_lastException = $e;
continue;
}
throw $e;
}
}
throw new TeaUnableRetryError($_lastRequest, $_lastException);
}
/**
* 转账查询
* @param $outBizNo
* @return AlipayTransferResponse |array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function payQueryByOutNo($outBizNo)
{
$_runtime = [
"ignoreSSL" => $this->_kernel->getConfig("ignoreSSL"),
"httpProxy" => $this->_kernel->getConfig("httpProxy"),
"connectTimeout" => 15000,
"readTimeout" => 15000,
"retry" => [
"maxAttempts" => 0
]
];
$_lastRequest = null;
$_lastException = null;
$_now = time();
$_retryTimes = 0;
while (Tea::allowRetry(@$_runtime["retry"], $_retryTimes, $_now)) {
if ($_retryTimes > 0) {
$_backoffTime = Tea::getBackoffTime(@$_runtime["backoff"], $_retryTimes);
if ($_backoffTime > 0) {
Tea::sleep($_backoffTime);
}
}
$_retryTimes = $_retryTimes + 1;
try {
$_request = new Request();
$systemParams = [
"method" => "alipay.fund.trans.common.query",
"app_id" => $this->_kernel->getConfig("appId"),
"timestamp" => $this->_kernel->getTimestamp(),
"format" => "json",
"version" => "1.0",
"alipay_sdk" => $this->_kernel->getSdkVersion(),
"charset" => "UTF-8",
"sign_type" => $this->_kernel->getConfig("signType"),
"app_cert_sn" => $this->_kernel->getMerchantCertSN(),
"alipay_root_cert_sn" => $this->_kernel->getAlipayRootCertSN()
];
$bizParams = [
"out_biz_no" => $outBizNo,
"biz_scene" => "DIRECT_TRANSFER",
"product_code" => "TRANS_ACCOUNT_NO_PWD",
];
$textParams = [];
$_request->protocol = $this->_kernel->getConfig("protocol");
$_request->method = "POST";
$_request->pathname = "/gateway.do";
$_request->headers = [
"host" => $this->_kernel->getConfig("gatewayHost"),
"content-type" => "application/x-www-form-urlencoded;charset=utf-8"
];
$_request->query = $this->_kernel->sortMap(Tea::merge([
"sign" => $this->_kernel->sign($systemParams, $bizParams, $textParams, $this->_kernel->getConfig("merchantPrivateKey"))
], $systemParams, $textParams));
$_request->body = $this->_kernel->toUrlEncodedRequestBody($bizParams);
$_lastRequest = $_request;
$_response = Tea::send($_request, $_runtime);
$respMap = $this->_kernel->readAsJson($_response, "alipay.fund.trans.common.query");
if ($this->_kernel->isCertMode()) {
if ($this->_kernel->verify($respMap, $this->_kernel->extractAlipayPublicKey($this->_kernel->getAlipayCertSN($respMap)))) {
return json_decode($respMap['http_body'], true)['alipay_fund_trans_common_query_response'] ?? [];
// return AlipayTransferResponse::fromMap($this->_kernel->toRespModel($respMap));
}
} else {
if ($this->_kernel->verify($respMap, $this->_kernel->getConfig("alipayPublicKey"))) {
return json_decode($respMap['http_body'], true)['alipay_fund_trans_common_query_response'] ?? [];
// return AlipayTransferResponse::fromMap($this->_kernel->toRespModel($respMap));
}
}
throw new TeaError([
"message" => "验签失败,请检查支付宝公钥设置是否正确。"
]);
} catch (Exception $e) {
if (! ($e instanceof TeaError)) {
$e = new TeaError([], $e->getMessage(), $e->getCode(), $e);
}
if (Tea::isRetryable($e)) {
$_lastException = $e;
continue;
}
throw $e;
}
}
throw new TeaUnableRetryError($_lastRequest, $_lastException);
}
/**
* ISV代商户代用,指定appAuthToken
*
* @param $appAuthToken String 代调用token
* @return \Alipay\EasySDK\Payment\Common\Client 本客户端,便于链式调用
*/
public function agent($appAuthToken)
{
$this->_kernel->injectTextParam("app_auth_token", $appAuthToken);
return $this;
}
/**
* 用户授权调用,指定authToken
*
* @param $authToken String 用户授权token
* @return $this
*/
public function auth($authToken)
{
$this->_kernel->injectTextParam("auth_token", $authToken);
return $this;
}
/**
* 设置异步通知回调地址,此处设置将在本调用中覆盖Config中的全局配置
*
* @param $url String 异步通知回调地址,例如:https://www.test.com/callback
* @return $this
*/
public function asyncNotify($url)
{
$this->_kernel->injectTextParam("notify_url", $url);
return $this;
}
/**
* 将本次调用强制路由到后端系统的测试地址上,常用于线下环境内外联调,沙箱与线上环境设置无效
*
* @param $testUrl String 后端系统测试地址
* @return $this
*/
public function route($testUrl)
{
$this->_kernel->injectTextParam("ws_service_url", $testUrl);
return $this;
}
/**
* 设置API入参中没有的其他可选业务请求参数(biz_content下的字段)
*
* @param $key String 业务请求参数名称(biz_content下的字段名,比如timeout_express)
* @param $value object 业务请求参数的值,一个可以序列化成JSON的对象
* 如果该字段是一个字符串类型(String、Price、Date在SDK中都是字符串),请使用String储存
* 如果该字段是一个数值型类型(比如:Number),请使用Long储存
* 如果该字段是一个复杂类型,请使用嵌套的array指定各下级字段的值
* 如果该字段是一个数组,请使用array储存各个值
* @return $this
*/
public function optional($key, $value)
{
$this->_kernel->injectBizParam($key, $value);
return $this;
}
/**
* 批量设置API入参中没有的其他可选业务请求参数(biz_content下的字段)
* optional方法的批量版本
*
* @param $optionalArgs array 可选参数集合,每个参数由key和value组成,key和value的格式请参见optional方法的注释
* @return $this
*/
public function batchOptional($optionalArgs)
{
foreach ( $optionalArgs as $key => $value ) {
$this->_kernel->injectBizParam($key, $value);
}
return $this;
}
}
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
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
# 结果处理类
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace app\cyyutils\ali\transfer\models;
use AlibabaCloud\Tea\Model;
class AlipayTransferResponse extends Model
{
protected $_name = [
'httpBody' => 'http_body',
'code' => 'code',
'msg' => 'msg',
'subCode' => 'sub_code',
'subMsg' => 'sub_msg',
'outBizNo' => 'out_biz_no',
'orderId' => 'order_id',
'payFundOrderId' => 'pay_fund_order_id',
'transDate' => 'trans_date',
'status' => 'status',
];
public function validate()
{
Model::validateRequired('httpBody', $this->httpBody, true);
Model::validateRequired('code', $this->code, true);
Model::validateRequired('msg', $this->msg, true);
Model::validateRequired('subCode', $this->subCode, true);
Model::validateRequired('subMsg', $this->subMsg, true);
Model::validateRequired('outBizNo', $this->outBizNo, true);
Model::validateRequired('orderId', $this->orderId, true);
Model::validateRequired('payFundOrderId', $this->payFundOrderId, true);
Model::validateRequired('transDate', $this->transDate, true);
}
public function toMap()
{
$res = [];
if (null !== $this->httpBody) {
$res['http_body'] = $this->httpBody;
}
if (null !== $this->code) {
$res['code'] = $this->code;
}
if (null !== $this->msg) {
$res['msg'] = $this->msg;
}
if (null !== $this->subCode) {
$res['sub_code'] = $this->subCode;
}
if (null !== $this->subMsg) {
$res['sub_msg'] = $this->subMsg;
}
if (null !== $this->outBizNo) {
$res['out_biz_no'] = $this->outBizNo;
}
if (null !== $this->orderId) {
$res['order_id'] = $this->orderId;
}
if (null !== $this->payFundOrderId) {
$res['pay_fund_order_id'] = $this->payFundOrderId;
}
if (null !== $this->transDate) {
$res['trans_date'] = $this->transDate;
}
if (null !== $this->status) {
$res['status'] = $this->status;
}
return $res;
}
/**
* @param array $map
* @return AlipayTransferResponse
*/
public static function fromMap($map = [])
{
$model = new self();
if (isset($map['http_body'])) {
$model->httpBody = $map['http_body'];
}
if (isset($map['code'])) {
$model->code = $map['code'];
}
if (isset($map['msg'])) {
$model->msg = $map['msg'];
}
if (isset($map['sub_code'])) {
$model->subCode = $map['sub_code'];
}
if (isset($map['sub_msg'])) {
$model->subMsg = $map['sub_msg'];
}
if (isset($map['out_biz_no'])) {
$model->outBizNo = $map['out_biz_no'];
}
if (isset($map['order_id'])) {
$model->orderId = $map['order_id'];
}
if (isset($map['pay_fund_order_id'])) {
$model->payFundOrderId = $map['pay_fund_order_id'];
}
if (isset($map['trans_date'])) {
$model->transDate = $map['trans_date'];
}
if (isset($map['status'])) {
$model->status = $map['status'];
}
return $model;
}
/**
* @var string
*/
public $httpBody;
/**
* @var string
*/
public $code;
/**
* @var string
*/
public $msg;
/**
* @var string
*/
public $subCode;
/**
* @var string
*/
public $subMsg;
/**
* @var string
*/
public $outBizNo;
/**
* @var string
*/
public $orderId;
/**
* @var string
*/
public $payFundOrderId;
/**
* @var string
*/
public $transDate;
/**
* @var string|null
*/
public $status;
}
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
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
在线编辑 (opens new window)
上次更新: 2025/02/25, 18:30:54