微信获取用户信息

 1 <?php
 2 
 3 
 4 /*********************************
 5  * 微信相关工具类
  *********************************
*/ 9 class wechat_util{ 10 const WC_APPID = ''; //微信公众号身份的唯一标识。审核通过后,在微信发送的邮件中查看 11 const WC_APP_SECRET = '';//JSAPI接口中获取openid,审核后在公众平台开启开发模式后可查看 12 /** 13 * 获取用户的code 14 */ 15 public function getUserCodeOp() 16 { 17 $redirect_uri = ''; //回调地址,自行设置为自己网站地址和请求参数 18 $state = 'yarkool'; 19 $scope = 'snsapi_base'; 20 //不弹出授权页面 21 $get_code_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' .self::WC_APPID . '&redirect_uri=' . urlencode($redirect_uri) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect'; 22 header("Location:" . $get_code_url); 23 } 24 //获取用户信息 25 public function getUserCodeCallbackOp() 26 { 27 $code = $_GET["code"]; 28 $get_base_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . self::WC_APPID . '&secret=' . self::WC_APP_SECRET; 29 $base_token = $this->curl_request($get_base_token_url); 30 $access_token = $base_token['access_token']; 31 //通过网页授权获取用户openid 32 $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . self::WC_APPID . '&secret=' . self::WC_APP_SECRET . '&code=' . $code . '&grant_type=authorization_code'; 33 $token_obj = $this->curl_request($get_token_url); 34 //根据openid和基础支持的access_token查询用户信息 35 $openid = $token_obj['openid']; 36 $get_user_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid&openid=' . $openid . '&lang'; 37 $user_obj = $this->curl_request($get_user_url); 38 39 //可对用户信息做处理,如存到数据库 40 if ($user_obj['openid']) { 41 $headurl = $user_obj['headimgurl']; //用户头像地址 42 $nickname = $user_obj['nickname'];//用户昵称 43 44 } 45 //获取到信息后自行操作 46 $index_url = ""; 47 header("Location:" . $index_url); 48 49 } 50 /** 51 * curl请求 52 */ 53 private function curl_request($url) 54 { 55 $ch = curl_init(); 56 //设置超时 57 curl_setopt($ch, CURLOPT_TIMEOUT, 30); 58 curl_setopt($ch, CURLOPT_URL, $url); 59 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 60 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 61 curl_setopt($ch, CURLOPT_HEADER, FALSE); 62 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 63 //运行curl,结果以jason形式返回 64 $res = curl_exec($ch); 65 curl_close($ch); 66 $json_obj = json_decode($res, true); 67 return $json_obj; 68 } 69 } 70 71 ?>

 

posted @ 2016-10-20 19:56  后土·K  阅读(260)  评论(0编辑  收藏  举报