WxPay.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. namespace app\common\library\wechat;
  3. use app\common\model\Wxapp as WxappModel;
  4. use app\common\enum\OrderType as OrderTypeEnum;
  5. use app\common\enum\order\PayType as PayTypeEnum;
  6. use app\common\exception\BaseException;
  7. /**
  8. * 微信支付
  9. * Class WxPay
  10. * @package app\common\library\wechat
  11. */
  12. class WxPay extends WxBase
  13. {
  14. // 微信支付配置
  15. private $config;
  16. // 订单模型
  17. private $modelClass = [
  18. OrderTypeEnum::MASTER => 'app\api\service\order\PaySuccess',
  19. OrderTypeEnum::SHARING => 'app\api\service\sharing\order\PaySuccess',
  20. OrderTypeEnum::RECHARGE => 'app\api\service\recharge\PaySuccess',
  21. ];
  22. /**
  23. * 构造函数
  24. * WxPay constructor.
  25. * @param $config
  26. */
  27. public function __construct($config = false)
  28. {
  29. parent::__construct();
  30. $this->config = $config;
  31. $this->config !== false && $this->setConfig($this->config['app_id'], $this->config['app_secret']);
  32. }
  33. /**
  34. * 统一下单API
  35. * @param $order_no
  36. * @param $openid
  37. * @param $totalFee
  38. * @param int $orderType 订单类型
  39. * @return array
  40. * @throws BaseException
  41. */
  42. public function unifiedorder($order_no, $openid, $totalFee, $orderType = OrderTypeEnum::MASTER)
  43. {
  44. // 当前时间
  45. $time = time();
  46. // 生成随机字符串
  47. $nonceStr = md5($time . $openid);
  48. // API参数
  49. $params = [
  50. 'appid' => $this->appId,
  51. 'attach' => json_encode(['order_type' => $orderType]),
  52. 'body' => $order_no,
  53. 'mch_id' => $this->config['mchid'],
  54. 'nonce_str' => $nonceStr,
  55. 'notify_url' => base_url() . 'notice.php', // 异步通知地址
  56. 'openid' => $openid,
  57. 'out_trade_no' => $order_no,
  58. 'spbill_create_ip' => \request()->ip(),
  59. 'total_fee' => $totalFee * 100, // 价格:单位分
  60. 'trade_type' => 'JSAPI',
  61. ];
  62. // 生成签名
  63. $params['sign'] = $this->makeSign($params);
  64. // 记录日志
  65. $this->doLogs(['name' => '微信支付统一下单API', 'params' => $params]);
  66. // 请求API
  67. $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
  68. $result = $this->post($url, $this->toXml($params));
  69. $prepay = $this->fromXml($result);
  70. // 请求失败
  71. if ($prepay['return_code'] === 'FAIL') {
  72. throw new BaseException(['msg' => "微信支付api:{$prepay['return_msg']}", 'code' => -10]);
  73. }
  74. if ($prepay['result_code'] === 'FAIL') {
  75. throw new BaseException(['msg' => "微信支付api:{$prepay['err_code_des']}", 'code' => -10]);
  76. }
  77. // 生成 nonce_str 供前端使用
  78. $paySign = $this->makePaySign($params['nonce_str'], $prepay['prepay_id'], $time);
  79. return [
  80. 'prepay_id' => $prepay['prepay_id'],
  81. 'nonceStr' => $nonceStr,
  82. 'timeStamp' => (string)$time,
  83. 'paySign' => $paySign
  84. ];
  85. }
  86. /**
  87. * 支付成功异步通知
  88. * @throws BaseException
  89. * @throws \Exception
  90. * @throws \think\exception\DbException
  91. */
  92. public function notify()
  93. {
  94. // $xml = <<<EOF
  95. //<xml><appid><![CDATA[wx8908532a27c5dd4f]]></appid>
  96. //<attach><![CDATA[{"order_type":10}]]></attach>
  97. //<bank_type><![CDATA[CFT]]></bank_type>
  98. //<cash_fee><![CDATA[1]]></cash_fee>
  99. //<fee_type><![CDATA[CNY]]></fee_type>
  100. //<is_subscribe><![CDATA[N]]></is_subscribe>
  101. //<mch_id><![CDATA[1509822581]]></mch_id>
  102. //<nonce_str><![CDATA[ca1fe6d2b4f667cf249bd1d7176c6178]]></nonce_str>
  103. //<openid><![CDATA[oZDDE5JLnVyc6qe6nbNWdbFHtY5I]]></openid>
  104. //<out_trade_no><![CDATA[2019040155491005]]></out_trade_no>
  105. //<result_code><![CDATA[SUCCESS]]></result_code>
  106. //<return_code><![CDATA[SUCCESS]]></return_code>
  107. //<sign><![CDATA[3880232710B7328822D079DC405FB09D]]></sign>
  108. //<time_end><![CDATA[20190401104804]]></time_end>
  109. //<total_fee>1</total_fee>
  110. //<trade_type><![CDATA[JSAPI]]></trade_type>
  111. //<transaction_id><![CDATA[4200000265201904014227830207]]></transaction_id>
  112. //</xml>
  113. //EOF;
  114. if (!$xml = file_get_contents('php://input')) {
  115. $this->returnCode(false, 'Not found DATA');
  116. }
  117. // 将服务器返回的XML数据转化为数组
  118. $data = $this->fromXml($xml);
  119. // 记录日志
  120. $this->doLogs($xml);
  121. $this->doLogs($data);
  122. // 实例化订单模型
  123. $model = $this->getOrderModel($data['out_trade_no'], $data['attach']);
  124. // 订单信息
  125. $order = $model->getOrderInfo();
  126. empty($order) && $this->returnCode(false, '订单不存在');
  127. // 小程序配置信息
  128. $wxConfig = WxappModel::getWxappCache($order['wxapp_id']);
  129. // 设置支付秘钥
  130. $this->config['apikey'] = $wxConfig['apikey'];
  131. // 保存微信服务器返回的签名sign
  132. $dataSign = $data['sign'];
  133. // sign不参与签名算法
  134. unset($data['sign']);
  135. // 生成签名
  136. $sign = $this->makeSign($data);
  137. // 判断签名是否正确 判断支付状态
  138. if (
  139. ($sign !== $dataSign)
  140. || ($data['return_code'] !== 'SUCCESS')
  141. || ($data['result_code'] !== 'SUCCESS')
  142. ) {
  143. $this->returnCode(false, '签名失败');
  144. }
  145. // 订单支付成功业务处理
  146. $status = $model->onPaySuccess(PayTypeEnum::WECHAT, $data);
  147. if ($status == false) {
  148. $this->returnCode(false, $model->getError());
  149. }
  150. // 返回状态
  151. $this->returnCode(true, 'OK');
  152. }
  153. /**
  154. * 申请退款API
  155. * @param $transaction_id
  156. * @param double $total_fee 订单总金额
  157. * @param double $refund_fee 退款金额
  158. * @return bool
  159. * @throws BaseException
  160. */
  161. public function refund($transaction_id, $total_fee, $refund_fee)
  162. {
  163. // 当前时间
  164. $time = time();
  165. // 生成随机字符串
  166. $nonceStr = md5($time . $transaction_id . $total_fee . $refund_fee);
  167. // API参数
  168. $params = [
  169. 'appid' => $this->appId,
  170. 'mch_id' => $this->config['mchid'],
  171. 'nonce_str' => $nonceStr,
  172. 'transaction_id' => $transaction_id,
  173. 'out_refund_no' => $time,
  174. 'total_fee' => $total_fee * 100,
  175. 'refund_fee' => $refund_fee * 100,
  176. ];
  177. // 生成签名
  178. $params['sign'] = $this->makeSign($params);
  179. // 请求API
  180. $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
  181. $result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
  182. // 请求失败
  183. if (empty($result)) {
  184. throw new BaseException(['msg' => '微信退款api请求失败']);
  185. }
  186. // 格式化返回结果
  187. $prepay = $this->fromXml($result);
  188. // 记录日志
  189. log_write(['describe' => '微信退款API', [
  190. 'params' => $params,
  191. 'result' => $result,
  192. 'prepay' => $prepay
  193. ]]);
  194. // 请求失败
  195. if ($prepay['return_code'] === 'FAIL') {
  196. throw new BaseException(['msg' => 'return_msg: ' . $prepay['return_msg']]);
  197. }
  198. if ($prepay['result_code'] === 'FAIL') {
  199. throw new BaseException(['msg' => 'err_code_des: ' . $prepay['err_code_des']]);
  200. }
  201. return true;
  202. }
  203. /**
  204. * 企业付款到零钱API
  205. * @param $order_no
  206. * @param $openid
  207. * @param $amount
  208. * @param $desc
  209. * @return bool
  210. * @throws BaseException
  211. */
  212. public function transfers($order_no, $openid, $amount, $desc)
  213. {
  214. // API参数
  215. $params = [
  216. 'mch_appid' => $this->appId,
  217. 'mchid' => $this->config['mchid'],
  218. 'nonce_str' => md5(uniqid()),
  219. 'partner_trade_no' => $order_no,
  220. 'openid' => $openid,
  221. 'check_name' => 'NO_CHECK',
  222. 'amount' => $amount * 100,
  223. 'desc' => $desc,
  224. 'spbill_create_ip' => \request()->ip(),
  225. ];
  226. // 生成签名
  227. $params['sign'] = $this->makeSign($params);
  228. // 请求API
  229. $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  230. $result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
  231. // 请求失败
  232. if (empty($result)) {
  233. throw new BaseException(['msg' => '微信退款api请求失败']);
  234. }
  235. // 格式化返回结果
  236. $prepay = $this->fromXml($result);
  237. // 请求失败
  238. if ($prepay['return_code'] === 'FAIL') {
  239. throw new BaseException(['msg' => 'return_msg: ' . $prepay['return_msg']]);
  240. }
  241. if ($prepay['result_code'] === 'FAIL') {
  242. throw new BaseException(['msg' => 'err_code_des: ' . $prepay['err_code_des']]);
  243. }
  244. return true;
  245. }
  246. /**
  247. * 获取cert证书文件
  248. * @return array
  249. * @throws BaseException
  250. */
  251. private function getCertPem()
  252. {
  253. if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
  254. throw new BaseException(['msg' => '请先到后台小程序设置填写微信支付证书文件']);
  255. }
  256. // cert目录
  257. $filePath = __DIR__ . '/cert/' . $this->config['wxapp_id'] . '/';
  258. return [
  259. 'certPem' => $filePath . 'cert.pem',
  260. 'keyPem' => $filePath . 'key.pem'
  261. ];
  262. }
  263. /**
  264. * 实例化订单模型 (根据attach判断)
  265. * @param $orderNo
  266. * @param null $attach
  267. * @return mixed
  268. */
  269. private function getOrderModel($orderNo, $attach = null)
  270. {
  271. $attach = json_decode($attach, true);
  272. // 判断订单类型返回对应的订单模型
  273. $model = $this->modelClass[$attach['order_type']];
  274. return new $model($orderNo);
  275. }
  276. /**
  277. * 返回状态给微信服务器
  278. * @param boolean $returnCode
  279. * @param string $msg
  280. */
  281. private function returnCode($returnCode = true, $msg = null)
  282. {
  283. // 返回状态
  284. $return = [
  285. 'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
  286. 'return_msg' => $msg ?: 'OK',
  287. ];
  288. // 记录日志
  289. log_write([
  290. 'describe' => '返回微信支付状态',
  291. 'data' => $return
  292. ]);
  293. die($this->toXml($return));
  294. }
  295. /**
  296. * 生成paySign
  297. * @param $nonceStr
  298. * @param $prepay_id
  299. * @param $timeStamp
  300. * @return string
  301. */
  302. private function makePaySign($nonceStr, $prepay_id, $timeStamp)
  303. {
  304. $data = [
  305. 'appId' => $this->appId,
  306. 'nonceStr' => $nonceStr,
  307. 'package' => 'prepay_id=' . $prepay_id,
  308. 'signType' => 'MD5',
  309. 'timeStamp' => $timeStamp,
  310. ];
  311. // 签名步骤一:按字典序排序参数
  312. ksort($data);
  313. $string = $this->toUrlParams($data);
  314. // 签名步骤二:在string后加入KEY
  315. $string = $string . '&key=' . $this->config['apikey'];
  316. // 签名步骤三:MD5加密
  317. $string = md5($string);
  318. // 签名步骤四:所有字符转为大写
  319. $result = strtoupper($string);
  320. return $result;
  321. }
  322. /**
  323. * 将xml转为array
  324. * @param $xml
  325. * @return mixed
  326. */
  327. private function fromXml($xml)
  328. {
  329. // 禁止引用外部xml实体
  330. libxml_disable_entity_loader(true);
  331. return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  332. }
  333. /**
  334. * 生成签名
  335. * @param $values
  336. * @return string 本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
  337. */
  338. private function makeSign($values)
  339. {
  340. //签名步骤一:按字典序排序参数
  341. ksort($values);
  342. $string = $this->toUrlParams($values);
  343. //签名步骤二:在string后加入KEY
  344. $string = $string . '&key=' . $this->config['apikey'];
  345. //签名步骤三:MD5加密
  346. $string = md5($string);
  347. //签名步骤四:所有字符转为大写
  348. $result = strtoupper($string);
  349. return $result;
  350. }
  351. /**
  352. * 格式化参数格式化成url参数
  353. * @param $values
  354. * @return string
  355. */
  356. private function toUrlParams($values)
  357. {
  358. $buff = '';
  359. foreach ($values as $k => $v) {
  360. if ($k != 'sign' && $v != '' && !is_array($v)) {
  361. $buff .= $k . '=' . $v . '&';
  362. }
  363. }
  364. return trim($buff, '&');
  365. }
  366. /**
  367. * 输出xml字符
  368. * @param $values
  369. * @return bool|string
  370. */
  371. private function toXml($values)
  372. {
  373. if (!is_array($values)
  374. || count($values) <= 0
  375. ) {
  376. return false;
  377. }
  378. $xml = "<xml>";
  379. foreach ($values as $key => $val) {
  380. if (is_numeric($val)) {
  381. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  382. } else {
  383. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  384. }
  385. }
  386. $xml .= "</xml>";
  387. return $xml;
  388. }
  389. }