文档:
微信开放平台
需求: android 需要微信登录。
有两种方式: 一是移动应用; 而是 网站应用;
移动应用需要;所在的安卓系统上安装微信客户端; 不想安装微信客户端,所以不用这种方式。
采用网站应用 方式 步骤
1. 目的 获取code ;
php 后端 拼装好链接, 浏览器打开这个链接如:
2. 上一步出来二维码,用户扫码同意后会跳转到rediret_uri 指定的链接 并执行这个请求
这样PHP 就能获取code了;
curl 请求
"https://api.weixin.qq.com/sns/oauth2/access_token?code=sdfinenberw"...........;
返回得到 access_token 和 openid
3. 用 access_token , openid 来获取微信用户信息
curl请求
"https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
注意事项: redirect_uri 只能指定一个 b.herogames.cn 域名不能同时再指定为另一个如 fb.herogames.cn; 为了不影响线上微信授权运行,方便测试,或者供多个项目使用同一个 授权登录如:fbi-test.hero.cn fb-test.hero.cn jd-test.hero.cn .可以采用方法如下让 b.hero.cn 做进一步分发(重定向带上code)
public function common(){
$code = $this->input->get("code",true);
$flag = $this->input->get("flag",true);
$key = $this->input->get("key",true);
//$query = $_SERVER[""];
if($flag=="development"){ //测试
$url = "http://b-test.hero.cn/login/getOpenid?code={$code}&flag={$flag}";
}elseif ($flag=="production"){
$url = base_url()."/login/getOpenid?code={$code}&flag={$flag}";
}elseif($flag == 'funbox_development'){
$url = "http://fbi-test.hero.cn/wx/wxInfo?code={$code}&flag={$flag}&key={$key}";
}elseif($flag == 'funbox_production'){
$url = "http://fbi.hero.cn/wx/wxInfo?code={$code}&flag={$flag}&key={$key}";
}else{
echo "参数不正确";
exit;
}
header("Location:$url");
}
注意事项二: 改成接口 给android怎么做?
1. 给链接 让android使用内置浏览器打开是一个接口
2. 上面的获取access_token,openid; 获取微信用户信息; 都是在内置浏览器,浏览器重定向发的请求完成了。android怎么获取成果(微信用户信息)呢?
方案一: 后端在获取用户信息后存在一个地方(redis ,或 memcache 或mysql中)为了安全设置合适的有效期,信息和唯一标示关联;再给android 提供一个接口isLogin去获取信息,参数是什么呢?可以是设备唯一标示;。
这个接口 android可以从打开链接后就以一定频率调用isLogin, 获取到信息后停止。后端为了安全可以及时清除这个信息。
/**
* 是否登录
*/
public function isLogin()
{
$this->load->library('session');
$this->load->driver('cache');
$key = isset($this->_requestParams['key'])? $this->_requestParams['key'] : null;
if(empty($key)){
$this->response(4002,'参数错误');
}
$redisKey = "funbox_".$key."_".ENVIRONMENT;
$sessionData = $this->cache->redis->get($redisKey);
//$this->cache->redis->del($redisKey);
if(empty($sessionData)){
$this->response( 200,'');
}
$sessionData = json_decode($sessionData,true);
//设置session
$this->session->set_userdata(array(
'user_id' => $sessionData['user_id'],
'business_id'=>$sessionData['business_id'],
'name'=>$sessionData['name'],
'mobile'=>$sessionData['mobile'],
'avatar'=> $sessionData['avatar'],
// 'sex'=>$res['data']['sex'],
));
$token = session_id();
$this->response(200,'',array(
'user_id' => $sessionData['user_id'],
'business_id'=>$sessionData['business_id'],
'name'=>$sessionData['name'],
'mobile'=>$sessionData['mobile'],
'avatar'=> $sessionData['avatar'],
// 'sex'=>$res['data']['sex'],
'funbox_session'=>$token
));
}