1 , 安卓應用, 微信登陸,流程圖
2, php端代碼
$appid = ""; //開發平臺申請
$appsecret = ""; //開發平臺申請
$code = $_GET['code']; //安卓端提供用戶同意登入後的code
//認證
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code ."&grant_type=authorization_code";
//調用微信api
$http = new \Common\Util\ddhttp;
$rs = $http -> get($url);
if(!$rs)$this -> error('獲取OPENID失敗');
$rt = json_decode($rs, 1);
if($rt['errcode'])$this -> error('授權失敗:'.$rt['errmsg']);
// 拉取用戶信息
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$rt['access_token']."&openid=".$rt['openid']."&lang=zh_CN ";
$wechat_info = $http -> get($url);
if(!$wechat_info)$this -> error('獲取用戶資料失敗:CURL '.$http -> errmsg);
$wechat_info = json_decode($wechat_info, 1);
if($wechat_info['errcode']){
$this -> error("獲取用戶資料失敗".$wechat_info['errmsg']);
}
$user_info = array(
"headimg"=>$wechat_info['headimgurl'], //頭像
"nickname"=>$wechat_info['nickname'], //暱稱
"sex"=>$wechat_info['sex'], //性別
"openid"=>$wechat_info['openid'], //app唯一
"unionid"=>$wechat_info['unionid'] //微信內部唯一,小程序, 公衆號, web, 移動應用都是一致的
);
工具類
<?php
namespace Common\Util;
/**
* http操作類,實現簡單的GET和POST操作
* @author Dragondean
* @date 2015-05-14
*/
class ddhttp{
protected $url; //要請求的地址
protected $method; //請求方法
protected $data; //數據
public $errmsg; //錯誤信息,返回false的時候可以用來獲取詳細的錯誤代碼
public $sslkey = null; //sslkey,默認是pem格式
public $sslcert = null; //cert證書,默認是pem格式
/**
* GET方式抓取數據
* @param string $url 要抓取的URL
*/
public function get($url, $data = null){
$this->url = $url;
$data && $this->data = $data;
$this->method = "GET";
return $this->excrequest();
}
/**
* POST提交數據並返回內容
* @param string $url 要請求的地址
* @param mixed $data 提交的數據
*/
public function post($url, $data = null){
$this->url = $url;
$this->method = "POST";
$this->data = $data;
return $this->excrequest();
}
/**
* 執行請求並返回數據
* @access private
*/
private function excrequest(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if($this->sslcert){
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, $this->sslcert);
//echo $this->sslcert;
}
if($this->sslkey){
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, $this->sslkey);
//echo $this->sslkey;
}
//die($this->data);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);
$errorno = curl_errno($ch);
if(!$errorno)return $tmpInfo;
else{
$this->errmsg = $errorno;
return false;
}
}
}
?>