tp3.2 微信授权登录

    今天弄了弄微信网页授权登录,终于鼓捣出来了,把经验写下了,分享一下,省的大家走进坑。

1.第一步,公众号域名设置,以及白名单等设置,注意,白名单,没有你的IP地址,获取不到access这个文档都有,自己看下就OK

2.第二步,建一个数据库来存储用户的openid,昵称等信息

3.写代码,话不多说,直接上代码,tp3.2和5.0大同小异,文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

4.错误检查,直接去微信开发工具测试,或者直接var_dump();直接在微信中打开链接,错误信息全显示出来!

class CheckController extends Controller {
    public function index(){
        $opid = session('openId');
        if(empty($opid)){
            $appId = '你的appid';
            $uri = urlencode('http://www.xd666.com/Check/back'); //授权成功返回地址
            //下面$url请求授权登录地址,此处为静默授权,scope可改成snsapi_userinfo,注意此URL不能换行,静默授权只能获取_token 和 openId
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.$uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
            header('Location:'.$url);
        }

    }
    public function back(){
        $appId = '你的appid';
        $appSecret = '你的appsecret'; //appsecret,微信公众号基本设置里面找
        $code = $_GET['code']; //接收上面url返回code,5分钟有效期,code直接$_GET['code']接收,vdump($code);die();

        //通过下面url获取access_t和 openid,具体看代码
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code';
        $data = json_decode($this->curl($url));//调取function.php封装的CURL函数
        //存取session
        session('openId',$data->openid);
        $arr = array(
            'access_token'=>$data->access_token,
            'openid' =>$data->openid,
            'createtime'=> date('Y-m-d H:i:s',time())
        );

        //添加到数据库
        $wx = M('wxinfo');
        $list = M('wxinfo')->where("openid='".$data->openid."'")->find();
        if(!empty($list)){
            $wx->access_token = $data->access_token;
            $wx->openid = $data->openid;
            $wx->updatetime = date("Y-m-d H:i;s",time());
            $wx->where("openid='".$data->openid."'")->save();
        }else{
            $wx->add($arr);
        }

        header('Location:http://www.xd666.com/Tui');


    }

    public function curl($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }


以上,基本的微信登录就完成了,其他的就看自己的需求啦,根据文档就OK啦!注意,有效期时间,比如code等。有不合适的,或者错误,请指出。+群:372319250,寻求其他帮助!




猜你喜欢

转载自blog.csdn.net/qq_38997379/article/details/79993552