WxpayService.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace service;
  12. /**
  13. * 微信扫码支付
  14. * Class WxpayService
  15. * @package service
  16. *
  17. * 调用实例
  18. *
  19. * $data['total_amount'] = $payAmount;//价格
  20. $data['order_id'] = time().$themeEnlist['enlist_card'].mt_rand(10,99);//订单 不能超过32为
  21. ThemeEnlistModel::edit($data,$idB);
  22. $mchid = SystemConfig::getValue('pay_weixin_mchid'); //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
  23. $appid = SystemConfig::getValue('pay_weixin_appid'); //公众号APPID 通过微信支付商户资料审核后邮件发送
  24. $apiKey = SystemConfig::getValue('pay_weixin_key'); //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
  25. $wxPay = new WxpayService($mchid,$appid,$apiKey);//实例化微信扫码类
  26. $outTradeNo = $data['order_id']; //你自己的商品订单号
  27. $notifyUrl = SystemConfig::getValue('site_url').Url::build('index/Themeenlist/wapay_success_notify'); //付款成功后的回调地址(不要有问号)
  28. $payTime = time(); //付款时间
  29. $arr = $wxPay->createJsBizPackage($payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);//创建成功会微信返回的数据
  30. $url = 'http://pan.baidu.com/share/qrcode?w=104&h=100&url='.$arr['code_url'];//生成二维码 http://pan.baidu.com/share/qrcode 百度在线生成二维码链家
  31. */
  32. class WxpayService
  33. {
  34. protected $mchid;
  35. protected $appid;
  36. protected $apiKey;
  37. public function __construct($mchid, $appid, $key)
  38. {
  39. $this->mchid = $mchid;
  40. $this->appid = $appid;
  41. $this->apiKey = $key;
  42. }
  43. /**
  44. * 发起订单
  45. * @param float $totalFee 收款总费用 单位元
  46. * @param string $outTradeNo 唯一的订单号
  47. * @param string $orderName 订单名称
  48. * @param string $notifyUrl 支付结果通知url 不要有问号
  49. * @param string $timestamp 订单发起时间
  50. * @return array
  51. */
  52. public function createJsBizPackage($totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
  53. {
  54. $config = array(
  55. 'mch_id' => $this->mchid,
  56. 'appid' => $this->appid,
  57. 'key' => $this->apiKey,
  58. );
  59. //$orderName = iconv('GBK','UTF-8',$orderName);
  60. $unified = array(
  61. 'appid' => $config['appid'],
  62. 'attach' => 'pay', //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
  63. 'body' => $orderName,
  64. 'mch_id' => $config['mch_id'],
  65. 'nonce_str' => self::createNonceStr(),
  66. 'notify_url' => $notifyUrl,
  67. 'out_trade_no' => $outTradeNo,
  68. 'spbill_create_ip' => '127.0.0.1',
  69. 'total_fee' => intval($totalFee * 100), //单位 转为分
  70. 'trade_type' => 'NATIVE',
  71. );
  72. $unified['sign'] = self::getSign($unified, $config['key']);
  73. $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
  74. $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  75. if ($unifiedOrder === false) {
  76. die('parse xml error');
  77. }
  78. if ($unifiedOrder->return_code != 'SUCCESS') {
  79. die($unifiedOrder->return_msg);
  80. }
  81. if ($unifiedOrder->result_code != 'SUCCESS') {
  82. die($unifiedOrder->err_code);
  83. }
  84. $codeUrl = (array)($unifiedOrder->code_url);
  85. if(!$codeUrl[0]) exit('get code_url error');
  86. $arr = array(
  87. "appId" => $config['appid'],
  88. "timeStamp" => $timestamp,
  89. "nonceStr" => self::createNonceStr(),
  90. "package" => "prepay_id=" . $unifiedOrder->prepay_id,
  91. "signType" => 'MD5',
  92. "code_url" => $codeUrl[0],
  93. );
  94. $arr['paySign'] = self::getSign($arr, $config['key']);
  95. return $arr;
  96. }
  97. public function notify()
  98. {
  99. $config = array(
  100. 'mch_id' => $this->mchid,
  101. 'appid' => $this->appid,
  102. 'key' => $this->apiKey,
  103. );
  104. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  105. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  106. if ($postObj === false) {
  107. die('parse xml error');
  108. }
  109. if ($postObj->return_code != 'SUCCESS') {
  110. die($postObj->return_msg);
  111. }
  112. if ($postObj->result_code != 'SUCCESS') {
  113. die($postObj->err_code);
  114. }
  115. $arr = (array)$postObj;
  116. unset($arr['sign']);
  117. if (self::getSign($arr, $config['key']) == $postObj->sign) {
  118. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  119. return $postObj;
  120. }
  121. }
  122. /**
  123. * curl get
  124. *
  125. * @param string $url
  126. * @param array $options
  127. * @return mixed
  128. */
  129. public static function curlGet($url = '', $options = array())
  130. {
  131. $ch = curl_init($url);
  132. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  133. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  134. if (!empty($options)) {
  135. curl_setopt_array($ch, $options);
  136. }
  137. //https请求 不验证证书和host
  138. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  139. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  140. $data = curl_exec($ch);
  141. curl_close($ch);
  142. return $data;
  143. }
  144. public static function curlPost($url = '', $postData = '', $options = array())
  145. {
  146. if (is_array($postData)) {
  147. $postData = http_build_query($postData);
  148. }
  149. $ch = curl_init();
  150. curl_setopt($ch, CURLOPT_URL, $url);
  151. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  152. curl_setopt($ch, CURLOPT_POST, 1);
  153. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  154. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  155. if (!empty($options)) {
  156. curl_setopt_array($ch, $options);
  157. }
  158. //https请求 不验证证书和host
  159. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  160. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  161. $data = curl_exec($ch);
  162. curl_close($ch);
  163. return $data;
  164. }
  165. public static function createNonceStr($length = 16)
  166. {
  167. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  168. $str = '';
  169. for ($i = 0; $i < $length; $i++) {
  170. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  171. }
  172. return $str;
  173. }
  174. public static function arrayToXml($arr)
  175. {
  176. $xml = "<xml>";
  177. foreach ($arr as $key => $val) {
  178. if (is_numeric($val)) {
  179. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  180. } else
  181. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  182. }
  183. $xml .= "</xml>";
  184. return $xml;
  185. }
  186. /**
  187. * 获取签名
  188. */
  189. public static function getSign($params, $key)
  190. {
  191. ksort($params, SORT_STRING);
  192. $unSignParaString = self::formatQueryParaMap($params, false);
  193. $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
  194. return $signStr;
  195. }
  196. protected static function formatQueryParaMap($paraMap, $urlEncode = false)
  197. {
  198. $buff = "";
  199. ksort($paraMap);
  200. foreach ($paraMap as $k => $v) {
  201. if (null != $v && "null" != $v) {
  202. if ($urlEncode) {
  203. $v = urlencode($v);
  204. }
  205. $buff .= $k . "=" . $v . "&";
  206. }
  207. }
  208. $reqPar = '';
  209. if (strlen($buff) > 0) {
  210. $reqPar = substr($buff, 0, strlen($buff) - 1);
  211. }
  212. return $reqPar;
  213. }
  214. }