微信授权登陆(php开发完整示例)

实现逻辑

用户访问需要授权登陆的公众号,用是否存在openid判断登录状态。不存在,重定向到微信服务器。
微信服务器返回code,用code换取openid和access_token。
再用openid和access_token换取用户信息。

代码逻辑

判断openid,重定向到微信服务器

if (!$this->isAuth()) {
	$this->current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	Cookie::set('target_url',$this->current_url);
	$userAuth = new Weixin();
	$userAuth->getCode();
}
//判断登录状态
function isAuth(){
     $openid = Cookie::get('openid');
     if(!empty($openid)){
         $this->openid=$openid;
         return true;
     }else{
         return false;
     }
 }
 //获取code
 public function getCode()
 {
     $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . url('index/Weixin/auth');
     $jummpUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . urlencode($redirect_uri) . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
     $this->redirect($jummpUrl);
 }

接收微信服务器返回的code,并换取openid和access_token

 //微信登陆授权
public function auth()
{
	$code = $this->request->param('code');
	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appSecret . "&code=" . $code . "&grant_type=authorization_code";
	$json = json_decode(file_get_contents($url), true);
	$userInfo = $this->getUserInfo($json);
}

用openid和access_token换取用户微信信息

//换取用户微信信息
function getUserInfo($json){
	$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $json['access_token'] . "&openid=" . $json['openid'] . "&lang=zh_CN";
	$data = json_decode(file_get_contents($url), true);
	return $data;
}

结语

其实授权就是几个接口互相请求。比较困难的是调试,因为你无法打印微信服务器返给你的信息,可以自己写日志来进行调试。

附上连接

微信官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值