微信授權(quán)登陸
第一步:用戶(hù)同意授權(quán)骤视,獲取code
在確保微信公眾賬號(hào)擁有授權(quán)作用域(scope參數(shù))的權(quán)限的前提下(服務(wù)號(hào)獲得高級(jí)接口后孤个,默認(rèn)擁有scope參數(shù)中的snsapi_base和snsapi_userinfo),引導(dǎo)關(guān)注者打開(kāi)如下頁(yè)面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
第二步:通過(guò)code換取網(wǎng)頁(yè)授權(quán)access_token
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
第三步:刷新access_token(如果需要)
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
第四步:拉取用戶(hù)信息(需scope為 snsapi_userinfo)
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
具體代碼實(shí)現(xiàn)
public function actionGetUserInfo(){
//第一步:用戶(hù)同意授權(quán)酵幕,獲取code
$appid = "wx9c044f";
$redirect_url = urlencode("http://admin.cheesebeer.net/index.php?r=share/get-user");
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=".time()."#wechat_redirect";
header("location:".$url);
}
public function actionGetUser(){
$code = $_GET['code'];
$appid = "wx9c044f981";
$app_secret = "3fd73bb4cd76af92528e3";
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$app_secret."&code=".$code."&grant_type=authorization_code";
$res = json_decode($this->_http_curl_get($url));
if(isset($res->access_token)){
$get_user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res->access_token."&openid=".$res->openid."&lang=zh_CN";
$user_info = json_decode($this->_http_curl_get($get_user_url));
$target_url = "http://movietip1.duapp.com/index.html?headimgurl=".$user_info->headimgurl."&nickname=".$user_info->nickname;
header("location:".$target_url);
}
}
注意點(diǎn)
需要在微信后臺(tái)填寫(xiě) 授權(quán)回調(diào)頁(yè)面域名: 即上面的$redirect_url芬迄,$redirect_url需要urlencode,才能正常使用
Paste_Image.png
自定義分享接口
代碼采用的是yii2框架作為開(kāi)發(fā)的基礎(chǔ)框架
public function actionShare()
{
$app_id = Yii::$app->request->get('app_id','wx3639f3e999c3');
$app_secret = Yii::$app->request->get('app_secret','5e0d10f0f9b8c593e48f5dec');
$url = Yii::$app->request->get('url','http://marqian.duapp.com/');
$options = [
"app_id"=>$app_id,
"secret"=>$app_secret,
];
$wechat = new Application($options);
$wechat->js->setUrl($url);
return ($wechat->js->config(['onMenuShareTimeline','onMenuShareAppMessage'],true));
}