微信开发之授权获取用户信息(昵称、头像等)

测试  
  1. <?php
  2. error_reporting(1);
  3. header('Content-type:text/html; Charset=utf-8');
  4. /* 配置开始 */
  5. $appid = ''; //微信公众平台->开发->基本配置->AppID
  6. $appKey = ''; //微信公众平台->开发->基本配置->AppSecret
  7. /* 配置结束 */
  8. //①、获取用户openid
  9. $wxPay = new WxService($appid,$appKey);
  10. $data = $wxPay->GetOpenid(); //获取openid
  11. if(!$data['openid']) exit('获取openid失败');
  12. //②、获取用户信息
  13. $user = $wxPay->getUserInfo($data['openid'],$data['access_token']);
  14. ?>
  15. <!DOCTYPE html>
  16. <html lang="en">
  17. <head>
  18. <meta charset="UTF-8">
  19. <meta name="renderer" content="webkit" />
  20. <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
  21. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
  22. <title>微信获取用户信息demo</title>
  23. <link href="https://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
  24. <script src="https://cdn.bootcss.com/jquery/2.1.0/jquery.min.js"></script>
  25. </head>
  26. <body>
  27. <div class="container">
  28. <div class="row">
  29. <h1>你的基本信息如下:</h1>
  30. <table class="table table-bordered">
  31. <tr>
  32. <td>openid</td>
  33. <td><?=$user['openid']?></td>
  34. </tr>
  35. <tr>
  36. <td>unionid</td>
  37. <td><?=$user['unionid']?></td>
  38. </tr>
  39. <tr>
  40. <td>昵称</td>
  41. <td><?=$user['nickname']?></td>
  42. </tr>
  43. <tr>
  44. <td>头像</td>
  45. <td><img src="<?=$user['headimgurl']?>" style="width: 100px;" alt=""></td>
  46. </tr>
  47. <tr>
  48. <td>性别</td>
  49. <td><?php
  50. switch (strtoupper($user['sex'])){
  51. case 1:
  52. echo '男性';
  53. break;
  54. case 2:
  55. echo '女性';
  56. break;
  57. default:
  58. echo '未知';
  59. break;
  60. }
  61. ?></td>
  62. </tr>
  63. <tr>
  64. <td>省份 / 城市</td>
  65. <td><?=$user['province'].' / '.$user['city']?></td>
  66. </tr>
  67. <tr>
  68. <td>language</td>
  69. <td><?=$user['language']?></td>
  70. </tr>
  71. </table>
  72. </div>
  73. </div>
  74. </body>
  75. </html>
  76. <?php
  77. class WxService
  78. {
  79. protected $appid;
  80. protected $appKey;
  81. public $data = null;
  82. public function __construct($appid, $appKey)
  83. {
  84. $this->appid = $appid; //微信支付申请对应的公众号的APPID
  85. $this->appKey = $appKey; //微信支付申请对应的公众号的APP Key
  86. }
  87. /**
  88. * 通过跳转获取用户的openid,跳转流程如下:
  89. * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
  90. * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
  91. *
  92. * @return 用户的openid
  93. */
  94. public function GetOpenid()
  95. {
  96. //通过code获得openid
  97. if (!isset($_GET['code'])){
  98. //触发微信返回code码
  99. $baseUrl = $this->getCurrentUrl();
  100. $url = $this->__CreateOauthUrlForCode($baseUrl);
  101. Header("Location: $url");
  102. exit();
  103. } else {
  104. //获取code码,以获取openid
  105. $code = $_GET['code'];
  106. $openid = $this->getOpenidFromMp($code);
  107. return $openid;
  108. }
  109. }
  110. public function getCurrentUrl()
  111. {
  112. $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
  113. $uri = $_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
  114. if($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];
  115. $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$uri);
  116. return $baseUrl;
  117. }
  118. /**
  119. * 通过code从工作平台获取openid机器access_token
  120. * @param string $code 微信跳转回来带上的code
  121. * @return openid
  122. */
  123. public function GetOpenidFromMp($code)
  124. {
  125. $url = $this->__CreateOauthUrlForOpenid($code);
  126. $res = self::curlGet($url);
  127. $data = json_decode($res,true);
  128. $this->data = $data;
  129. return $data;
  130. }
  131. /**
  132. * 构造获取open和access_toke的url地址
  133. * @param string $code,微信跳转带回的code
  134. * @return 请求的url
  135. */
  136. private function __CreateOauthUrlForOpenid($code)
  137. {
  138. $urlObj["appid"] = $this->appid;
  139. $urlObj["secret"] = $this->appKey;
  140. $urlObj["code"] = $code;
  141. $urlObj["grant_type"] = "authorization_code";
  142. $bizString = $this->ToUrlParams($urlObj);
  143. return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
  144. }
  145. /**
  146. * 构造获取code的url连接
  147. * @param string $redirectUrl 微信服务器回跳的url,需要url编码
  148. * @return 返回构造好的url
  149. */
  150. private function __CreateOauthUrlForCode($redirectUrl)
  151. {
  152. $urlObj["appid"] = $this->appid;
  153. $urlObj["redirect_uri"] = "$redirectUrl";
  154. $urlObj["response_type"] = "code";
  155. $urlObj["scope"] = "snsapi_userinfo";
  156. $urlObj["state"] = "STATE";
  157. $bizString = $this->ToUrlParams($urlObj);
  158. return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
  159. }
  160. /**
  161. * 拼接签名字符串
  162. * @param array $urlObj
  163. * @return 返回已经拼接好的字符串
  164. */
  165. private function ToUrlParams($urlObj)
  166. {
  167. $buff = "";
  168. foreach ($urlObj as $k => $v)
  169. {
  170. if($k != "sign") $buff .= $k . "=" . $v . "&";
  171. }
  172. $buff = trim($buff, "&");
  173. return $buff;
  174. }
  175. /**
  176. * 获取用户信息
  177. * @param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid
  178. * @return string
  179. */
  180. public function getUserInfo($openid,$access_token)
  181. {
  182. $response = self::curlGet('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
  183. return json_decode($response,true);
  184. }
  185. public static function curlGet($url = '', $options = array())
  186. {
  187. $ch = curl_init($url);
  188. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  189. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  190. if (!empty($options)) {
  191. curl_setopt_array($ch, $options);
  192. }
  193. //https请求 不验证证书和host
  194. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  195. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  196. $data = curl_exec($ch);
  197. curl_close($ch);
  198. return $data;
  199. }
  200. public static function curlPost($url = '', $postData = '', $options = array())
  201. {
  202. if (is_array($postData)) {
  203. $postData = http_build_query($postData);
  204. }
  205. $ch = curl_init();
  206. curl_setopt($ch, CURLOPT_URL, $url);
  207. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  208. curl_setopt($ch, CURLOPT_POST, 1);
  209. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  210. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  211. if (!empty($options)) {
  212. curl_setopt_array($ch, $options);
  213. }
  214. //https请求 不验证证书和host
  215. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  216. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  217. $data = curl_exec($ch);
  218. curl_close($ch);
  219. return $data;
  220. }
  221. }


评论 0

发表评论

Top