微信公众平台OAuth2.0授权登陆(PHP)

文件1:index.php

//换成自己的接口信息

$appid = 'XXXXX';

header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=127.0.0.1/oauth.php&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect');

参数说明:

参数

是否必须

说明

appid公众号的唯一标识
redirect_uri授权后重定向的回调链接地址,请使用urlencode对链接进行处理
response_type返回类型,请填写code
scope应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息
state重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值
#wechat_redirect无论直接打开还是做页面302重定向时候,必须带此参数

 


文件二:oauth.php

 代码如下复制代码
<?php
$code = $_GET['code'];
$state = $_GET['state'];
//换成自己的接口信息
$appid = 'XXXXX';
$appsecret = 'XXXXX';
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;
}
//打印用户信息
echo '<pre>';
print_r($user_info);
echo '</pre>';
?>

 

参数

描述

openid用户的唯一标识
nickname用户昵称
sex用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
province用户个人资料填写的省份
city普通用户个人资料填写的城市
country国家,如中国为CN
headimgurl用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
privilege用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
unionid只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)

 

----------------------------个人封装----------------------

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Wap_oauth extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->load->library('wap_admin');
    }
    public function accredit()
    {
        $call_url = "http://www.ivymei.com/wxapi/index.php?/Wap_oauth/url_shift/"; 
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->config->item('appid').'&redirect_uri='.urlencode($call_url).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header("Location:".$url);  
    }

    public function url_shift()
    {
        $str = $_SERVER['REQUEST_URI'];
        $temp = explode('&', $str);
        $code = substr($temp[1], 5);
        $state = substr($temp[2], 6);
        // $call_url = 'http://m.ivymei.com/index.php?/Wap_oauth/get_token/&code='.$code.'&state='.$state; 
        $call_url = 'http://m.ivymei.com/index.php?/Wap_oauth/get_token/'.$code.'/'.$state; 
        header('Location:'.$call_url);
    }


    public function get_token($code = '', $state = '')
    {   
        //公众号信息
        $appid = $this->config->item('appid');
        $appsecret = $this->config->item('appsecret');
        if (empty($code)){ 
            die(json_encode(array('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)) {
            die(json_encode(array('error' => $token->errcode, 'msg' => $token->errmsg)));
        }

        //appid 和 更新token 获取 access_token 和 openid 的组合URL
        $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)) {
            die(json_encode(array('error' => $access_token->errcode, 'msg' => $access_token->errmsg)));
        }

        //access_token 和 openid 获取用户信息的组合URL
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';

        //转成对象
        // $userinfo = get_object_vars(json_decode(file_get_contents($user_info_url)));
        $userinfo = json_decode(file_get_contents($user_info_url));
        
        if (isset($user_info->errcode)) {
            die(json_encode(array('error' => $user_info->errcode, 'msg' => $user_info->errmsg)));
        }
        //转成数组
        $user_info = is_object($userinfo) ? get_object_vars($userinfo) :  $userinfo;
        echo '<pre>';

        print_r($user_info);

        echo '</pre>';

//根据openid 查找是否有注册
        $sql = "SELECT id,nick_name,avatar,sex,province,city,mobile FROM im_member WHERE openid = '".$user_info['openid']."'";
        $combo_userinfo = $this->db->query($sql);
        $userinfoFind = $combo_userinfo->result_array();
        if(empty($userinfoFind)){
            $_SESSION['wx_landing_info'] = $user_info;
            $this->load->view('message.html');
        }else{
            //将微信信息跟用户信息绑定
            $add_data = array();
            //昵称
            if(empty($userinfoFind[0]['nick_name']))
                $data['nick_name'] = $user_info['nickname'];
            //性别
            if(empty($userinfoFind[0]['sex']))
                $add_data['sex'] = $user_info['sex'];
            //省
            if(empty($userinfoFind[0]['province']))
                $add_data['province'] = $user_info['province'];
            //市
            if(empty($userinfoFind[0]['city']))
                $add_data['city'] = $user_info['city'];

            if(!empty($add_data)){
                $this->db->where('id',$userinfoFind[0]['id']); 
                $resUserinfo = $this->db->update('member',$add_data);
            }

            $_SESSION['wap_user']['mobile'] = $userinfoFind[0]['mobile'];
            $_SESSION['wap_user']['id'] = $userinfoFind[0]['id'];
            $_SESSION['wap_user']['name'] = $userinfoFind[0]['name'];

            //跳转首页  默认登录了
            header("Location: ".$this->config->item('base_url'));
        }

    }

}

上面之所以转了一次跳转,是因为第一个域名m.ivymei.com不是授权域名,所以只能先跳到授权域名下面,在调转回来,如果是同一个域名,即可减少url_shift这一步。

授权域名设置:登录微信公众平台---接口权限---找到网页账号--网页授权获取用户基本信息旁边有一个修改,里面添授权域名。

 

转载于:https://my.oschina.net/u/2443771/blog/747478

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值