js 微信授权登陆实现(转)

0311lc.com说:

追加:代码实现

完全使用前台实现 代码:点击跳转
完全使用后台实现 代码:点击跳转

前言
为了更好的用户体验,微信登陆已近必不可少!

一、注册
这里不多说了,网址:https://open.weixin.qq.com/ (微信开放平台)
但是我还是要吐槽一下,真的是无语,一会一个微信开放平台,一会一个微信公众平台,两个账号还不能通用,不能通用不能通用把,两个平台的邮箱注册账号还不能一样!真亏我以前注册了2个邮箱账号!

二、主要流程
官方文档:点击我跳转

主要流程
————————————————

2.1 引入样式以及相关js代码

配置显示微信二维码的div

<div id="weixin"></div>

引入js

http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js

在需要使用微信登录的地方实例以下JS对象:

var obj = new WxLogin({
id: "weixin",
appid: "你自己申请的小程序会有的",
scope: "snsapi_login",
redirect_uri: "回调地址"    // 扫描二维码就会使用该接口并在该接口后增添参数  ?code=011LSrB80R1abG1k6WD80wk5B80LSnBj&state=undefined
});

例子: 如果redirect_uri: “http;//www.guokangjie.cn/weixinlogin” 则用户在扫描二维码时会跳转路径如下 http://www.guokangjie.cn/weixinlogin?code=011LSrB80R1abG1k6WD80wk5B80LSrBj&state=undefined
其中的code 是非常重要的!!!是下一步的关键

2.2、调用接口

2.2.1、通过code获取access_token和openid (使用刚才的code)

https://api.weixin.qq.com/sns/oauth2/access_token?appid=你自己的APPID&secret=你的AppSecret&code=刚刚获取的code&grant_type=authorization_code

会返回json串如下:

{
    "access_token":"18_louWUfx1BmTXOp5HGBoDu75hDDkXP9xwjPlJtG-nrywW5hf0d4-YWRyUZA47LHZ0DR8SgwDEA2gEuWX2X-v1-w",
    "expires_in":7200,
    "refresh_token":"18_px7yKjfWiikiBzNujc8xNG_EbhgXKjWD4F3iItAKl46Amo7sAlvtkPY3qHCYqKm1762FfJSK-0IeD0hjO0R9Ew",
    "openid":"oypcC1tzpTQM3z8oXWgbrWX4dgqQ",
    "scope":"snsapi_login",
    "unionid":"o6JuL1l80GspPSrdODDaSUIRbwGI"
}

其中的access_token和openid是下一步的关键

2.2.2、通过access_token获取该微信用户信息

调用微信获取用户信息接口(使用sccess_token)

http请求方式: GET https://api.weixin.qq.com/sns/userinfo?access_token=前面你获取的ACCESS_TOKEN&openid=前面你获取的openid

返回用户信息json串

{
    "openid":"oypcC1tzgTQM3z8oXWgbrWX4dgqQ",
    "nickname":"城墙",  //微信昵称
    "sex":1,            //性别
    "language":"zh_CN", //语言
    "city":"Suzhou",    //所在城市
    "province":"Anhui",  //所在省份
    "country":"CN",      //所在国家
    "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/fhOw1icVrUT15pIvqV4C1eUic1OAXOgWRh9ZJUyiaIA5qLKgVTsGa6V9dS3nup7SCb6accqLHYq9T5TtLqqSOsOWA/132", //微信头像
    "privilege":[   //用户特权信息,json数组,如微信沃卡用户为(chinaunicom)
    ],
    "unionid":"o6JuL1l80GskPSrdODDaSUIRowGI"  //用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。
}

 

3、总结与吐槽
过程如下:
页面生成二维码 ——》用户扫描确认 ——》生成带有code的url ——》使用code获取 access_token和openid ——》使用acess_token和openid获取该微信用户信息 ——》获得用户json串!!

是真的麻烦,直接一个url捎过去,回来一个用户信息不就ok了吗!!哈哈哈!!开个玩笑,毕竟这类东西还是很重要毕竟是用户的个人隐私,安全点比较好!!

大家在测试的时候要注意要快,有过期时间!!!!另外详细的文档官网以给!!

 


PHP实现微信网页授权登陆

0311lc.com说:

官方开发文档地址

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN;

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);
    }
}

 


php 微信授权原理

0311lc.com说:
  1. 微信授权有什么作用,微信授权我们需要使用微信开发的什么接口。微信授权,对于开发来说,他是与微信用户系统对接的唯一途径。为什么说是唯一途径,因为,只有通过微信授权,才能拿到用户在微信平台上的信息(头像,昵称,地址),例如:在进入微信商城的时候,弹出确认“xxx商城授权”。点击确定,就是该电商平台到微信去授权获取用户的信息。
  2. 微信授权,获取用户信息的接口(确保微信公众账号拥有授权作用域(scope参数)的权限的前提下引导用户去授权页面)
    • 静默授权  静默授权不需要用户确认,只需要用户访问某个网页,属于嵌套在普通网页里的授权形式,但是只能获取到用户的唯一标示openid,无法获取用户的个人信息
    • 网页授权 网页授权是一种通过用户确认,来获取用户的openid、个人信息、关注信息等的接口返回形式
  3. 在开发之前,我们要确保我们的服务号,在接口权限处,已经获得了网页授权权限

    此外,我们还需要有个备案通过的域名,比如”www.myname.com”,并确保你的域名可以访问到你的服务器,于是在公众号设置那里把域名配置好,把校验文件”MP_verify_lS1VtPAOta6l5jrQ.txt”放置到你的网站的根目录,于是提交成功,变成如下设置

    接下来,我们要去建立一个php文件”getinfo.php”,内容如下:

    <?php
    $appid = 'wxxxxa95xxx0xxxxx';
     
    #你的公众号appid
     
    $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=http%3A%2F%2Fwww.xingchuangpinzhi.com%2FgetinfoDetail.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
     
    #redirect_uri改为你的网页授权域名和刚刚跳转到的显示页面,比如我的是getinfoDetail.php
     
    header('location:'.$url);
    ?>
    

    建立一个php文件”getinfoDetail.php”,内容如下:

    <?php
    header("Access-Control-Allow-Origin:*"); #设置跨域
    header("Content-Type: application/json; charset=UTF-8"); 
    //获取存放在cookies里面的token
    $code = $_GET['code'];
    $state = $_GET['state'];
    //换成自己的接口信息
    $appid = 'wxxxxxxxxxxxxxx';#你的公众号appid
    $appsecret = '7xxfxxxxxxxxxxxxxxxxx';#你的公众号appsecret
    if (empty($code)) $this->error('授权失败');
    $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
    $token = json_decode(file_get_contents($token_url));
    if (isset($token->errcode)) {
        echo '<h1>错误:</h1>'.$token->errcode;
        echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
        exit;
    }
    $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
    //转成对象
    $access_token = json_decode(file_get_contents($access_token_url));
    if (isset($access_token->errcode)) {
        echo '<h1>错误:</h1>'.$access_token->errcode;
        echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
        exit;
    }
    $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
    //转成对象
    $user_info = json_decode(file_get_contents($user_info_url));
    if (isset($user_info->errcode)) {
        echo '<h1>错误:</h1>'.$user_info->errcode;
        echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
        exit;
    }
     
    $rs =  json_decode(json_encode($user_info),true);//返回的json数组转换成array数组
    $openid= $rs["openid"];
    $nickname=$rs["nickname"];
    $sex=$rs["sex"];
    $language=$rs["language"];
    $city=$rs["city"];
    $province=$rs["province"];
    $country=$rs["country"];
    $headuri=$rs["headimgurl"];
    //打印用户信息
    echo $openid;
    echo $nickname;
    echo $sex;
    echo $language;
    echo $city;
    echo $province;
    echo $nickname;
    echo $headuri;
    echo $country;
    ?>
    

    完成后访问url:”http://www.我的域名.com/getinfo.php”,显示

    点击获取,打印出授权用户信息: