Table of Contents
error:
msg? :
Home Backend Development PHP Tutorial QQ登录OAuth2.0 php接入种

QQ登录OAuth2.0 php接入种

Jun 13, 2016 am 10:39 AM
config function session url

QQ登录OAuth2.0 php接入类

?

/**
?*
?* qq登录
?* @author http://www.heui.org
?*
?*/
class Oauth_qq
{
??private static $_instance;
??private $config = array();
?
??private function __construct($config)
??{
????$this->Oauth_qq($config);
??}
?
??public static function getInstance($config)
??{
????if(!isset(self::$_instance))
????{
??????$c=__CLASS__;
??????self::$_instance = new $c($config);
????}
????return self::$_instance;
??}
?
??private function Oauth_qq($config)
??{
????$this->config = $config;
????$_SESSION["appid"]??? = $this->config['appid'];
????$_SESSION["appkey"]?? = $this->config['appkey'];
????$_SESSION["callback"] = $this->config['callback'];
????$_SESSION["scope"] = "get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo";
??}
?
??function login()
??{
????$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
????$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
????. $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"])
????. "&state=" . $_SESSION['state']
????. "&scope=".$_SESSION["scope"];
????header("Location:$login_url");
??}
?
??function callback()
??{
????if($_REQUEST['state'] == $_SESSION['state']) //csrf
????{
??????$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
??????. "client_id=" . $_SESSION["appid"]. "&redirect_uri=" . urlencode($_SESSION["callback"])
??????. "&client_secret=" . $_SESSION["appkey"]. "&code=" . $_REQUEST["code"];
?
??????$response = get_url_contents($token_url);
??????if (strpos($response, "callback") !== false)
??????{
????????$lpos = strpos($response, "(");
????????$rpos = strrpos($response, ")");
????????$response? = substr($response, $lpos + 1, $rpos - $lpos -1);
????????$msg = json_decode($response);
????????if (isset($msg->error))
????????{
??????????echo "<h3 id="error">error:</h3>" . $msg->error;
??????????echo "<h3 id="msg">msg? :</h3>" . $msg->error_description;
??????????exit;
????????}
??????}
?
??????$params = array();
??????parse_str($response, $params);
?
??????$_SESSION["access_token"] = $params["access_token"];
????}
????else
????{
??????echo("The state does not match. You may be a victim of CSRF.");
????}
??}
?
??function get_openid()
??{
????$graph_url = "https://graph.qq.com/oauth2.0/me?access_token="
????. $_SESSION['access_token'];
?
????$str? = get_url_contents($graph_url);
????if (strpos($str, "callback") !== false)
????{
??????$lpos = strpos($str, "(");
??????$rpos = strrpos($str, ")");
??????$str? = substr($str, $lpos + 1, $rpos - $lpos -1);
????}
?
????$user = json_decode($str);
????if (isset($user->error))
????{
??????echo "<h3 id="error">error:</h3>" . $user->error;
??????echo "<h3 id="msg">msg? :</h3>" . $user->error_description;
??????exit;
????}
?
????//set openid to session
????return $_SESSION["openid"] = $user->openid;
??}
?
??function get_user_info()
??{
????$get_user_info = "https://graph.qq.com/user/get_user_info?"
????. "access_token=" . $_SESSION['access_token']
????. "&oauth_consumer_key=" . $_SESSION["appid"]
????. "&openid=" . $_SESSION["openid"]
????. "&format=json";
?
????$info = get_url_contents($get_user_info);
????$arr = json_decode($info, true);
?
????return $arr;
??}
?
??public function __clone()
??{
????trigger_error('Clone is not allow' ,E_USER_ERROR);
??}
?
}
?
/* 公用函数 */
if (!function_exists("do_post"))
{
??function do_post($url, $data)
??{
????$ch = curl_init();
????curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
????curl_setopt($ch, CURLOPT_POST, TRUE);
????curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
????curl_setopt($ch, CURLOPT_URL, $url);
????$ret = curl_exec($ch);
?
????curl_close($ch);
????return $ret;
??}
}
if (!function_exists("get_url_contents"))
{
??function get_url_contents($url)
??{
????if (ini_get("allow_url_fopen") == "1")
????return file_get_contents($url);
?
????$ch = curl_init();
????curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
????curl_setopt($ch, CURLOPT_URL, $url);
????$result =? curl_exec($ch);
????curl_close($ch);
?
????return $result;
??}
}

使用实例:

$config['appid']??? = '';
$config['appkey']?? = '';
$config['callback'] = '';
$o_qq = Oauth_qq::getInstance($config);
?
//then
$o_qq->login();
//or
$o_qq->callback();
$o_qq->get_openid();
$o_qq->get_user_info();

原文:http://www.heui.org/archives/454

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP function introduction—get_headers(): Get the response header information of the URL PHP function introduction—get_headers(): Get the response header information of the URL Jul 25, 2023 am 09:05 AM

PHP function introduction—get_headers(): Overview of obtaining the response header information of the URL: In PHP development, we often need to obtain the response header information of the web page or remote resource. The PHP function get_headers() can easily obtain the response header information of the target URL and return it in the form of an array. This article will introduce the usage of get_headers() function and provide some related code examples. Usage of get_headers() function: get_header

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

What is the difference between html and url What is the difference between html and url Mar 06, 2024 pm 03:06 PM

Differences: 1. Different definitions, url is a uniform resource locator, and html is a hypertext markup language; 2. There can be many urls in an html, but only one html page can exist in a url; 3. html refers to is a web page, and url refers to the website address.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

How to implement SMS login in Redis shared session application How to implement SMS login in Redis shared session application Jun 03, 2023 pm 03:11 PM

1. Implementing SMS login based on session 1.1 SMS login flow chart 1.2 Implementing sending SMS verification code Front-end request description: Description of request method POST request path /user/code request parameter phone (phone number) return value No back-end interface implementation: @Slf4j@ ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1. Verify mobile phone number if

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

See all articles