點擊微信公衆號菜單按鈕 跳轉網頁授權登錄

流程:

用戶點擊菜單按鈕
—–> 發送頁面授權請求到微信後臺
—–> 得到 code 發送到 我們服務器後臺的url
—–> 將 code 參數發送到微信後臺獲取用戶的openid返回服務器上的頁面(也可以直接獲取用戶頭像等基本信息,需用戶點擊同意授權)
詳情參照官方文檔:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

//填寫獲取code的接口的路徑
這裏寫圖片描述

//添加路由
這裏寫圖片描述

class WapWechatController extends Controller
{
public function http_curl($url){

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output,true);
}

public function getcode(){

    //1.用戶同意授權,獲取code
    $appid="你的appid";
    $redirect_uri=urlencode("http://www.mrygtv.com/wx/getuserinfo");
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    //跳轉到回調地址的方法裏
    header('location:'.$url);
}

//攜帶code參數跳到userinfo方法
http://www.mrygtv.com/wx/getuserinfo?code=sbnJJMJMX&state=STATE
public function getuserinfo(Request $request){

//2.通過code換取網頁授權access_token,openid

    //獲取code
    $code= $_GET['code'];
    $appid="你的appid";
    $secret=你的secret";
    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";

   $res=$this->http_curl($url,'get');
   $access_token=$res['access_token'];
   $openid=$res['openid'];

    //3.拉取用戶信息
    $url2="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";

    $res2=$this->http_curl($url2,'get');

    //將用戶信息存入數據庫(舉例)
    $insert = DB::table('user_auths')->insert(['openid' => $res2['openid'],'nickname' => $res2['nickname']]);

    //跳轉到你要跳轉的頁面
   header('location:'.'http://www.mrygtv.com');
}

}

方法2:
將菜單 view 按鈕的 url直接寫爲:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=“+yourAppid+”&redirect_uri=”+你要跳轉的url+”&response_type=code&scope=snsapi_base&state=1#wechat_redirect”
相當於直接發送頁面授權請求到微信後臺,將url裏的code發送給後臺,直接請求第二個接口獲取openid,token接口即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章