简单说一下OAuth协议:
OAUTH是一种开放的协议,为桌面、手机或web应用提供了一种简单的,标准的方式去访问需要用户授权的API服务。
下面我们去微博开发者平台登入微博。如图填写信息:
网站接入->创建新应用
填写信息后可以拿到微博给我们分配的App Key、App Secret
填写回调地址
下载php 版本的sdk包并解压
我这里把核心类文件saetv2.ex.class.php和weibo_login.png单独拿出来。
index.php<?php
require_once 'config.php';
require_once 'saetv2.ex.class.php';
$redis = new \Redis();
$redis->connect('127.0.0.1');
$cache_key = 'weibo_accessToken';
$isLogin = $redis->get($cache_key) ? true : false;
?>
微博登入测试登入成功
//$o = new SaeTClientV2(WB_KEY, WB_SEC, $redis->get($cache_key));
//debug($o->update('我的测试微博'));
?>
config.php<?php
/**
* Created by ZhengNiu.
* User: admin
* Date: 2019/8/28
* Time: 9:37
*/
define("WB_KEY", 'xxxxxxxx');//App Key
define("WB_SEC", 'xxxxxxxxx');//App Secret
define("CALLBACK","https://xxx.com/callback.php");//回调地址,需要和上面在微博平台配置的保持一致。
//调试工具暂时放这里
function debug($val, $dump = false, $exit = true)
{
if ($dump) {
$func = 'var_dump';
} else {
$func = (is_array($val) || is_object($val)) ? 'print_r' : 'printf';
}
header('Content-type:text-html;charset=utf-8');
echo '
debug output:';
$func($val);
echo "
";if ($exit) exit;
}
callback.php<?php
/**
* Created by ZhengNiu.
* User: admin
* Date: 2019/8/28
* Time: 10:20
*/
require_once 'config.php';
require_once 'saetv2.ex.class.php';
$redis = new \Redis();
$redis->connect('127.0.0.1');
$cache_key = 'weibo_accessToken';
$access_token = $redis->get($cache_key);
if (!$access_token) {
$keys['code'] = $_GET['code'];
$keys['redirect_uri'] = CALLBACK;
$o = new SaeTOAuthV2(WB_KEY, WB_SEC);
$res = $o->getAccessToken($keys);
$redis->setex($cache_key,$res['expires_in'], $res['access_token']);
$access_token = $res['access_token'];
}
header('Location:index.php');
loginout.php<?php
/**
* Created by ZhengNiu.
* User: admin
* Date: 2019/8/28
* Time: 11:10
*/
$redis = new \Redis();
$redis->connect('127.0.0.1');
$cache_key = 'weibo_accessToken';
$redis->delete($cache_key);
header('Location:index.php');
wblogin.php<?php
/**
* Created by ZhengNiu.
* User: admin
* Date: 2019/8/28
* Time: 10:10
*/
require_once 'config.php';
require_once 'saetv2.ex.class.php';
$o = new SaeTOAuthV2(WB_KEY, WB_SEC);
$oauth = $o->getAuthorizeURL(CALLBACK);
header('Location:'.$oauth);
上面只是粗略的写了代码演示了一下使用方法,应用中请根据自己的需求结合到框架里面。
演示: