WxpayService.php 7.7 KB

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