微信web使用者授權
阿新 • • 發佈:2018-11-09
以thinkphp3.2為例
步驟:1.使用者授權->2.獲得CODE->3.根據CODE獲取openid->4.根據openid獲取使用者資訊
1.使用者初次訪問頁面
class IndexController extends Controller { public function index(){ header('Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=你自己的APPID&redirect_uri=授權後跳轉的頁面地址(我這裡跳到pro這個控制器中)&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'); } }
2.獲取資訊
<?php namespace Home\Controller; use Think\Controller; class ProController extends Controller { public function index(){ //2.通過授權獲取code if(isset($_GET['code'])){ $code = $_GET['code']; }else{ $this->redirect('index/index'); } //3.根據CODE獲得access_token和openid $arccess_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".C('appid')."&secret=".C('APPSECRET')."&code=".$code."&grant_type=authorization_code"; $arccess_token_json = file_get_contents($arccess_token_url); $arccess_token_array = json_decode($arccess_token_json, true); $access_token = $arccess_token_array['access_token']; $openid = $arccess_token_array['openid']; if(!$openid){ $this->redirect('index/index'); } //4.根據access_token和openid獲取使用者資訊 $userinfo_url = "https://api.weixin.qq.com/sns/userinfo? access_token=".$access_token."&openid=".$openid."&lang=zh_CN"; $userinfo_json = file_get_contents($userinfo_url); $userinfo_array = json_decode($userinfo_json, true); $data['openid'] = $userinfo_array['openid']; $data['sex'] = $userinfo_array['sex']; $data['nickname'] = $userinfo_array['nickname']; $data['province'] = $userinfo_array['province']; $data['city'] = $userinfo_array['city']; $data['headimgurl'] = $userinfo_array['headimgurl']; //5.資料傳輸到前臺 $this->userinfo = $data; $this->display(); } }