WxPay.php 9.8 KB

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