WxPay.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. namespace app\common\library\easywechat;
  3. use app\api\service\order\paysuccess\type\PayTypeSuccessFactory;
  4. use app\common\enum\order\OrderTypeEnum;
  5. use app\common\enum\order\OrderPayTypeEnum;
  6. use app\common\exception\BaseException;
  7. use think\facade\Cache;
  8. /**
  9. * 微信支付
  10. */
  11. class WxPay
  12. {
  13. // 微信支付配置
  14. private $app;
  15. /**
  16. * 构造函数
  17. */
  18. public function __construct($app)
  19. {
  20. $this->app = $app;
  21. }
  22. /**
  23. * 统一下单API
  24. */
  25. public function unifiedorder($order_no, $openid, $totalFee, $orderType = OrderTypeEnum::MASTER, $pay_source, $multiple)
  26. {
  27. $data = [
  28. 'attach' => json_encode(['order_type' => $orderType, 'pay_source' => $pay_source, 'multiple' => $multiple]),
  29. 'body' => $order_no,
  30. 'out_trade_no' => $order_no,
  31. 'total_fee' => $totalFee * 100,// 价格:单位分
  32. 'spbill_create_ip' => \request()->ip(),
  33. 'notify_url' => base_url() . 'index.php/job/notify/wxpay', // 异步通知地址
  34. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  35. 'openid' => $openid
  36. ];
  37. //h5支付差异
  38. if($pay_source == 'payH5'){
  39. unset($data['openid']);
  40. $data['trade_type'] = 'MWEB';
  41. $data['scene_info'] = '{"h5_info":{"type":"Wap","wap_url":'.base_url().',"wap_name":"支付"}}';//场景信息 必要参数
  42. }
  43. if($pay_source == 'app'){
  44. $data['trade_type'] = 'APP';
  45. $data['body'] = '订单支付';
  46. }
  47. // 统一下单
  48. $result = $this->app->order->unify($data);
  49. // 请求失败
  50. if ($result['return_code'] === 'FAIL') {
  51. throw new BaseException(['msg' => "微信支付api:{$result['return_msg']}", 'code' => 0]);
  52. }
  53. if ($result['result_code'] === 'FAIL') {
  54. throw new BaseException(['msg' => "微信支付api:{$result['err_code_des']}", 'code' => 0]);
  55. }
  56. //如果是微信小程序
  57. if($pay_source == 'wx' || $pay_source == 'app') {
  58. $time = time();
  59. if($pay_source == 'wx') {
  60. // 二次签名的参数必须与下面相同
  61. $params = [
  62. 'appId' => $result['appid'],//有所修改
  63. 'timeStamp' => $time,
  64. 'nonceStr' => $result['nonce_str'],
  65. 'package' => 'prepay_id=' . $result['prepay_id'],
  66. 'signType' => 'MD5',
  67. ];
  68. $result['paySign'] = $this->makeSign($params);
  69. return [
  70. 'prepay_id' => $result['prepay_id'],
  71. 'nonceStr' => $result['nonce_str'],
  72. 'timeStamp' => (string)$time,
  73. 'paySign' => $result['paySign']
  74. ];
  75. }else if($pay_source == 'app'){
  76. // 二次签名的参数必须与下面相同
  77. $params = [
  78. 'appid' => $result['appid'],//有所修改
  79. 'partnerid' => $result['mch_id'],
  80. 'prepayid' => $result['prepay_id'],
  81. 'package' => 'Sign=WXPay',
  82. 'noncestr' => $result['nonce_str'],
  83. 'timestamp' => $time,
  84. ];
  85. $result['paySign'] = $this->makeSign($params);
  86. return [
  87. 'appid' => $result['appid'],
  88. 'partnerid' => $result['mch_id'],
  89. 'prepayid' => $result['prepay_id'],
  90. 'package' => 'Sign=WXPay',
  91. 'noncestr' => $result['nonce_str'],
  92. 'timestamp' => (string)$time,
  93. 'sign' => $result['paySign']
  94. ];
  95. }
  96. }
  97. return $result;
  98. }
  99. /**
  100. * 支付成功异步通知
  101. */
  102. public function notify()
  103. {
  104. if (!$xml = file_get_contents('php://input')) {
  105. log_write('Not found DATA');
  106. $this->returnCode(false, 'Not found DATA');
  107. }
  108. // 将服务器返回的XML数据转化为数组
  109. $data = $this->fromXml($xml);
  110. // 记录日志
  111. log_write($xml);
  112. log_write($data);
  113. $attach = json_decode($data['attach'], true);
  114. // 实例化订单模型
  115. Cache::tag("cache")->set('pay_result:'.$data['out_trade_no'], ['data'=> $data,'attach'=>$attach], 600);
  116. $PaySuccess = PayTypeSuccessFactory::getFactory($data['out_trade_no'], $attach);
  117. $app_id = $PaySuccess->isExist();
  118. $app_id == 0 && $this->returnCode(false, '订单不存在');
  119. // 支付配置信息
  120. if($attach['pay_source'] == 'mp' || $attach['pay_source'] == 'payH5'){
  121. $this->app = AppMp::getWxPayApp($app_id);
  122. } else if($attach['pay_source'] == 'wx'){
  123. $this->app = AppWx::getWxPayApp($app_id);
  124. } else if($attach['pay_source'] == 'app'){
  125. $this->app = AppOpen::getWxPayApp($app_id);
  126. }
  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 = $PaySuccess->onPaySuccess(OrderPayTypeEnum::WECHAT, $data);
  143. if ($status == false) {
  144. $this->returnCode(false, $PaySuccess->error);
  145. }
  146. // 返回状态
  147. $this->returnCode(true, 'OK');
  148. }
  149. /**
  150. * 申请退款API
  151. */
  152. public function refund($transaction_id, $total_fee, $refund_fee)
  153. {
  154. // 当前时间
  155. $time = time();
  156. $result = $this->app->refund->byTransactionId($transaction_id, $time, intval($total_fee * 100), intval($refund_fee * 100), [
  157. // 可在此处传入其他参数,详细参数见微信支付文档
  158. 'refund_desc' => '用户申请取消',
  159. ]);
  160. // 请求失败
  161. if (empty($result)) {
  162. throw new BaseException(['msg' => '微信退款api请求失败']);
  163. }
  164. // 请求失败
  165. if ($result['return_code'] === 'FAIL') {
  166. throw new BaseException(['msg' => 'return_msg: ' . $result['return_msg']]);
  167. }
  168. if ($result['result_code'] === 'FAIL') {
  169. throw new BaseException(['msg' => 'err_code_des: ' . $result['err_code_des']]);
  170. }
  171. return true;
  172. }
  173. /**
  174. * 企业付款到零钱API
  175. */
  176. public function transfers($order_no, $openid, $amount, $desc)
  177. {
  178. $result = $this->app->transfer->toBalance([
  179. 'partner_trade_no' => $order_no, // 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有符号)
  180. 'openid' => $openid,
  181. 'check_name' => 'NO_CHECK', // NO_CHECK:不校验真实姓名, FORCE_CHECK:强校验真实姓名
  182. 'amount' => $amount * 100, // 企业付款金额,单位为分
  183. 'desc' => $desc, // 企业付款操作说明信息。必填
  184. ]);
  185. // 请求失败
  186. if (empty($result)) {
  187. throw new BaseException(['msg' => '微信提现到零钱api请求失败']);
  188. }
  189. // 请求失败
  190. if ($result['return_code'] === 'FAIL') {
  191. throw new BaseException(['msg' => 'return_msg: ' . $result['return_msg']]);
  192. }
  193. if ($result['result_code'] === 'FAIL') {
  194. throw new BaseException(['msg' => 'err_code_des: ' . $result['err_code_des']]);
  195. }
  196. return true;
  197. }
  198. /**
  199. * 返回状态给微信服务器
  200. */
  201. private function returnCode($returnCode = true, $msg = null)
  202. {
  203. // 返回状态
  204. $return = [
  205. 'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
  206. 'return_msg' => $msg ?: 'OK',
  207. ];
  208. // 记录日志
  209. log_write([
  210. 'describe' => '返回微信支付状态',
  211. 'data' => $return
  212. ]);
  213. die($this->toXml($return));
  214. }
  215. /**
  216. * 生成签名
  217. */
  218. private function makeSign($values)
  219. {
  220. //签名步骤一:按字典序排序参数
  221. ksort($values);
  222. $string = $this->toUrlParams($values);
  223. //签名步骤二:在string后加入KEY
  224. $string = $string . '&key=' . $this->app->config['key'];
  225. //签名步骤三:MD5加密
  226. $string = md5($string);
  227. //签名步骤四:所有字符转为大写
  228. $result = strtoupper($string);
  229. return $result;
  230. }
  231. /**
  232. * 格式化参数格式化成url参数
  233. */
  234. private function toUrlParams($values)
  235. {
  236. $buff = '';
  237. foreach ($values as $k => $v) {
  238. if ($k != 'sign' && $v != '' && !is_array($v)) {
  239. $buff .= $k . '=' . $v . '&';
  240. }
  241. }
  242. return trim($buff, '&');
  243. }
  244. /**
  245. * 将xml转为array
  246. */
  247. private function fromXml($xml)
  248. {
  249. // 禁止引用外部xml实体
  250. libxml_disable_entity_loader(true);
  251. return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  252. }
  253. /**
  254. * 输出xml字符
  255. * @param $values
  256. * @return bool|string
  257. */
  258. private function toXml($values)
  259. {
  260. if (!is_array($values)
  261. || count($values) <= 0
  262. ) {
  263. return false;
  264. }
  265. $xml = "<xml>";
  266. foreach ($values as $key => $val) {
  267. if (is_numeric($val)) {
  268. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  269. } else {
  270. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  271. }
  272. }
  273. $xml .= "</xml>";
  274. return $xml;
  275. }
  276. }