CI框架 QQ接口(第三方登录接口PHP版)
本帖内容较多,大部分都是源码,要修改的地方只有一个,其他只要复制过去,就可以完美运行。本帖主要针对CI框架,不用下载SDK,按我下面的步骤,建文件,复制代码就可以了。10分钟不要,接口就可完成。
第一步:申请APP ID,APP KEY,申请地址:http://connect.opensns.qq.com/
验证通过后:会得到APP ID,APP KEY。这是你用个文件把这些信息保持下来,免得用的时候有要上网去查,记录在本地记事本里,方便,用的时候打开就可以。如下:
APP ID:101091331
APP KEY:7cb032049f2c900fea509424e614a979
回调地址:http://test.com
第二步:如果你的系统没有安装curl,请先安装curl。
怎么知道本地系统是否安装了curl呢,方法如下:
1.在web服务器目录( Ubuntu下的通常为 /var/www )新建crul.php文件
2.编辑文件,键入下面一行代码:
<?php phpinfo(); ?>
3.保存文件
4.打开浏览器,浏览该网页。(例如:http://localhost/curl.php)
5.搜索"curl",如果没搜到就证明没安装curl。
下面是安装方法:
打开终端,输入下面的命令:
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
再重启apache:
sudo /etc/init.d/apache2 restart
这样curl就安装好了,打开你刚才的那个页面,搜一下curl,就可以看到了curl了,这表示已经安装成功,很简单吧。
如果还是没有,编辑你的php.ini文件,我的phpini.php文件在/etc/php5/apache2/php.ini,估计你的也差不多是在这个位置,去找找看,找到后,打开这个文件,在最后加上一行:
extension=curl.so
保存文件后重启Apache服务器,再打开页面,就会出现curl了。
第三步:代码
注:腾讯提供了SDK,可以在官网下载:下载地址:http://wiki.connect.qq.com/sdk%E4%B8%8B%E8%BD%BD,如果不是CI框架,估计下载下来就可以用了,CI框架调用规则不同,所以要做修改,如果是CI框架下开发QQ登录接口,就不用下载SDK了,用我下面的代码,下面正式上代码,完整的代码。
代码步骤:
1.打开application/config/constants.php文件
写入如下代码:
/*qq登陆*/
define('GET_AUTH_CODE_URL', "https://graph.qq.com/oauth2.0/authorize");
define('GET_ACCESS_TOKEN_URL' , "https://graph.qq.com/oauth2.0/token");
define('GET_OPENID_URL' , "https://graph.qq.com/oauth2.0/me");
保存
2.打开application文件夹,在application下新建一个文件夹isetting,在isetting下建一个qq_setting.php文件,
打开qq_setting.php文件,输入如下代码:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* @qq互联配置信息
* 默认开启get_user_info模块
* **/
$config['inc_info'] = array(
array (
'appid' => '101091331',
'appkey' => '7cb032049f2c900fea509424e614a979',
'callback' => 'http://test.com'
),
array (
'get_user_info' => '1',
'add_topic' => '0',
'add_one_blog' => '0',
'add_album' => '0',
'upload_pic' => '0',
'list_album' => '0',
'add_share' => '0',
'check_page_fans' => '0',
'add_t' => '0',
'add_pic_t' => '0',
'del_t' => '0',
'get_repost_list' => '0',
'get_info' => '0',
'get_other_info' => '0',
'get_fanslist' => '0',
'get_idollist' => '0',
'add_idol' => '0',
'del_idol' => '0',
'get_tenpay_addr' => '0',
)
);
保存
说明:你需要把appid,appkey对应的键值修改成你刚刚申请的appid,appkey值,callback为回调地址(所谓回调地址就是登录成功后,返回到哪个页面),callback的值写你申请的时候做验证的那个地址。
3.打开application下的libraries文件,新建一个文件夹tencent,在tencent里面新建一个文件oauth.php,打开这个文件,复制下面的代码进去:
<?php
class Oauth
{
/**
* combineURL
* 拼接url
* @param string $baseURL 基于的url
* @param array $keysArr 参数列表数组
* @return string 返回拼接的url
*/
private $APIMap;
public function __construct() {
/*以下部分为获取第三方qq登陆资料*/
//初始化APIMap
/*
* 加#表示非必须,无则不传入url(url中不会出现该参数), "key" => "val" 表示key如果没有定义则使用默认值val
* 规则 array( baseUrl, argListArr, method)
*/
$this->APIMap = array(
/* qzone */
"add_blog" => array(
"https://graph.qq.com/blog/add_one_blog",
array("title", "format" => "json", "content" => null),
"POST"
),
"add_topic" => array(
"https://graph.qq.com/shuoshuo/add_topic",
array("richtype","richval","con","#lbs_nm","#lbs_x","#lbs_y","format" => "json", "#third_source"),
"POST"
),
"get_user_info" => array(
"https://graph.qq.com/user/get_user_info",
array("format" => "json"),
"GET"
),
"add_one_blog" => array(
"https://graph.qq.com/blog/add_one_blog",
array("title", "content", "format" => "json"),
"GET"
),
"add_album" => array(
"https://graph.qq.com/photo/add_album",
array("albumname", "#albumdesc", "#priv", "format" => "json"),
"POST"
),
"upload_pic" => array(
"https://graph.qq.com/photo/upload_pic",
array("picture", "#photodesc", "#title", "#albumid", "#mobile", "#x", "#y", "#needfeed", "#successnum", "#picnum", "format" => "json"),
"POST"
),
"list_album" => array(
"https://graph.qq.com/photo/list_album",
array("format" => "json")
),
"add_share" => array(
"https://graph.qq.com/share/add_share",
array("title", "url", "#comment","#summary","#images","format" => "json","#type","#playurl","#nswb","site","fromurl"),
"POST"
),
"check_page_fans" => array(
"https://graph.qq.com/user/check_page_fans",
array("page_id" => "314416946","format" => "json")
),
/* wblog */
"add_t" => array(
"https://graph.qq.com/t/add_t",
array("format" => "json", "content","#clientip","#longitude","#compatibleflag"),
"POST"
),
"add_pic_t" => array(
"https://graph.qq.com/t/add_pic_t",
array("content", "pic", "format" => "json", "#clientip", "#longitude", "#latitude", "#syncflag", "#compatiblefalg"),
"POST"
),
"del_t" => array(
"https://graph.qq.com/t/del_t",
array("id", "format" => "json"),
"POST"
),
"get_repost_list" => array(
"https://graph.qq.com/t/get_repost_list",
array("flag", "rootid", "pageflag", "pagetime", "reqnum", "twitterid", "format" => "json")
),
"get_info" => array(
"https://graph.qq.com/user/get_info",
array("format" => "json")
),
"get_other_info" => array(
"https://graph.qq.com/user/get_other_info",
array("format" => "json", "#name", "fopenid")
),
"get_fanslist" => array(
"https://graph.qq.com/relation/get_fanslist",
array("format" => "json", "reqnum", "startindex", "#mode", "#install", "#sex")
),
"get_idollist" => array(
"https://graph.qq.com/relation/get_idollist",
array("format" => "json", "reqnum", "startindex", "#mode", "#install")
),
"add_idol" => array(
"https://graph.qq.com/relation/add_idol",
array("format" => "json", "#name-1", "#fopenids-1"),
"POST"
),
"del_idol" => array(
"https://graph.qq.com/relation/del_idol",
array("format" => "json", "#name-1", "#fopenid-1"),
"POST"
),
/* pay */
"get_tenpay_addr" => array(
"https://graph.qq.com/cft_info/get_tenpay_addr",
array("ver" => 1,"limit" => 5,"offset" => 0,"format" => "json")
)
);
}
//登陆
public function check_login()
{
if(isset($_SESSION['qq']['state']) && $_GET['state'] && ($_SESSION['qq']['state'] == $_GET['state']))
{
return 'true';
}
else
{
return 'false';
}
}
public function qq_login()
{
$CI = &get_instance();
$CI->config->load('isetting/qq_setting');
$setting = $CI->config->item('inc_info');
$appid = $setting[0]['appid'];
$callback = $setting[0]['callback'];
$scope = '';
foreach ($setting[1] as $key=>$val)
{
if($val === '1')
{
$scope .= $key . ',';
}
}
$scope = trim(rtrim($scope,','));
//-------生成唯一随机串防CSRF攻击
$state = md5(uniqid(rand(), TRUE));
$_SESSION['qq']['state'] = $state;
//-------构造请求参数列表
$keysArr = array(
"response_type" => "code",
"client_id" => $appid,
"redirect_uri" => $callback,
"state" => $state,
"scope" => $scope
);
$login_url = $this->combineURL(GET_AUTH_CODE_URL, $keysArr);
header("Location:$login_url");
}
//callback回调方法
public function qq_callback()
{
$CI = &get_instance();
$CI->config->load('isetting/qq_setting');
$setting = $CI->config->item('inc_info');
$state = $_SESSION['qq']['state'];
//--------验证state防止CSRF攻击
if($_GET['state'] != $state){
echo "<script>alert('QQ第三方登陆失败');</script>";
redirect('/login','location',301);
}
//-------请求参数列表
$keysArr = array(
"grant_type" => "authorization_code",
"client_id" => $setting[0]['appid'],
"redirect_uri" => $setting[0]['callback'],
"client_secret" => $setting[0]['appkey'],
"code" => $_GET['code']
);
//------构造请求access_token的url
$token_url = $this->combineURL(GET_ACCESS_TOKEN_URL, $keysArr);
$response = $this->get_contents($token_url);
$params = array();
parse_str($response, $params);
$_SESSION['qq']['access_token'] = $params["access_token"];
$access_token = $params["access_token"];
$openid= $this->get_openid();
//进入主页
//获取用户信息
$_data = $this->qq_get_user($access_token,$openid);
redirect('/','location',301);
}
//注销
public function qq_logout()
{
}
public function combineURL($baseURL,$keysArr){
$combined = $baseURL."?";
$valueArr = array();
foreach($keysArr as $key => $val){
$valueArr[] = "$key=$val";
}
$keyStr = implode("&",$valueArr);
$combined .= ($keyStr);
return $combined;
}
/**
* get_contents
* 服务器通过get请求获得内容
* @param string $url 请求的url,拼接后的
* @return string 请求返回的内容
*/
public function get_contents($url)
{
if (ini_get("allow_url_fopen") == "1") {
$response = file_get_contents($url);
}else{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
}
//-------请求为空
if(empty($response)){
echo "<script>alert('QQ第三方登陆失败');</script>";
redirect('/login','location',301);
}
return $response;
}
public function get_openid()
{
//-------请求参数列表
$keysArr = array(
"access_token" => $_SESSION['qq']['access_token']
);
$graph_url = $this->combineURL(GET_OPENID_URL, $keysArr);
$response = $this->get_contents($graph_url);
//----检测错误是否发生
if(strpos($response, "callback") !== false)
{
$lpos = strpos($response, "(");
$rpos = strrpos($response, ")");
$response = substr($response, $lpos + 1, $rpos - $lpos -1);
}
$user = json_decode($response);
//------记录openid
$_SESSION['qq']['openid'] = $user->openid;
return $user->openid;
}
/**
* _call
* 魔术方法,做api调用转发
* @param string $name 调用的方法名称
* @param array $arg 参数列表数组
* @since 5.0
* @return array 返加调用结果数组
*/
public function __call($name,$arg){
//如果APIMap不存在相应的api
if(empty($this->APIMap[$name])){
echo "<script>alert('获取资料出错');</script>";
redirect('/login','location',301);
}
//从APIMap获取api相应参数
$baseUrl = $this->APIMap[$name][0];
$argsList = $this->APIMap[$name][1];
$method = isset($this->APIMap[$name][2]) ? $this->APIMap[$name][2] : "GET";
if(empty($arg)){
$arg[0] = null;
}
//对于get_tenpay_addr,特殊处理,php json_decode对\xA312此类字符支持不好
if($name != "get_tenpay_addr"){
$response = json_decode($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
$responseArr = $this->objToArr($response);
}else{
$responseArr = $this->simple_json_parser($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
}
//检查返回ret判断api是否成功调用
if($responseArr['ret'] == 0){
return $responseArr;
}else{
echo "<script>alert('第三方登陆失败')</script>";
redirect('/','location',301);
}
}
//调用相应api
private function _applyAPI($arr, $argsList, $baseUrl, $method){
$pre = "#";
$keysArr = $this->keysArr;
$optionArgList = array();//一些多项选填参数必选一的情形
foreach($argsList as $key => $val){
$tmpKey = $key;
$tmpVal = $val;
if(!is_string($key)){
$tmpKey = $val;
if(strpos($val,$pre) === 0){
$tmpVal = $pre;
$tmpKey = substr($tmpKey,1);
if(preg_match("/-(\d$)/", $tmpKey, $res)){
$tmpKey = str_replace($res[0], "", $tmpKey);
$optionArgList[$res[1]][] = $tmpKey;
}
}else{
$tmpVal = null;
}
}
//-----如果没有设置相应的参数
if(!isset($arr[$tmpKey]) || $arr[$tmpKey] === ""){
if($tmpVal == $pre){//则使用默认的值
continue;
}else if($tmpVal){
$arr[$tmpKey] = $tmpVal;
}else{
if($v = $_FILES[$tmpKey]){
$filename = dirname($v['tmp_name'])."/".$v['name'];
move_uploaded_file($v['tmp_name'], $filename);
$arr[$tmpKey] = "@$filename";
}else{
$this->error->showError("api调用参数错误","未传入参数$tmpKey");
}
}
}
$keysArr[$tmpKey] = $arr[$tmpKey];
}
//检查选填参数必填一的情形
foreach($optionArgList as $val){
$n = 0;
foreach($val as $v){
if(in_array($v, array_keys($keysArr))){
$n ++;
}
}
if(! $n){
$str = implode(",",$val);
$this->error->showError("api调用参数错误",$str."必填一个");
}
}
if($method == "POST"){
if($baseUrl == "https://graph.qq.com/blog/add_one_blog") $response = $this->urlUtils->post($baseUrl, $keysArr, 1);
else $response = $this->urlUtils->post($baseUrl, $keysArr, 0);
}else if($method == "GET"){
$response = $this->urlUtils->get($baseUrl, $keysArr);
}
return $response;
}
//php 对象到数组转换
private function objToArr($obj){
if(!is_object($obj) && !is_array($obj)) {
return $obj;
}
$arr = array();
foreach($obj as $k => $v){
$arr[$k] = $this->objToArr($v);
}
return $arr;
}
//简单实现json到php数组转换功能
private function simple_json_parser($json){
$json = str_replace("{","",str_replace("}","", $json));
$jsonValue = explode(",", $json);
$arr = array();
foreach($jsonValue as $v){
$jValue = explode(":", $v);
$arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
}
return $arr;
}
}
保存
说明:这段代码复制不过就行,不用做任何改动。这个是最核心的代码,代码比较多,但是功能代码就这些了,想想,在自己的网站上,别人用qq帐号就可以登录了,都不用注册,多方便啊,是吧,这样一想这些代码也不算多了。
4.建控制器。打开application下的controllers文件夹,在controllers下新建一个文件qq.php,打开qq.php,复制下面代码:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* @ qq登陆 注销 消息获取等
* @author
*/
class QQ extends CI_Controller
{
public function __construct() {
parent::__construct();
session_start();
$this->load->helper('url');
//error_reporting(0);
/*qq登陆*/
$this->load->library('tencent/oauth','oauth');
}
public function index()
{
//验证是登陆还是回调
if($this->oauth->check_login() === 'false')
{
$this->oauth->qq_login();
}
else
{
$this->oauth->qq_callback();
}
}
}
保存
说明:这段代码不用做修改。
5.放置登录按钮,点击用QQ帐号登录按钮,跳转到QQ登录页面登录。
在你的登录页面放按钮的位置,写入:
<div><a href="/qq"><img src="http://images.cnblogs.com/qq_login.png" width="110" /></a></div>
保存
说明:样式你可自己调整,图片按钮可以从官网下载,地址:http://wiki.connect.qq.com/%E8%A7%86%E8%A7%89%E7%B4%A0%E6%9D%90%E4%B8%8B%E8%BD%BD#2.QQ.E7.99.BB.E5.BD.95.E6.A1.86.E6.A0.87.E5.87.86.E6.A0.B7.E5.BC.8F
到这里,QQ第三方登录接口就OK了,你打开你的登录页面,点击QQ登录的图片按钮,它会转到QQ登录页面登录,如果要上线,要用到别的功能,可在这几个文件上填代码就行了。
申明:
本帖仅供学习参考,不涉及任何商业范围,如有冒犯,敬请原谅!
如有不对的地方,或者可以改良的地方,请回复指点,受教受教!
CI框架 QQ接口(第三方登录接口PHP版)的更多相关文章
- QQ登录接口(第三方登录接口)
CI框架 QQ接口(第三方登录接口PHP版) 本帖内容较多,大部分都是源码,要修改的地方只有一个,其他只要复制过去,就可以完美运行.本帖主要针对CI框架,不用下载SDK,按我下面的步骤,建文件,复制代 ...
- [iOS常见问题] 关于使用QQ做第三方登录的问题!
[iOS常见问题] 关于使用QQ做第三方登录的问题! 注意:QQ本身没有授权功能,所以想要使用QQ做第三方登录必须通过QQ空间来实现! 第一步:集成ShareSDK(步骤同集成分享的一样,如果已经集成 ...
- 第三方登录插件.NET版XY.OAuth-CSharp
XY.OAuth-CSharp GitHub:XY.OAuth-CSharp OSChina:XY.OAuth-CSharp 第三方登录插件.NET版 使用 首先,从NuGet上安装"XY. ...
- CI框架整合微信公共平台接口
#CI框架控制器 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /*** CI框架整合微信 ...
- 关于CI框架加入sphinx官方API接口文件的时候,需要注意的问题
从sphinx下载的官方文件sphinxapi.php中类名为class SphinxClient 加入到CI框架,放在system/libraries/下,由于需要遵从CI框架libraries类名 ...
- Android中用友盟实现QQ的第三方登录
//首先应该去友盟的官网注册你的账号,创建一个应用,获得它的APPkey,也可以用它的API上的appkey,下载SDK,下面根据API文档一步步实现就行了. //下面是友盟的APi文档 1. 产品 ...
- yii框架中保存第三方登录信息
(第三方登录) 创建应用,域名,详情请看:http://www.cnblogs.com/xujn/p/5287157.html 效果图:
- 【WEB开发】微信网页授权第三方登录接口(WEB登录)
随着手机微信的崛起,腾讯发布的微信联登确实很诱惑pc端的伙伴们,现在就说说在pc端用微信扫一扫实现微信第三方登陆的方式.(具体代码U盘) 本文链接至:http://blog.csdn.net/hxke ...
- CI框架下 新浪微博登录接口完整版
https://www.cnblogs.com/yznyzcw/p/3756622.html#top 说明:本贴只适合CI框架.功能实现:登录接口跳转链接成功,获取用户信息(包括最重要的u_id)成功 ...
随机推荐
- ARM 嵌入式中断
1. SATA中断要打开,挂在fiq上(通过cpu中断的fiq中断enable位,对sata中断使能), 2.外设及GPIO中断打开,挂在irq上(通过cpu中断的irq 的enable位对其使能), ...
- c# 基本知识 ref 和 out
一:首先两者都是引用传递,都是按地址传递的. 二: 区别 (1)ref 默认必须初始化,out 不需要显式初始化.例如: ; int num2; refMethod(ref num1); outMet ...
- 通用窗口类 Inventory Pro 2.1.2 Demo1(下)
本篇想总结的是Inventory Pro中通用窗口的具体实现,但还是要强调下该插件的重点还是装备系统而不是通用窗口系统,所以这里提到的通用窗口类其实是通用装备窗口类(其实该插件中也有非装备窗口比如No ...
- Ini文件操作函数
/// <summary> /// Copies a string into the specified section of an initialization file. /// &l ...
- C++之路起航——标准模板库(deque)
deque(双端队列):http://baike.baidu.com/link?url=JTvA2cuLubptctHZwFxswvlZvxNdFOxmifsYCGLj5IZF-Tj4rbWLv8Jn ...
- LED流水灯(二)
记住看汇编的时候是红在上面 黑色在下面 startup.s 程序 ; MDK跑马灯实验; PRESERVE8 // 字节对齐关键词 ,汇编有8位对齐的要求,要添加 AREA ...
- paper 71 :图像清晰化
图像清晰度是衡量图像品质优劣的标准之一,清晰的图像能给人以赏心悦目的视觉享受.长期以来,图像扫描设备和图像处理软件的开发生产厂商都很重视图像清晰度处理功能的开发,图像处理人员也在日常的实践中不断摸索出 ...
- java 中多线程和锁的使用
关键词: implements 实现 Runnable 类 run() 方法 注意点 : 创建类的实例 InterfaceController inter=new InterfaceContro ...
- 深入Java核心 探秘Java垃圾回收机制(转自http://edu.21cn.com/java/g_189_859836-1.htm)
垃圾收集GC(Garbage Collection)是Java语言的核心技术之一,之前我们曾专门探讨过Java 7新增的垃圾回收器G1的新特性,但在JVM的内部运行机制上看,Java的垃圾回收原理与机 ...
- C++之: CDib类
头文件Cdib.h 源文件Cdib.cpp