PHP实现微信网页授权登陆

官方文档地址
1.识别浏览器,普通浏览器跳到登陆页面;微信打开的话,发起微信网页授权登陆,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;

2.通过code参数加上AppID和AppSecret等,通过API换取access_token;

3.通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。

<?php

namespace Home\Controller;

use Think\Controller;

class CommonController extends Controller {

    /*

    * 自动执行

    */

    public function _initialize(){

        //判断是否在微信打开

        $ua = $_SERVER['HTTP_USER_AGENT'];

        //MicroMessenger 是android/iphone版微信所带的

        //Windows Phone 是winphone版微信带的  (这个标识会误伤winphone普通浏览器的访问)

        if(strpos($ua, 'MicroMessenger') == false && strpos($ua, 'Windows Phone') == false){

            //普通浏览器

            if(!$_SESSION['username']) {

                header('Location:xxx');

            }

        }else{  

            //微信浏览器

            $users = M('User');

            $appid = 'xxx';

            $secret = 'xxx';

            if(!$_SESSION['username']) {

                //微信网页授权

                $redirect_uri = urlencode ('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

                $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";

                header("Location:".$url);

                $code = $_GET["code"];

 

                //第一步:取得openid

                $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";

                $oauth2 = $this->getJson($oauth2Url);

                //第二步:根据全局access_token和openid查询用户信息

                $access_token = $oauth2["access_token"];

                $openid = $oauth2['openid'];

                $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";

                $userinfo = $this->getJson($get_user_info_url);

                //save用户信息

                if($userinfo['openid']){

                    $username = $userinfo['openid'];

                    $nickname = $userinfo['nickname'];

                    $headimg = $userinfo['headimgurl'];

                    $province = $userinfo['province'];

                    $city = $userinfo['city'];

                    $sex = $userinfo['sex'];

                    $user = $users->where(array('username' => $username))->find();

                    if ($user) {

                        $users->where(array('username' => $username))->save(array('nickname' => $nickname, 'avatar' => $headimg, 'lasttime' => time()));

                    }else{

                        $users->add(array('username' => $username, 'nickname' => $nickname, 'avatar' => $headimg, 'province' => $province, 'city' => $city, 'gender' => $sex, 'regtime' => time(), 'lasttime' => time()));

                        // $data = array('username' => $username, 'nickname' => $nickname, 'avatar' => $headimg, 'province' => $province, 'city' => $city, 'gender' => $sex, 'regtime' => time(), 'lasttime' => time());

                    }

                    $_SESSION['username'] = $username;

                    if($user['tel'] == NULL){

                        //如果用户手机号为空的话跳转到绑定手机号页面

                        header('Location:xxx'); 

                    }

                }                

            }else{

                $user = D('User')->getUserInfo();  //getUserInfo()是model根据session('username')获取用户数据的方法

                if($user['tel'] == NULL){

                    header('Location:xxx');

                }

            }

 

            //获取接口调用凭证access_token

            $accessurl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;

            $access_token = S('access_token');

            if(!$access_token){

                $access = $this->getJson($accessurl);

                if(!empty($access['access_token'])){

                    S('access_token',$access['access_token'],$access['expires_in']);

                }

            }

            //分享

            /*$share = new WechatShare($appid, $_SESSION['username']);

            $this->shareScript = $share->getSgin($access_token);

            $this->assign('shareScript', $this->shareScript);

            $this->assign('sharewechaid', $_SESSION['username']);

            if($_GET['sharewechaid']){

                $this->assign('getsharewechaid', $_GET['sharewechaid']);

            }*/

        }

     

}

 

    public function getJson($url){

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);

        curl_close($ch);

        return json_decode($output, true);

    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP微信网页授权是指开发者使用微信公众平台提供的接口,在PHP开发的网站中实现用户通过微信进行身份验证和登录的功能。这个过程通常包含以下几个步骤: 1. **获取授权URL**:首先,你需要在微信公众平台上注册并配置应用,获取到AppID、AppSecret。然后调用微信的`https://open.weixin.qq.com/connect/oauth2/authorize`接口,传入相应的参数(如redirect_uri、response_type等)生成一个授权页面链接。 ```php $authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" . "appid=" . $appID . "&redirect_uri=" . urlencode($redirectUri) . "&response_type=code" . "&scope=snsapi_userinfo" // 请求用户基础信息权限 . "&state=your_state" // 自定义状态值防止CSRF攻击 . "#wechat_redirect"; ``` 2. **用户点击授权**:用户在浏览器中打开这个链接后,会跳转到微信客户端,提示用户确认授权。如果用户同意,微信服务器会重定向回指定的redirect_uri,并附带access_token作为查询参数。 3. **验证授权码**:用户回到你的网站后,你需要从请求中解析出access_code,然后用它换取access_token。这通常涉及到HTTP POST请求到`https://api.weixin.qq.com/sns/oauth2/access_token`接口,提供AppID、AppSecret以及刚才接收到的code。 4. **刷新access_token**:为了长期有效使用,可能需要定期或在需要时刷新access_token。同样通过POST请求到`https://api.weixin.qq.com/sns/oauth2/token`,但这次需要使用refresh_token。 5. **获取用户信息**:有了access_token,你可以调用`https://api.weixin.qq.com/sns/userinfo`接口,传入access_token和openid(从code到token的过程中会得到),以获取用户的详细信息。 6. **存储用户信息**:最后,将用户的微信信息保存到数据库,以便后续操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值