WxPay.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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' => $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' => $totalFee * 100,
  170. 'refund_fee' => $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. * 企业付款到零钱API
  200. * @param string $orderNo 订单号
  201. * @param string $openid 微信用户openid
  202. * @param string $amount 支付金额
  203. * @param string $desc 描述
  204. * @return bool
  205. * @throws BaseException
  206. * @throws \cores\exception\BaseException
  207. */
  208. public function transfers(string $orderNo, string $openid, string $amount, string $desc): bool
  209. {
  210. // API参数
  211. $params = [
  212. 'mch_appid' => $this->appId,
  213. 'mchid' => $this->config['mchid'],
  214. 'nonce_str' => md5(uniqid()),
  215. 'partner_trade_no' => $orderNo,
  216. 'openid' => $openid,
  217. 'check_name' => 'NO_CHECK',
  218. 'amount' => $amount * 100,
  219. 'desc' => $desc,
  220. 'spbill_create_ip' => \request()->ip(),
  221. ];
  222. // 生成签名
  223. $params['sign'] = $this->makeSign($params);
  224. // 请求API
  225. $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  226. $result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
  227. // 请求失败
  228. if (empty($result)) {
  229. throwError('企业付款到零钱API请求失败');
  230. }
  231. // 格式化返回结果
  232. $prepay = $this->fromXml($result);
  233. // 请求失败
  234. if ($prepay['return_code'] === 'FAIL') {
  235. throwError("return_msg: {$prepay['return_msg']}");
  236. }
  237. if ($prepay['result_code'] === 'FAIL') {
  238. throwError("err_code_des: {$prepay['err_code_des']}");
  239. }
  240. return true;
  241. }
  242. /**
  243. * 获取cert证书文件
  244. * @return string[]
  245. * @throws \cores\exception\BaseException
  246. */
  247. private function getCertPem(): array
  248. {
  249. if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
  250. throwError('请先到后台小程序设置填写微信支付证书文件');
  251. }
  252. // cert目录
  253. $filePath = __DIR__ . "/cert/{$this->storeId}/";
  254. return [
  255. 'certPem' => $filePath . 'cert.pem',
  256. 'keyPem' => $filePath . 'key.pem'
  257. ];
  258. }
  259. /**
  260. * 实例化订单模型 (根据attach判断)
  261. * @param $orderNo
  262. * @param null $attach
  263. * @return mixed
  264. */
  265. private function getOrderModel($orderNo, $attach = null)
  266. {
  267. $attach = helper::jsonDecode($attach);
  268. // 判断订单类型返回对应的订单模型
  269. $model = $this->modelClass[$attach['order_type']];
  270. return new $model($orderNo);
  271. }
  272. /**
  273. * 返回状态给微信服务器
  274. * @param boolean $returnCode
  275. * @param string $msg
  276. */
  277. private function returnCode($returnCode = true, $msg = null)
  278. {
  279. // 返回状态
  280. $return = [
  281. 'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
  282. 'return_msg' => $msg ?: 'OK',
  283. ];
  284. // 记录日志
  285. log_record([
  286. 'name' => '返回微信支付状态',
  287. 'data' => $return
  288. ]);
  289. die($this->toXml($return));
  290. }
  291. /**
  292. * 生成paySign
  293. * @param string $nonceStr
  294. * @param string $prepayId
  295. * @param int $timeStamp
  296. * @return string
  297. */
  298. private function makePaySign(string $nonceStr, string $prepayId, int $timeStamp): string
  299. {
  300. $data = [
  301. 'appId' => $this->appId,
  302. 'nonceStr' => $nonceStr,
  303. 'package' => 'prepay_id=' . $prepayId,
  304. 'signType' => 'MD5',
  305. 'timeStamp' => $timeStamp,
  306. ];
  307. // 签名步骤一:按字典序排序参数
  308. ksort($data);
  309. $string = $this->toUrlParams($data);
  310. // 签名步骤二:在string后加入KEY
  311. $string = $string . '&key=' . $this->config['apikey'];
  312. // 签名步骤三:MD5加密
  313. $string = md5($string);
  314. // 签名步骤四:所有字符转为大写
  315. return strtoupper($string);
  316. }
  317. /**
  318. * 将xml转为array
  319. * @param string $xml
  320. * @return mixed
  321. */
  322. private function fromXml(string $xml)
  323. {
  324. // 禁止引用外部xml实体
  325. libxml_disable_entity_loader(true);
  326. return helper::jsonDecode(helper::jsonEncode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)));
  327. }
  328. /**
  329. * 生成签名
  330. * @param array $values
  331. * @return string 本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
  332. */
  333. private function makeSign(array $values): string
  334. {
  335. //签名步骤一:按字典序排序参数
  336. ksort($values);
  337. $string = $this->toUrlParams($values);
  338. //签名步骤二:在string后加入KEY
  339. $string = $string . '&key=' . $this->config['apikey'];
  340. //签名步骤三:MD5加密
  341. $string = md5($string);
  342. //签名步骤四:所有字符转为大写
  343. return strtoupper($string);
  344. }
  345. /**
  346. * 格式化参数格式化成url参数
  347. * @param array $values
  348. * @return string
  349. */
  350. private function toUrlParams(array $values): string
  351. {
  352. $buff = '';
  353. foreach ($values as $k => $v) {
  354. if ($k != 'sign' && $v != '' && !is_array($v)) {
  355. $buff .= $k . '=' . $v . '&';
  356. }
  357. }
  358. return trim($buff, '&');
  359. }
  360. /**
  361. * 输出xml字符
  362. * @param array $values
  363. * @return bool|string
  364. */
  365. private function toXml(array $values)
  366. {
  367. if (!is_array($values)
  368. || count($values) <= 0
  369. ) {
  370. return false;
  371. }
  372. $xml = "<xml>";
  373. foreach ($values as $key => $val) {
  374. if (is_numeric($val)) {
  375. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  376. } else {
  377. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  378. }
  379. }
  380. $xml .= "</xml>";
  381. return $xml;
  382. }
  383. }