WxPay.php 13 KB

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