提交 1b4efcc8 编写于 作者: D devil_gong

优化

上级 079e8f7c
......@@ -76,7 +76,7 @@ class Pluginsadmin extends Common
'total' => $total,
'where' => $params,
'page' => isset($params['page']) ? intval($params['page']) : 1,
'url' => MyUrl('admin/Pluginsadmin/index'),
'url' => MyUrl('admin/pluginsadmin/index'),
);
$page = new \base\Page($page_params);
$this->assign('page_html', $page->GetPageHtml());
......
<?php
namespace app\plugins\shopoauth;
use think\Controller;
use app\plugins\shopoauth\ThinkOauth;
use app\service\PluginsService;
/**
* 第三方登入 API - 钩子入口
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
class Admin extends Controller
{
/**
* 后台首页
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
public function index($params = [])
{
$ret = PluginsService::PluginsData('shopoauth');
if($ret['code'] == 0)
{
$this->assign('data', $ret['data']);
return $this->fetch('../../../plugins/view/shopoauth/admin/index');
} else {
return $ret['msg'];
}
}
/**
* 参数配置
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
public function saveinfo($params = [])
{
$ret = PluginsService::PluginsData('shopoauth');
if($ret['code'] == 0)
{
// 是否
$is_whether_list = [
0 => array('id' => 0, 'name' => '否'),
1 => array('id' => 1, 'name' => '是', 'checked' => true),
];
$this->assign('is_whether_list', $is_whether_list);
$this->assign('data', $ret['data']);
return $this->fetch('../../../plugins/view/shopoauth/admin/saveinfo');
} else {
return $ret['msg'];
}
}
/**
* 数据编辑
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
public function save($params = [])
{
return PluginsService::PluginsDataSave(['plugins'=>'shopoauth', 'data'=>$params]);
}
}
?>
\ No newline at end of file
<?php
namespace app\plugins\shopoauth;
use think\Db;
use think\Controller;
use app\service\UserService;
use app\service\PluginsService;
use app\plugins\shopoauth\ThinkOauth;
use app\plugins\shopoauth\LoginEvent;
/**
* 第三方登入 API - 钩子入口
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
class Auth extends Controller
{
/**
* 解绑
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2019-03-15
* @desc description
* @param array $params [description]
* @return [type] [description]
*/
public function remove($params = [])
{
if(!empty($params['type']))
{
$user = UserService::LoginUserInfo();
if(!empty($user['id']))
{
Db::name('PluginsShopoauthOauth')->where(['platform'=>$params['type'], 'user_id'=>$user['id']])->delete();
}
}
$this->redirect(MyUrl('user/personal/index'));
}
/**
* 跳转授权登入
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
public function login($params = []){
$sns = ThinkOauth::getInstance($params['type']);
$this->redirect($sns->getRequestCodeURL());
}
/**
* 授权回调地址
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
public function callback($params = [])
{
if(empty($params['code']) || empty($params['type']))
{
return 'ERROR-10001——参数出错!';exit;
}
$sns = ThinkOauth::getInstance($params['type']);
$token = $sns->getAccessToken($params['code'], []);
$type = $params['type'];
//获取当前登录用户信息
if(is_array($token))
{
$even = new LoginEvent();
$result = $even->$type($token);
/*校验是否登入*/
$user = UserService::LoginUserInfo();
$user_id = empty($user['id']) ? 0 : $user['id'];
//登入后返回信息
if(!empty($result))
{
$oauth = [
'user_id' => $user_id,
'platform' => $result['type'],
'openid' => $result['token']['openid'],
'openname' => $result['name'],
'access_token' => $result['token']['access_token'],
'refresh_token' => $result['token']['refresh_token'],
'expires_in' => $result['token']['expires_in'],
'createtime' => time(),
'updatetime' => time(),
'logintime' => time()
];
//判断或者写入oauth表
$where = ['openid'=>$oauth['openid']];
$oauth_user = Db::name('PluginsShopoauthOauth')->where($where)->find();
if(!empty($oauth_user))
{
$up_data = [
'access_token' => $result['token']['access_token'],
'refresh_token' => $result['token']['refresh_token'],
'expires_in' => $result['token']['expires_in'],
'updatetime' => time(),
'logintime' => time()
];
//更新表数据
//用户是否已绑定账号
if(!empty($oauth_user['user_id']))
{
Db::name('PluginsShopoauthOauth')->where($where)->update($up_data);
//更新用户登录缓存数据
UserService::UserLoginRecord($oauth_user['user_id']);
$this->redirect('/');
} else {
Db::name('PluginsShopoauthOauth')->where($where)->update($up_data);
session('oauth_id', $oauth['openid']);
//跳转注册页面
$this->success('登入成功,请绑定或注册账号~', MyUrl('/index/user/reginfo'));
}
} else {
$id = Db::name('PluginsShopoauthOauth')->insertGetId($oauth);
if($user_id > 0)
{
UserService::UserLoginRecord($user_id);
$this->redirect('/');
} else {
session('oauth_id', $oauth['openid']);
$this->success('登入成功,请绑定或注册账号~', MyUrl('/index/user/reginfo'));
}
}
} else {
$this->error('系统出错~');
}
} else {
$this->error('TOKEN-ERROR-10001——参数出错!~');
}
}
}
?>
\ No newline at end of file
<?php
namespace app\plugins\shopoauth;
use think\Db;
use app\service\PluginsService;
use app\service\UserService;
/**
* 第三方登入 API - 钩子入口
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
class Hook
{
/**
* 钩子入口
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
public function run($params = [])
{
// 是否后端钩子
if(!empty($params['hook_name']))
{
switch($params['hook_name'])
{
// 用户登录后更新关联表登录时间
case 'plugins_service_user_login_end' :
$ret = $this->LoginUpdate($params);
break;
// 顶部登录入口/登录信息
case 'plugins_view_header_navigation_top_left' :
$ret = $this->LoginNavTopHtml($params);
break;
// header代码
case 'plugins_common_header' :
$ret = $this->Style($params);
break;
// 用户中心资料列表
case 'plugins_service_users_personal_show_field_list_handle' :
$ret = $this->UserPersonal($params);
break;
default :
$ret = DataReturn('无需处理', 0);
}
return $ret;
// 默认返回视图
} else {
return '';
}
}
/**
* 用户中心资料
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @date 2019-03-15
* @param [array] $params [输入参数]
* @desc description
*/
public function UserPersonal($params = [])
{
if(!empty($params['data']))
{
//读取用户信息
$user = UserService::LoginUserInfo();
if(!empty($user['id']))
{
//读取当前已经有的数据
$ret = PluginsService::PluginsData('shopoauth');
if(!empty($ret['data']['auth']))
{
$html = '';
foreach($ret['data']['auth'] as $k=>$v)
{
if(isset($v['open']) && $v['open'] == 1)
{
$icon = strtoupper($k);
$name = empty($v['name']) ? $k : $v['name'];
$oauth = Db::name('PluginsShopoauthOauth')->where(['platform'=>$icon, 'user_id'=>$user['id']])->find();
$value = '未绑定';
if(!empty($oauth))
{
$value = $name.'('.$oauth['openname'].')';
$html .= '<a href="'.PluginsHomeUrl('shopoauth', 'auth', 'remove',['type'=>$k]).'">解绑</a>';
} else {
$html .= '<a href="'.PluginsHomeUrl('shopoauth', 'auth', 'login',['type'=>$k]).'"><i class="am-icon-'.$icon.'"></i> 前去绑定</a>';
}
$params['data'][] = [
'is_ext' => 1,
'name' => $name,
'value' => $value,
'tips' => $html,
];
}
}
}
}
}
return DataReturn('处理成功', 0);
}
/**
* 前端顶部小导航展示登入
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
* @param [array] $params [输入参数]
*/
public function LoginNavTopHtml($params = [])
{
// 获取已登录用户信息,已登录则不展示入口
$user = UserService::LoginUserInfo();
if(empty($user))
{
// 获取插件信息
$ret = PluginsService::PluginsData('shopoauth');
$html = '<div class="am-dropdown menu-hd plugins-shopoauth-nav-top" data-am-dropdown>
<a class="am-dropdown-toggle" href="javascript:;" target="_top" data-am-dropdown-toggle>
<i class="am-icon-cube am-icon-link"></i>
<span>第三方登入</span>
<i class="am-icon-caret-down"></i>
</a><ul class="am-dropdown-content">';
if(!empty($ret['data']['auth']))
{
foreach($ret['data']['auth'] as $k=>$v)
{
if(isset($v['open']) && $v['open'] == 1)
{
$name = empty($v['name']) ? $k : $v['name'];
$html .= '<li><a href="'.PluginsHomeUrl('shopoauth', 'auth', 'login',['type'=>$k]).'"><i class="am-icon-cube am-icon-qq"></i> '.$name.'</a></li>';
}
}
$html .= '</ul></div>';
return $html;
}
}
return '';
}
/**
* css
* @author Devil
* @blog http://gong.gg/
* @version 1.0.0
* @datetime 2019-02-06T16:16:34+0800
* @param [array] $params [输入参数]
*/
public function Style($params = [])
{
return '<style type="text/css">
.plugins-shopoauth-nav-top { margin-left: 10px; }
</style>';
}
/**
* 更新登录时间
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
private function LoginUpdate($params)
{
$oauth_id = session('oauth_id');
if(!empty($oauth_id) && !empty($params['user_id']))
{
$up_data = [
'user_id' => $params['user_id'],
'logintime' => time()
];
Db::name('PluginsShopoauthOauth')->where(['openid'=>$oauth_id])->update($up_data);
}
return DataReturn('处理成功', 0);
}
}
?>
\ No newline at end of file
<?php
namespace app\plugins\shopoauth;
use app\plugins\shopoauth\ThinkOauth;
/**
* 登入事件
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
class LoginEvent
{
//登录成功,获取腾讯QQ用户信息
public function qq($token)
{
$qq = ThinkOauth::getInstance('qq', $token);
$data = $qq->call('user/get_user_info');
if ($data['ret'] == 0) {
$userInfo['type'] = 'QQ';
$userInfo['name'] = $data['nickname'];
$userInfo['nick'] = $data['nickname'];
$userInfo['head'] = $data['figureurl_2'];
$userInfo['openid'] = $qq->openid();
$userInfo['token'] = $token;
return $userInfo;
} else {
throw new \think\Exception("获取腾讯QQ用户信息失败:{$data['msg']}");
}
}
}
\ No newline at end of file
<?php
namespace app\plugins\shopoauth;
use app\service\PluginsService;
use app\plugins\shopoauth\LoginEvent;
/**
* ThinkOauth
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
abstract class ThinkOauth
{
/**
* oauth版本
* @var string
*/
protected $Version = '3.0';
/**
* 申请应用时分配的app_key
* @var string
*/
protected $AppKey = '';
/**
* 申请应用时分配的 app_secret
* @var string
*/
protected $AppSecret = '';
/**
* 授权类型 response_type 目前只能为code
* @var string
*/
protected $ResponseType = 'code';
/**
* grant_type 目前只能为 authorization_code
* @var string
*/
protected $GrantType = 'authorization_code';
/**
* 回调页面URL 可以通过配置文件配置
* @var string
*/
protected $Callback = '';
/**
* 获取request_code的额外参数 URL查询字符串格式
* @var srting
*/
protected $Authorize = '';
/**
* 获取request_code请求的URL
* @var string
*/
protected $GetRequestCodeURL = '';
/**
* 获取access_token请求的URL
* @var string
*/
protected $GetAccessTokenURL = '';
/**
* API根路径
* @var string
*/
protected $ApiBase = '';
/**
* 授权后获取到的TOKEN信息
* @var array
*/
protected $Token = null;
/**
* 调用接口类型
* @var string
*/
private $Type = '';
/**
* 构造方法,配置应用信息
* @param array $token
*/
public function __construct($token = null)
{
$class = get_class($this);
$this->Type = explode('\\', strtoupper(substr($class, 0, strlen($class) - 3)))[4];
$ret = PluginsService::PluginsData('shopoauth');
foreach($ret['data']['auth'] as $k=>$v){
if($v['open']==1){
$configs[strtoupper($k)] = $v;
$configs[strtoupper($k)]['CALLBACK'] = PluginsHomeUrl('shopoauth', 'Auth', 'callback',['type'=>$k]);
}
}
$config =$configs[$this->Type];
if (empty($config['app_key']) || empty($config['app_secret'])) {
throw new \think\Exception('请配置您申请的APP_KEY和APP_SECRET', 100001);
} else {
$this->AppKey = $config['app_key'];
$this->AppSecret = $config['app_secret'];
$this->Token = $token; //设置获取到的TOKEN
}
}
/**
* 取得Oauth实例
* @static
* @return mixed 返回Oauth
*/
public static function getInstance($type, $token = null)
{
$name = ucfirst(strtolower($type)) . 'SDK';
if (class_exists("app\plugins\shopoauth\sdk\\{$name}")) {
$class_name = "\app\plugins\shopoauth\sdk\\{$name}";
return new $class_name($token);
} else {
throw new \think\Exception('CLASS_NOT_EXIST:' . $name, 100002);
}
}
/**
* 请求code
*/
public function getRequestCodeURL()
{
$this->config();
//Oauth 标准参数
$params = array(
'client_id' => $this->AppKey,
'redirect_uri' => $this->Callback,
'response_type' => $this->ResponseType,
);
//获取额外参数
if ($this->Authorize) {
parse_str($this->Authorize, $_param);
if (is_array($_param)) {
$params = array_merge($params, $_param);
} else {
throw new \think\Exception('AUTHORIZE配置不正确!',100003);
}
}
return $this->GetRequestCodeURL . '?' . http_build_query($params);
}
/**
* 初始化配置
*/
private function config()
{
$class = get_class($this);
$this->Type = explode('\\', strtoupper(substr($class, 0, strlen($class) - 3)))[4];
$ret = PluginsService::PluginsData('shopoauth');
foreach($ret['data']['auth'] as $k=>$v){
if($v['open']==1){
$configs[strtoupper($k)] = $v;
$configs[strtoupper($k)]['CALLBACK'] = PluginsHomeUrl('shopoauth', 'Auth', 'callback',['type'=>$k]);
}
}
$config =$configs[$this->Type];
if (!empty($config['AUTHORIZE']))
$this->Authorize = $config['AUTHORIZE'];
if (!empty($config['CALLBACK']))
$this->Callback = $config['CALLBACK'];
else
throw new \think\Exception('请配置回调页面地址',100004);
}
/**
* 获取access_token
* @param string $code 上一步请求到的code
* $code = $_GET['code']
*/
public function getAccessToken($code, $extend = null)
{
$this->config();
$params = array(
'client_id' => $this->AppKey,
'client_secret' => $this->AppSecret,
'grant_type' => $this->GrantType,
'code' => $code,
'redirect_uri' => $this->Callback,
);
$data = $this->http($this->GetAccessTokenURL, $params, 'POST');
$this->Token = $this->parseToken($data, $extend);
return $this->Token;
}
/**
* 发送HTTP请求方法,目前只支持CURL发送请求
* @param string $url 请求URL
* @param array $params 请求参数
* @param string $method 请求方法GET/POST
* @return array $data 响应数据
*/
protected function http($url, $params, $method = 'GET', $header = array(), $multi = false)
{
$opts = array(
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $header
);
/* 根据请求类型设置特定参数 */
switch (strtoupper($method)) {
case 'GET':
$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
break;
case 'POST':
//判断是否传输文件
$params = $multi ? $params : http_build_query($params);
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $params;
break;
default:
throw new \think\Exception('不支持的请求方式!',100005);
}
/* 初始化并执行curl请求 */
$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error)
throw new \think\Exception('请求发生错误:' . $error,100006);
return $data;
}
/**
* 抽象方法,在SNSSDK中实现
* 解析access_token方法请求后的返回值
*/
abstract protected function parseToken($result, $extend);
/**
* 抽象方法,在SNSSDK中实现
* 获取当前授权用户的SNS标识
*/
abstract public function openid();
/**
* 合并默认参数和额外参数
* @param array $params 默认参数
* @param array /string $param 额外参数
* @return array:
*/
protected function param($params, $param)
{
if (is_string($param))
parse_str($param, $param);
return array_merge($params, $param);
}
/**
* 获取指定API请求的URL
* @param string $api API名称
* @param string $fix api后缀
* @return string 请求的完整URL
*/
protected function url($api, $fix = '')
{
return $this->ApiBase . $api . $fix;
}
/**
* 抽象方法,在SNSSDK中实现
* 组装接口调用参数 并调用接口
*/
abstract protected function call($api, $param = '', $method = 'GET', $multi = false);
}
{
"base":{
"plugins":"shopoauth",
"name":"第三方账号登陆",
"logo":"\/static\/upload\/images\/plugins_shopoauth\/2019\/03\/13\/1552472848865750.png",
"author":"guoguo",
"author_url":"http:\/\/gadmin.cojz8.com",
"version":"1.0.0",
"desc":"第三方账号登陆",
"apply_terminal":[
"pc"
],
"apply_version":[
"1.4.0"
],
"is_home":false
},
"hook":{
"plugins_common_header":[
"app\\plugins\\shopoauth\\Hook"
],
"plugins_service_user_login_end":[
"app\\plugins\\shopoauth\\Hook"
],
"plugins_view_header_navigation_top_left":[
"app\\plugins\\shopoauth\\Hook"
],
"plugins_service_users_personal_show_field_list_handle":[
"app\\plugins\\shopoauth\\Hook"
]
}
}
\ No newline at end of file
<?php
namespace app\plugins\shopoauth\sdk;
use app\plugins\shopoauth\ThinkOauth;
/**
* QQ类库
* @author Guoguo
* @blog http://gadmin.cojz8.com
* @version 1.0.0
* @datetime 2019年3月14日
*/
class QqSDK extends ThinkOauth
{
/**
* 获取requestCode的api接口
* @var string
*/
protected $GetRequestCodeURL = 'https://graph.qq.com/oauth2.0/authorize';
/**
* 获取access_token的api接口
* @var string
*/
protected $GetAccessTokenURL = 'https://graph.qq.com/oauth2.0/token';
/**
* 获取request_code的额外参数,可在配置中修改 URL查询字符串格式
* @var srting
*/
protected $Authorize = 'scope=get_user_info,add_share';
/**
* API根路径
* @var string
*/
protected $ApiBase = 'https://graph.qq.com/';
/**
* 组装接口调用参数 并调用接口
* @param string $api 微博API
* @param string $param 调用API的额外参数
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET', $multi = false)
{
/* 腾讯QQ调用公共参数 */
$params = array(
'oauth_consumer_key' => $this->AppKey,
'access_token' => $this->Token['access_token'],
'openid' => $this->openid(),
'format' => 'json'
);
$data = $this->http($this->url($api), $this->param($params, $param), $method);
return json_decode($data, true);
}
/**
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result, $extend)
{
parse_str($result, $data);
if ($data['access_token'] && $data['expires_in']) {
$this->Token = $data;
$data['openid'] = $this->openid();
return $data;
} else
throw new \think\Exception("获取腾讯QQ ACCESS_TOKEN 出错:{$result}");
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function openid()
{
$data = $this->Token;
if (isset($data['openid']))
return $data['openid'];
elseif ($data['access_token']) {
$data = $this->http($this->url('oauth2.0/me'), array('access_token' => $data['access_token']));
$data = json_decode(trim(substr($data, 9), " );\n"), true);
if (isset($data['openid']))
return $data['openid'];
else
throw new \think\Exception("获取用户openid出错:{$data['error_description']}");
} else {
throw new \think\Exception('没有获取到openid!');
}
}
}
此差异已折叠。
......@@ -58,7 +58,7 @@ App({
// 请求地址
request_url: "{{request_url}}",
//request_url: "https://test.shopxo.net/",
request_url: 'http://tp5-dev.com/',
//request_url: 'http://tp5-dev.com/',
// 基础信息
application_title: "{{application_title}}",
......
/**
* 首页
*/
.shopoauth-content .items {
margin: 10px 0 20px 0;
border-bottom: 1px dashed #f1f1f1;
padding-bottom: 20px;
}
.shopoauth-content .edit-submit {
margin-bottom: 20px;
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册