微信授权登陆
第一步:用户同意授权,获取code
在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
第二步:通过code换取网页授权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
第四步:拉取用户信息(需scope为 snsapi_userinfo)
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
具体代码实现
public function actionGetUserInfo(){
//第一步:用户同意授权,获取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);
}
}
注意点
需要在微信后台填写 授权回调页面域名: 即上面的$redirect_url,$redirect_url需要urlencode,才能正常使用
Paste_Image.png自定义分享接口
代码采用的是yii2框架作为开发的基础框架
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));
}
网友评论