微信登录类

Posted by
<?php
/**
* 微信网页登录类
* @author guomumin <aaron8573@gmail.com>
* @version 1.0
* @date 2014-12-19
*/
class Voauth{

/**
* @var 授权获取code url
*/
private $oauth_url = 'https://open.weixin.qq.com/connect/qrconnect';

/**
* @var 授权获取access_token url
*/
private $access_url = 'https://api.weixin.qq.com/sns/oauth2/access_token';

/**
* @var 获取用户信息
*/
private $user_info_url = 'https://api.weixin.qq.com/sns/userinfo';

/**
* @var 微信appid
*/
private $appid = '';

/**
* @var 微信appsecret
*/
private $appsecret = '';

/**
* @var 返回地址
*/
private $redirect_uri = '';

/**
* @var access_token
*/
private $access_token = '';

/**
* 初始化设置
* 主要设置 $param = array('appid'=>'', 'appsecret'=>'', 'redirect_uri'=>'')
*/
public function init( $params = array() )
{
if ( empty($params) )
{
return false;
}

foreach ( $params as $k => $v )
{
if ( isset($this->$k) )
{
$this->$k = $v;
}
}
}

/**
* 发起授权页面,获取code
*/
public function getCode( $state = '' )
{
$param = array();
$param['appid'] = $this->appid;
$param['redirect_uri'] = $this->redirect_uri;
$param['response_type'] = 'code';
$param['scope'] = 'snsapi_login';
$param['state'] = $state;

$query = http_build_query($param, '', '&');
header("Location:".$this->oauth_url.'?'.$query);
}

/**
* 获取access_token
* @return array / false
*/
public function getAccessToken( $code = '' )
{
if ( $code == '' )
{
return false;
}

$param = array();
$param['appid'] = $this->appid;
$param['secret'] = $this->appsecret;
$param['code'] = $code;
$param['grant_type'] = 'authorization_code';

$query = http_build_query($param);

$url = $this->access_url.'?'.$query;

$result = $this->httpGet($url);

if ($result)
{
if (isset($result['access_token']))
{
$this->setAccessToken( $result['access_token'] );
}

return $result;
}else{
return false;
}
}

/**
* 获取指定用户的用户信息
* @return array / false
*/
public function getUserInfo( $openid = '' )
{
if ( $openid == '' )
{
return false;
}

$url = $this->user_info_url. '?access_token=' .$this->access_token.'&openid='. $openid;

$result = $this->httpGet($url);

if ( $result )
{
return $result;
}else{
return false;
}
}

/**
* 设置access_token
*/
public function setAccessToken($params = '')
{
if ($params != '')
{
$this->access_token = $params;
}
}

/**
* 发起get请求
* @return array / false
*/
public function httpGet( $url = '')
{
if ($url == '')
{
return false;
}

$oCurl = curl_init();
if( stripos($url,"https://") !== FALSE )
{
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
}

curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );

$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);

if( intval($aStatus["http_code"]) == 200 )
{
return json_decode($sContent, true);
}
else
{
return false;
}
}

}
?>

4 comments

Leave a Reply

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据