微信公众号网页授权,获取用户信息以及openid
这几天做项目,想通过公众号的appid获取用户的openid就,然后在网上查资料,问朋友,最后找到了方法,就是这个网页授权。
起初一直很蒙,这个怎么弄,又是需要code,又是需要允许授权的,我怎么获取这个code,在哪里出发这个网页授权的事件呢,最后弄明白了,其实很简单。
首先我们先写一个html网页,比如这样的:
点击·确认授权·,执行下面php代码里面的request_wechat1
方法就ok了。
对,没错,这就完成了,简单吗,是不是很简单,只需要一步
PHP代码:
public function request_wechat1(){$app_id = '微信公众号appid';// 回调地址$redirect_url = '/seafood/public/index/base/get_open_id1';$url = "https://open./connect/oauth2/authorize?appid=" . $app_id . "&redirect_uri=" . $redirect_url . "&response_type=code&scope=snsapi_base&state=0#wechat_redirect";header("Location:{$url}");die;}/*** 微信回调地址,以获取openid*/public function get_open_id1(){$code = Request::instance()->param('code');$app_id = '微信公众号appid';$app_secret = '微信公众号app_secret';//第一步:取全局access_token$url = "https://api./cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$app_secret}";$token = $this->get_json($url);//第二步:取得openid$oauth2Url = "https://api./sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code";$oauth2 = $this->get_json($oauth2Url);//第三步:根据全局access_token和openid查询用户信息$access_token = $token["access_token"];$openid = $oauth2['openid'];$get_user_info_url = "https://api./cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";$userinfo = $this->get_json($get_user_info_url);print_r($userinfo);}protected function get_json($url){$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$output = curl_exec($ch);curl_close($ch);return json_decode($output, true);}