better-staridc-MNBT
1<?php
2/**
3 * 支付宝官方 API SDK(单文件版)
4 *
5 * 基于 dedemao/alipay 的实现整合:
6 * - alipay.trade.page.pay(电脑网站支付,PC)
7 * - alipay.trade.precreate(当面付,扫码)
8 * - 异步通知验签
9 *
10 * 仅依赖 PHP openssl + curl 扩展,无 composer 依赖。
11 * 仅本插件内部使用,不污染全局命名空间。
12 *
13 * 来源:https://github.com/dedemao/alipay
14 * License: MIT
15 */
16
17if (!defined('IN_CRONLITE')) {
18 exit;
19}
20
21class Alipay_Official_Service
22{
23 protected $appId;
24 protected $rsaPrivateKey; // 应用私钥
25 protected $alipayPublicKey; // 支付宝公钥
26 protected $charset = 'utf-8';
27 protected $gateway = 'https://openapi.alipay.com/gateway.do';
28
29 public function __construct(array $config)
30 {
31 $this->appId = isset($config['app_id']) ? trim((string)$config['app_id']) : '';
32 $this->rsaPrivateKey = isset($config['private_key']) ? trim((string)$config['private_key']) : '';
33 $this->alipayPublicKey = isset($config['public_key']) ? trim((string)$config['public_key']) : '';
34 if (!empty($config['gateway'])) {
35 $this->gateway = rtrim((string)$config['gateway'], '/');
36 }
37 }
38
39 /**
40 * 电脑网站支付:返回自动提交的 HTML 表单。
41 *
42 * @param array $params [out_trade_no, total_amount, subject, return_url, notify_url]
43 * @return string HTML
44 */
45 public function buildPagePay(array $params)
46 {
47 $requestConfigs = [
48 'out_trade_no' => $params['out_trade_no'],
49 'product_code' => 'FAST_INSTANT_TRADE_PAY',
50 'total_amount' => $params['total_amount'],
51 'subject' => $params['subject'],
52 ];
53 $commonConfigs = [
54 'app_id' => $this->appId,
55 'method' => 'alipay.trade.page.pay',
56 'format' => 'JSON',
57 'return_url' => $params['return_url'],
58 'charset' => $this->charset,
59 'sign_type' => 'RSA2',
60 'timestamp' => date('Y-m-d H:i:s'),
61 'version' => '1.0',
62 'notify_url' => $params['notify_url'],
63 'biz_content' => json_encode($requestConfigs, JSON_UNESCAPED_UNICODE),
64 ];
65 $commonConfigs['sign'] = $this->generateSign($commonConfigs);
66 return $this->buildRequestForm($commonConfigs);
67 }
68
69 /**
70 * 当面付(扫码):调用 alipay.trade.precreate,返回二维码链接。
71 *
72 * @param array $params [out_trade_no, total_amount, subject, notify_url]
73 * @return array ['ok'=>bool, 'qr_code'=>string, 'raw'=>array]
74 */
75 public function buildPrecreate(array $params)
76 {
77 $requestConfigs = [
78 'out_trade_no' => $params['out_trade_no'],
79 'total_amount' => $params['total_amount'],
80 'subject' => $params['subject'],
81 'timeout_express' => '2h',
82 ];
83 $commonConfigs = [
84 'app_id' => $this->appId,
85 'method' => 'alipay.trade.precreate',
86 'format' => 'JSON',
87 'charset' => $this->charset,
88 'sign_type' => 'RSA2',
89 'timestamp' => date('Y-m-d H:i:s'),
90 'version' => '1.0',
91 'notify_url' => $params['notify_url'],
92 'biz_content' => json_encode($requestConfigs, JSON_UNESCAPED_UNICODE),
93 ];
94 $commonConfigs['sign'] = $this->generateSign($commonConfigs);
95 $resp = $this->curlPost($this->gateway . '?charset=' . $this->charset, $commonConfigs);
96 $data = json_decode($resp, true);
97 if (!is_array($data)) {
98 return ['ok' => false, 'qr_code' => '', 'raw' => ['error' => '响应解析失败', 'raw' => $resp]];
99 }
100 // 同步签名校验(开放平台返回结构:alipay_trade_precreate_response + sign)
101 $innerKey = 'alipay_trade_precreate_response';
102 $inner = isset($data[$innerKey]) ? $data[$innerKey] : null;
103 if (!is_array($inner)) {
104 return ['ok' => false, 'qr_code' => '', 'raw' => $data];
105 }
106 if (isset($inner['code']) && (string)$inner['code'] === '10000' && !empty($inner['qr_code'])) {
107 return ['ok' => true, 'qr_code' => $inner['qr_code'], 'raw' => $data];
108 }
109 return ['ok' => false, 'qr_code' => '', 'raw' => $data];
110 }
111
112 /**
113 * 验证异步通知签名。
114 *
115 * @param array $params 通常是 $_POST
116 * @return bool
117 */
118 public function verifyNotify(array $params)
119 {
120 if (empty($params['sign']) || empty($params['sign_type'])) {
121 return false;
122 }
123 $sign = $params['sign'];
124 $signType = $params['sign_type'];
125 unset($params['sign'], $params['sign_type']);
126 return $this->verify($this->getSignContent($params), $sign, $signType);
127 }
128
129 // ============================================================
130 // 内部方法
131 // ============================================================
132
133 protected function buildRequestForm(array $params)
134 {
135 $html = "<form id='alipaysubmit' name='alipaysubmit' action='" . htmlspecialchars($this->gateway . '?charset=' . $this->charset, ENT_QUOTES, 'UTF-8') . "' method='POST'>";
136 foreach ($params as $key => $val) {
137 if ($this->checkEmpty($val)) continue;
138 $html .= "<input type='hidden' name='" . htmlspecialchars($key, ENT_QUOTES, 'UTF-8') . "' value='" . htmlspecialchars($val, ENT_QUOTES, 'UTF-8') . "'/>";
139 }
140 $html .= "<input type='submit' value='正在跳转' style='display:none'></form>";
141 $html .= "<script>document.forms['alipaysubmit'].submit();</script>";
142 return $html;
143 }
144
145 public function generateSign($params)
146 {
147 return $this->sign($this->getSignContent($params));
148 }
149
150 protected function sign($data, $signType = 'RSA2')
151 {
152 $priKey = $this->rsaPrivateKey;
153 $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
154 wordwrap($priKey, 64, "\n", true) .
155 "\n-----END RSA PRIVATE KEY-----";
156 if (!$res) {
157 error_log('[MNBT alipay_official] 私钥格式错误');
158 return '';
159 }
160 if ($signType === 'RSA2') {
161 openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
162 } else {
163 openssl_sign($data, $sign, $res);
164 }
165 return base64_encode($sign);
166 }
167
168 protected function verify($data, $sign, $signType = 'RSA2')
169 {
170 $pubKey = $this->alipayPublicKey;
171 if ($pubKey === '') return false;
172 $res = "-----BEGIN PUBLIC KEY-----\n" .
173 wordwrap($pubKey, 64, "\n", true) .
174 "\n-----END PUBLIC KEY-----";
175 if (!$res) return false;
176 if ($signType === 'RSA2') {
177 return (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
178 }
179 return (bool)openssl_verify($data, base64_decode($sign), $res);
180 }
181
182 protected function checkEmpty($value)
183 {
184 if (!isset($value)) return true;
185 if ($value === null) return true;
186 if (trim($value) === '') return true;
187 return false;
188 }
189
190 public function getSignContent($params)
191 {
192 ksort($params);
193 $stringToBeSigned = '';
194 $i = 0;
195 foreach ($params as $k => $v) {
196 if ($this->checkEmpty($v) || substr($v, 0, 1) === '@') continue;
197 $v = $this->characet($v, $this->charset);
198 if ($i == 0) {
199 $stringToBeSigned .= $k . '=' . $v;
200 } else {
201 $stringToBeSigned .= '&' . $k . '=' . $v;
202 }
203 $i++;
204 }
205 return $stringToBeSigned;
206 }
207
208 protected function characet($data, $targetCharset)
209 {
210 if (!empty($data) && strcasecmp($this->charset, $targetCharset) != 0) {
211 $data = mb_convert_encoding($data, $targetCharset, $this->charset);
212 }
213 return $data;
214 }
215
216 protected function curlPost($url, $postData = '', $options = [])
217 {
218 if (is_array($postData)) {
219 $postData = http_build_query($postData);
220 }
221 $ch = curl_init();
222 curl_setopt($ch, CURLOPT_URL, $url);
223 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
224 curl_setopt($ch, CURLOPT_POST, 1);
225 curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
226 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
227 if (!empty($options)) {
228 curl_setopt_array($ch, $options);
229 }
230 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
231 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
232 $data = curl_exec($ch);
233 if ($data === false) {
234 error_log('[MNBT alipay_official] curl error: ' . curl_error($ch));
235 }
236 curl_close($ch);
237 return $data;
238 }
239}