WxPay.JsApiPay.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. /**
  3. *
  4. * example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5. * 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6. * 请勿直接直接使用样例对外提供服务
  7. *
  8. **/
  9. require_once "WxPay.Api.php";
  10. /**
  11. *
  12. * JSAPI支付实现类
  13. * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、
  14. * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数
  15. *
  16. * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发
  17. *
  18. * @author widy
  19. *
  20. */
  21. class JsApiPay
  22. {
  23. /**
  24. *
  25. * 网页授权接口微信服务器返回的数据,返回样例如下
  26. * {
  27. * "access_token":"ACCESS_TOKEN",
  28. * "expires_in":7200,
  29. * "refresh_token":"REFRESH_TOKEN",
  30. * "openid":"OPENID",
  31. * "scope":"SCOPE",
  32. * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
  33. * }
  34. * 其中access_token可用于获取共享收货地址
  35. * openid是微信支付jsapi支付接口必须的参数
  36. * @var array
  37. */
  38. public $data = null;
  39. public function __construct($config)
  40. {
  41. $this->config = $config;
  42. }
  43. /**
  44. *
  45. * 通过跳转获取用户的openid,跳转流程如下:
  46. * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
  47. * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
  48. *
  49. * @return 用户的openid
  50. */
  51. public function GetOpenid()
  52. {
  53. //通过code获得openid
  54. if (!isset($_GET['code'])){
  55. //触发微信返回code码
  56. $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
  57. $url = $this->_CreateOauthUrlForCode($baseUrl);
  58. Header("Location: $url");
  59. exit();
  60. } else {
  61. //获取code码,以获取openid
  62. $code = $_GET['code'];
  63. $openid = $this->getOpenidFromMp($code);
  64. return $openid;
  65. }
  66. }
  67. /**
  68. *
  69. * 获取jsapi支付的参数
  70. * @param array $UnifiedOrderResult 统一支付接口返回的数据
  71. * @throws WxPayException
  72. *
  73. * @return json数据,可直接填入js函数作为参数
  74. */
  75. public function GetJsApiParameters($UnifiedOrderResult)
  76. {
  77. if(!array_key_exists("appid", $UnifiedOrderResult)
  78. || !array_key_exists("prepay_id", $UnifiedOrderResult)
  79. || $UnifiedOrderResult['prepay_id'] == "")
  80. {
  81. throw new WxPayException("参数错误");
  82. }
  83. $jsapi = new WxPayJsApiPay();
  84. $jsapi->SetAppid($UnifiedOrderResult["appid"]);
  85. $timeStamp = time();
  86. $jsapi->SetTimeStamp("$timeStamp");
  87. $jsapi->SetNonceStr(WxPayApi::getNonceStr());
  88. $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
  89. $jsapi->SetPaySign($jsapi->MakeSign($this->config));
  90. $parameters = json_encode($jsapi->GetValues());
  91. return $parameters;
  92. }
  93. /**
  94. *
  95. * 通过code从工作平台获取openid机器access_token
  96. * @param string $code 微信跳转回来带上的code
  97. *
  98. * @return openid
  99. */
  100. public function GetOpenidFromMp($code)
  101. {
  102. $url = $this->__CreateOauthUrlForOpenid($code);
  103. //初始化curl
  104. $ch = curl_init();
  105. $curlVersion = curl_version();
  106. $ua = "WXPaySDK/3.0.9 (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." "
  107. .$this->config->GetMerchantId();
  108. //设置超时
  109. curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
  110. curl_setopt($ch, CURLOPT_URL, $url);
  111. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
  112. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
  113. curl_setopt($ch, CURLOPT_USERAGENT, $ua);
  114. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  115. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  116. $proxyHost = "0.0.0.0";
  117. $proxyPort = 0;
  118. $this->config->GetProxy($proxyHost, $proxyPort);
  119. if($proxyHost != "0.0.0.0" && $proxyPort != 0){
  120. curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
  121. curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
  122. }
  123. //运行curl,结果以jason形式返回
  124. $res = curl_exec($ch);
  125. curl_close($ch);
  126. //取出openid
  127. $data = json_decode($res,true);
  128. $this->data = $data;
  129. $openid = $data['openid'];
  130. return $openid;
  131. }
  132. /**
  133. *
  134. * 拼接签名字符串
  135. * @param array $urlObj
  136. *
  137. * @return 返回已经拼接好的字符串
  138. */
  139. private function ToUrlParams($urlObj)
  140. {
  141. $buff = "";
  142. foreach ($urlObj as $k => $v)
  143. {
  144. if($k != "sign"){
  145. $buff .= $k . "=" . $v . "&";
  146. }
  147. }
  148. $buff = trim($buff, "&");
  149. return $buff;
  150. }
  151. /**
  152. *
  153. * 获取地址js参数
  154. *
  155. * @return 获取共享收货地址js函数需要的参数,json格式可以直接做参数使用
  156. */
  157. public function GetEditAddressParameters()
  158. {
  159. $getData = $this->data;
  160. $data = array();
  161. $data["appid"] = $this->config->GetAppId();
  162. $data["url"] = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  163. $time = time();
  164. $data["timestamp"] = "$time";
  165. $data["noncestr"] = WxPayApi::getNonceStr();
  166. $data["accesstoken"] = $getData["access_token"];
  167. ksort($data);
  168. $params = $this->ToUrlParams($data);
  169. $addrSign = sha1($params);
  170. $afterData = array(
  171. "addrSign" => $addrSign,
  172. "signType" => "sha1",
  173. "scope" => "jsapi_address",
  174. "appId" => $this->config->GetAppId(),
  175. "timeStamp" => $data["timestamp"],
  176. "nonceStr" => $data["noncestr"]
  177. );
  178. $parameters = json_encode($afterData);
  179. return $parameters;
  180. }
  181. /**
  182. *
  183. * 构造获取code的url连接
  184. * @param string $redirectUrl 微信服务器回跳的url,需要url编码
  185. *
  186. * @return 返回构造好的url
  187. */
  188. private function _CreateOauthUrlForCode($redirectUrl)
  189. {
  190. $urlObj["appid"] = $this->config->GetAppId();
  191. $urlObj["redirect_uri"] = "$redirectUrl";
  192. $urlObj["response_type"] = "code";
  193. $urlObj["scope"] = "snsapi_base";
  194. $urlObj["state"] = "STATE"."#wechat_redirect";
  195. $bizString = $this->ToUrlParams($urlObj);
  196. return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
  197. }
  198. /**
  199. *
  200. * 构造获取open和access_toke的url地址
  201. * @param string $code,微信跳转带回的code
  202. *
  203. * @return 请求的url
  204. */
  205. private function __CreateOauthUrlForOpenid($code)
  206. {
  207. $urlObj["appid"] = $this->config->GetAppId();
  208. $urlObj["secret"] = $this->config->GetAppSecret();
  209. $urlObj["code"] = $code;
  210. $urlObj["grant_type"] = "authorization_code";
  211. $bizString = $this->ToUrlParams($urlObj);
  212. return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
  213. }
  214. }