WxPay.php 12 KB

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