微信支付之原生支付(扫码支付)

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


评论 0

发表评论

Top