文檔:
微信開放平臺
需求: 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
));
}