微信登录授权,适合H5页面使用
欢迎一起讨论,使用ci半年,获益良多。希望一起进步,qq 1113288996weixin.php<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Weixin
{
private $appId;
private $appSecret;
function __construct()
{
$this->appId = trim('');
$this->appSecret = trim('');
}
function redirect_url($redirect)
{
/*授权页面*/
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appId&redirect_uri=$redirect&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
return $url;
}
/* 通过code换取access_token*/
function access_token($code)
{
/*获取到的code换取access_token和openid*/
$post_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appId&secret=$this->appSecret&code=$code&grant_type=authorization_code";
$return = $this->postdata($post_url);
$access_token = $return['access_token'];
$openid = $return['openid'];
/*获取微信用户数据*/
$get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = json_decode(file_get_contents($get_userinfo));
return $userinfo;
}
function eff($access_token,$openid)
{
/*检测access_token是否正确,errcode=0 为正确*/
$eff_url = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
$get_eff =json_decode(file_get_contents($eff_url));
return $get_eff;
}
function get_subscribe($openid)
{
/*
通过用户openid拉取用户信息中subscribe,0为未关注,1为已关注
*/
$acc_token = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}"));
$acc_token = $acc_token->access_token;
// return $acc_token;
$get_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$acc_token}&openid={$openid}&lang=zh_CN";
$subscribe_obj = json_decode(file_get_contents($get_url));
$subscribe = $this->obj_to_arr($subscribe_obj);
return $subscribe['subscribe'];
}
//通过curl方式提交code换取access_token数据
function postdata($url)
{
header('Content-Type:text/html;charset=utf-8');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
$access = json_decode($output,true);
return $access;
}
/*
这个位置开始是控制器index()传入的微信用户资料处理
*/
function save_session($data)
{
foreach ($data as $key => $value)
{
$_SESSION[$key] = $value;
}
return $_SESSION;
// print_r($_SESSION);exit();
// unset($_SESSION);
}
function obj_to_arr($data)
{
// 进行转换成数组 使用 obj_to_arr方式
$data = is_object($data)?get_object_vars($data):$data;
foreach ($data as $key => $value)
{
$arr[$key] = $value;
}
return $arr;
}
}
Controller页面中需要简单的调用下即可。
示例
--其他controller以后这样调用即可----
function vipIndex()
{
$bid = $this->uri->segment(5);
$openid = $this->session->openid;
$_SESSION['return_url'] =$_SERVER['REQUEST_URI'];
// 如果openid为空,则需要授权后再进入该页面
if(empty($this->session->openid))header('location:'.'http://h5.imchaotan.com/coupon/index.php/Vip/Coupon/instance_game');
$getBusiness = $this->VipModel->GeneralQuery('cou_business',array('bid'=>$bid));
$data = $getBusiness ;
$Jssdk = new Jssdk();
$signPackage = $Jssdk->getSignPackage();
$data['signPackage']= $signPackage;
$this->load->view('/vip/vip.html',$data);
}
--------以下是某一controller必备。-----------
/*
微信授权基本设置
*/
function instance_game()
{
/*进入领取页面,需要先经过授权*/
$redirect_url = 'Vip/Coupon/weixinAccess';
$redirect = urlencode('http://h5.imchaotan.com/coupon/index.php/'.$redirect_url);
$return = $this->weixin->redirect_url($redirect);
// echo $return;exit();
header('location:'.$return);
}
function weixinAccess()
{
/*
检测改微信用户是否存在
$user_arr 获取的是通过get_code返回的微信用户信息,此时的信息是通过微信服务器返回的,不能记录session
$user std_obj模式,转换为数组
$user_exists 扔入model中,检测数据表中是否存在该用户
$redirect 走完流程后,跳转到首页
if语句的作用,是 判断通过model返回数据表的信息,如果为空则把微信用户信息录入到表中,再读取出来,存进session。
else 则数据表已经存在该用户,直接读取,存进session
需要注意的是,使用foreach的原因,是二维数组转一维数组
*/
$user_arr = $this->get_code();
// print_r($user_arr);exit();
$user = $this->weixin->obj_to_arr($user_arr);
//检测头像是否和数据库相同
$user_exists = $this->VipModel->GeneralQuery('cou_user',array('openid'=>$user['openid']));
if($user_exists['headimgurl'] !== $user['headimgurl'] || $user_exists['nickname'] !== $user['nickname'])
{
$this->VipModel->GeneralUpdate('cou_user',array('openid'=>$user['openid']),array('headimgurl'=>$user['headimgurl'],'nickname'=>$user['nickname']));
}
$redirect = 'http://h5.imchaotan.com'.$this->session->return_url;
if(empty($user_exists))
{
//加入自定义的字符进入数组
unset($user['privilege']);
$user_exists['nickname'] = $user['nickname'];
$user_exists['openid'] = $user['openid'];
$user_exists['language'] = $user['language'];
$user_exists['city'] = $user['city'];
$user_exists['country'] = $user['country'];
$user_exists['province'] = $user['province'];
$user_exists['headimgurl'] = $user['headimgurl'];
$user_exists['sex'] = $user['sex'];
$user_exists['fullname'] = $user['nickname'];
$user_exists['telphone'] = '';
$user_exists['login_ip'] = $this->input->ip_address();
$user_exists['last_ip'] = $this->input->ip_address();
$user_exists['groups'] = REGISTER_GROUP_ID;
$user_exists['status'] = 1;
$user_exists['login_time'] = date("Y-m-d");
try {
$insert_id= $this->VipModel->insertOne('cou_user',$user_exists);
$user_exists['uid'] = $insert_id;
} catch (Exception $e) {
echo 'Message: ' .$e->getMessage();
}
}
else{
$user_exists = $user_exists;
}
$this->session->set_userdata($user_exists);
/*如果session中有return_url,就跳转到return_url中*/
if(isset($this->session->return_url))header('location:'.$this->session->return_url);
// header('location:'.$redirect);
}
function get_subscribe($openid)
{
/*
通过subscribe检测该用户是否是否关注公众号
*/
$subscribe = $this->weixin->get_subscribe($openid);
return $subscribe;
}
function get_code()
{
if(isset($_GET['code']))
{
$code = $_GET['code'];
// echo $code;exit();
$user_arr = $this->weixin->access_token($code);
//跳转到用户检测中check_exists()去
return $user_arr;
}else{
//否则检测cookie中是否存在该用户,如果有,则return回首页
echo 'error';
}
}
access_token 有7200s的有效时间有次数限制 你每次都刷新了access_token
页:
[1]