WxPay.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.thinkphp.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: thinkphp <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\library\wechat;
  12. use app\common\model\wxapp\Setting as WxappSettingModel;
  13. use app\common\enum\OrderType as OrderTypeEnum;
  14. use app\common\enum\order\PayType as OrderPayTypeEnum;
  15. use app\common\library\helper;
  16. use app\common\exception\BaseException;
  17. /**
  18. * 微信支付
  19. * Class WxPay
  20. * @package app\common\library\wechat
  21. */
  22. class WxPay extends WxBase
  23. {
  24. // 微信支付配置
  25. private $config;
  26. // 当前商城ID
  27. private $storeId;
  28. // 订单模型
  29. private $modelClass = [
  30. OrderTypeEnum::ORDER => \app\api\service\order\PaySuccess::class,
  31. OrderTypeEnum::RECHARGE => \app\api\service\recharge\PaySuccess::class,
  32. OrderTypeEnum::BOOK => \app\api\service\book\PaySuccess::class,
  33. OrderTypeEnum::LOCKED => \app\api\service\book\PaySuccess::class,
  34. ];
  35. /**
  36. * 构造函数
  37. * @param array $config
  38. * @param int|null $storeId
  39. */
  40. public function __construct(array $config = [], ?int $storeId = null)
  41. {
  42. parent::__construct();
  43. $this->config = $config;
  44. $this->storeId = $storeId;
  45. if (!empty($this->config)) {
  46. $this->setConfig($this->config['app_id'], $this->config['app_secret']);
  47. }
  48. }
  49. /**
  50. * 统一下单API
  51. * @param $orderNo
  52. * @param $openid
  53. * @param $totalFee
  54. * @param int $orderType 订单类型
  55. * @return array
  56. * @throws \cores\exception\BaseException
  57. */
  58. public function unifiedorder($orderNo, $openid, $totalFee, int $orderType = OrderTypeEnum::ORDER): array
  59. {
  60. // 当前时间
  61. $time = time();
  62. // 生成随机字符串
  63. $nonceStr = md5($time . $openid);
  64. // API参数
  65. $params = [
  66. 'appid' => $this->appId,
  67. 'attach' => helper::jsonEncode(['order_type' => $orderType]),
  68. 'body' => $orderNo,
  69. 'mch_id' => $this->config['mchid'],
  70. 'nonce_str' => $nonceStr,
  71. 'notify_url' => base_url() . 'notice.php', // 异步通知地址
  72. 'openid' => $openid,
  73. 'out_trade_no' => $orderNo,
  74. 'spbill_create_ip' => \request()->ip(),
  75. 'total_fee' => (int)helper::bcmul($totalFee, 100), // 价格:单位分
  76. 'trade_type' => 'JSAPI',
  77. ];
  78. // 生成签名
  79. $params['sign'] = $this->makeSign($params);
  80. // 请求API
  81. $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
  82. $result = $this->post($url, $this->toXml($params));
  83. $prepay = $this->fromXml($result);
  84. // 请求失败
  85. if ($prepay['return_code'] === 'FAIL') {
  86. $errMsg = "微信支付api:{$prepay['return_msg']}";
  87. throwError($errMsg, null, ['errorCode' => 'WECHAT_PAY', 'isCreated' => true]);
  88. }
  89. if ($prepay['result_code'] === 'FAIL') {
  90. $errMsg = "微信支付api:{$prepay['err_code_des']}";
  91. throwError($errMsg, null, ['errorCode' => 'WECHAT_PAY', 'isCreated' => true]);
  92. }
  93. // 生成 nonce_str 供前端使用
  94. $paySign = $this->makePaySign($params['nonce_str'], $prepay['prepay_id'], $time);
  95. return [
  96. 'prepay_id' => $prepay['prepay_id'],
  97. 'nonceStr' => $nonceStr,
  98. 'timeStamp' => (string)$time,
  99. 'paySign' => $paySign
  100. ];
  101. }
  102. /**
  103. * 支付成功异步通知
  104. * @throws \think\db\exception\DataNotFoundException
  105. * @throws \think\db\exception\DbException
  106. * @throws \think\db\exception\ModelNotFoundException
  107. */
  108. public function notify()
  109. {
  110. if (!$xml = file_get_contents('php://input')) {
  111. $this->returnCode(false, 'Not found DATA');
  112. }
  113. // 将服务器返回的XML数据转化为数组
  114. $data = $this->fromXml($xml);
  115. // 记录日志
  116. log_record($xml);
  117. log_record($data);
  118. // 实例化订单模型
  119. $model = $this->getOrderModel($data['out_trade_no'], $data['attach']);
  120. // 订单信息
  121. $order = $model->getOrderInfo();
  122. empty($order) && $this->returnCode(false, '订单不存在');
  123. // 小程序配置信息
  124. $wxConfig = WxappSettingModel::getWxappConfig($order['store_id']);
  125. // 设置支付秘钥
  126. $this->config['apikey'] = $wxConfig['apikey'];
  127. // 保存微信服务器返回的签名sign
  128. $dataSign = $data['sign'];
  129. // sign不参与签名算法
  130. unset($data['sign']);
  131. // 生成签名
  132. $sign = $this->makeSign($data);
  133. // 判断签名是否正确 判断支付状态
  134. if (
  135. ($sign !== $dataSign)
  136. || ($data['return_code'] !== 'SUCCESS')
  137. || ($data['result_code'] !== 'SUCCESS')
  138. ) {
  139. $this->returnCode(false, '签名失败');
  140. }
  141. // 订单支付成功业务处理
  142. $status = $model->onPaySuccess(OrderPayTypeEnum::WECHAT, $data);
  143. if ($status == false) {
  144. $this->returnCode(false, $model->getError());
  145. }
  146. // 返回状态
  147. $this->returnCode(true, 'OK');
  148. }
  149. /**
  150. * 申请退款API
  151. * @param string $transactionId 微信支付交易流水号
  152. * @param string $totalFee 订单总金额
  153. * @param string $refundFee 退款金额
  154. * @return bool
  155. * @throws BaseException
  156. * @throws \cores\exception\BaseException
  157. */
  158. public function refund(string $transactionId, string $totalFee, string $refundFee): bool
  159. {
  160. // 当前时间
  161. $time = time();
  162. // 生成随机字符串
  163. $nonceStr = md5($time . $transactionId . $totalFee . $refundFee);
  164. // API参数
  165. $params = [
  166. 'appid' => $this->appId,
  167. 'mch_id' => $this->config['mchid'],
  168. 'nonce_str' => $nonceStr,
  169. 'transaction_id' => $transactionId,
  170. 'out_refund_no' => $time,
  171. 'total_fee' => helper::bcmul($totalFee,100),
  172. 'refund_fee' => helper::bcmul($refundFee,100),
  173. ];
  174. // 生成签名
  175. $params['sign'] = $this->makeSign($params);
  176. // 请求API
  177. $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
  178. $result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
  179. // 请求失败
  180. if (empty($result)) {
  181. throwError('微信退款api请求失败');
  182. }
  183. // 格式化返回结果
  184. $prepay = $this->fromXml($result);
  185. // 记录日志
  186. log_record(['name' => '微信退款API', [
  187. 'params' => $params,
  188. 'result' => $result,
  189. 'prepay' => $prepay
  190. ]]);
  191. // 请求失败
  192. if ($prepay['return_code'] === 'FAIL') {
  193. throwError("return_msg: {$prepay['return_msg']}");
  194. }
  195. if ($prepay['result_code'] === 'FAIL') {
  196. throwError("err_code_des: {$prepay['err_code_des']}");
  197. }
  198. return true;
  199. }
  200. /**
  201. * 获取cert证书文件
  202. * @return string[]
  203. * @throws \cores\exception\BaseException
  204. */
  205. private function getCertPem(): array
  206. {
  207. if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
  208. throwError('请先到后台小程序设置填写微信支付证书文件');
  209. }
  210. // cert目录
  211. $filePath = __DIR__ . "/cert/{$this->storeId}/";
  212. return [
  213. 'certPem' => $filePath . 'cert.pem',
  214. 'keyPem' => $filePath . 'key.pem'
  215. ];
  216. }
  217. /**
  218. * 实例化订单模型 (根据attach判断)
  219. * @param $orderNo
  220. * @param null $attach
  221. * @return mixed
  222. */
  223. private function getOrderModel($orderNo, $attach = null)
  224. {
  225. $attach = helper::jsonDecode($attach);
  226. // 判断订单类型返回对应的订单模型
  227. $model = $this->modelClass[$attach['order_type']];
  228. return new $model($orderNo);
  229. }
  230. /**
  231. * 返回状态给微信服务器
  232. * @param boolean $returnCode
  233. * @param string|null $msg
  234. */
  235. private function returnCode(bool $returnCode = true, string $msg = null)
  236. {
  237. // 返回状态
  238. $return = [
  239. 'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
  240. 'return_msg' => $msg ?: 'OK',
  241. ];
  242. // 记录日志
  243. log_record([
  244. 'name' => '返回微信支付状态',
  245. 'data' => $return
  246. ]);
  247. die($this->toXml($return));
  248. }
  249. /**
  250. * 生成paySign
  251. * @param string $nonceStr
  252. * @param string $prepayId
  253. * @param int $timeStamp
  254. * @return string
  255. */
  256. private function makePaySign(string $nonceStr, string $prepayId, int $timeStamp): string
  257. {
  258. $data = [
  259. 'appId' => $this->appId,
  260. 'nonceStr' => $nonceStr,
  261. 'package' => 'prepay_id=' . $prepayId,
  262. 'signType' => 'MD5',
  263. 'timeStamp' => $timeStamp,
  264. ];
  265. // 签名步骤一:按字典序排序参数
  266. ksort($data);
  267. $string = $this->toUrlParams($data);
  268. // 签名步骤二:在string后加入KEY
  269. $string = $string . '&key=' . $this->config['apikey'];
  270. // 签名步骤三:MD5加密
  271. $string = md5($string);
  272. // 签名步骤四:所有字符转为大写
  273. return strtoupper($string);
  274. }
  275. /**
  276. * 将xml转为array
  277. * @param string $xml
  278. * @return mixed
  279. */
  280. private function fromXml(string $xml)
  281. {
  282. // 禁止引用外部xml实体
  283. libxml_disable_entity_loader(true);
  284. return helper::jsonDecode(helper::jsonEncode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)));
  285. }
  286. /**
  287. * 生成签名
  288. * @param array $values
  289. * @return string 本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
  290. */
  291. private function makeSign(array $values): string
  292. {
  293. //签名步骤一:按字典序排序参数
  294. ksort($values);
  295. $string = $this->toUrlParams($values);
  296. //签名步骤二:在string后加入KEY
  297. $string = $string . '&key=' . $this->config['apikey'];
  298. //签名步骤三:MD5加密
  299. $string = md5($string);
  300. //签名步骤四:所有字符转为大写
  301. return strtoupper($string);
  302. }
  303. /**
  304. * 格式化参数格式化成url参数
  305. * @param array $values
  306. * @return string
  307. */
  308. private function toUrlParams(array $values): string
  309. {
  310. $buff = '';
  311. foreach ($values as $k => $v) {
  312. if ($k != 'sign' && $v != '' && !is_array($v)) {
  313. $buff .= $k . '=' . $v . '&';
  314. }
  315. }
  316. return trim($buff, '&');
  317. }
  318. /**
  319. * 输出xml字符
  320. * @param array $values
  321. * @return bool|string
  322. */
  323. private function toXml(array $values)
  324. {
  325. if (!is_array($values)
  326. || count($values) <= 0
  327. ) {
  328. return false;
  329. }
  330. $xml = "<xml>";
  331. foreach ($values as $key => $val) {
  332. if (is_numeric($val)) {
  333. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  334. } else {
  335. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  336. }
  337. }
  338. $xml .= "</xml>";
  339. return $xml;
  340. }
  341. }