本文主要是介绍php之微信登陆,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
微信登陆和qq登陆一样,只是微信登陆少一个不走,access_token和openid是同时获取的。
class weixinClass{
protected $appid = "";
protected $callback = "";
protected $appkey = "";
public function __construct()
{
require(dirname(__FILE__) . '/oauth.config.php');
$this->appid = $wx['appid'];
$this->callback = urlencode($wx['callback']);
$this->appkey = $wx['appkey'];
}
public function wx_login(){
$response_type = "code";
$scope = "snsapi_login";
//-------生成唯一随机串防CSRF攻击
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$login_url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->appid.
"&redirect_uri=".$this->callback.
"&response_type=".$response_type.
"&scope=".$scope.
"&state=".$_SESSION['state']."#wechat_redirect";
header("Location:$login_url");
}
public function wx_callback(){
//--------验证state防止CSRF攻击
if($_REQUEST['state'] == $_SESSION['state']){
$grant_type = "authorization_code";
$code = $_REQUEST['code'];
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid.
"&secret=".$this->appkey.
"&code=".$code.
"&grant_type=".$grant_type;
$response = file_get_contents($token_url);
$params = json_decode($response, true);
if (isset($params->error))
{
echo "<h3>error:</h3>" . $msg->error;
echo "<h3>msg :</h3>" . $msg->error_description;
exit;
}
return $params;
}
else
{
return "";
}
}
function get_user_info($access_token, $openid)
{
if(!empty($access_token) && !empty($openid))
{
$user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token.
"&openid=".$openid;
$response = file_get_contents($user_url);
$params = json_decode($response, true);
if (isset($params->error))
{
echo "<h3>error:</h3>" . $msg->error;
echo "<h3>msg :</h3>" . $msg->error_description;
exit;
}
return $params;
}else
{
return "";
}
}
}
这篇关于php之微信登陆的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!