목차
error:
msg? :
백엔드 개발 PHP 튜토리얼 QQ登录OAuth2.0 php接入种

QQ登录OAuth2.0 php接入种

Jun 13, 2016 pm 01:18 PM
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

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Jul 25, 2023 am 09:05 AM

세션 실패를 해결하는 방법 세션 실패를 해결하는 방법 Oct 18, 2023 pm 05:19 PM

세션 실패를 해결하는 방법

e의 NameResolutionError(self.host, self, e) 이유와 해결 방법 e의 NameResolutionError(self.host, self, e) 이유와 해결 방법 Mar 01, 2024 pm 01:20 PM

e의 NameResolutionError(self.host, self, e) 이유와 해결 방법

PHP 세션 교차 도메인 문제에 대한 솔루션 PHP 세션 교차 도메인 문제에 대한 솔루션 Oct 12, 2023 pm 03:00 PM

PHP 세션 교차 도메인 문제에 대한 솔루션

기능은 무슨 뜻인가요? 기능은 무슨 뜻인가요? Aug 04, 2023 am 10:33 AM

기능은 무슨 뜻인가요?

Redis 공유 세션 애플리케이션에서 SMS 로그인을 구현하는 방법 Redis 공유 세션 애플리케이션에서 SMS 로그인을 구현하는 방법 Jun 03, 2023 pm 03:11 PM

Redis 공유 세션 애플리케이션에서 SMS 로그인을 구현하는 방법

HTML과 URL의 차이점은 무엇입니까 HTML과 URL의 차이점은 무엇입니까 Mar 06, 2024 pm 03:06 PM

HTML과 URL의 차이점은 무엇입니까

Scrapy 최적화 팁: 중복 URL 크롤링을 줄이고 효율성을 높이는 방법 Scrapy 최적화 팁: 중복 URL 크롤링을 줄이고 효율성을 높이는 방법 Jun 22, 2023 pm 01:57 PM

Scrapy 최적화 팁: 중복 URL 크롤링을 줄이고 효율성을 높이는 방법

See all articles