/**
* 微信授权登录类
* Author:1327444968
*/
var wx_union = (function () {
var wx_type = "wx_web";
var isDebug = true;
function Debug(str) {
if (!isDebug) {
return;
}
console.log(str);
}
function getCookie(name) {
var reg = new RegExp("(^|)("+name+")=([^;]*)(;|$)", 'gi');
var obj={};
document.cookie.replace(reg, (match, p1, p2,p3) => {
// console.log(match, p1, p2,p3)
Object.defineProperty(obj, name, {
value: p3,
enumerable: true,
writable: true
});
return null;
});
return (obj[name]||null);
}
/*
* 设置Cookies
*/
function setCookie(name, value, domain, time) {
Debug("设置Cookies:" + name + "=" + value);
time = time || 3600 * 24 * 30;
var strsec = time;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
//document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
domain = domain||"changsha.cn";
document.cookie = name + "=" + escape(value) + ";path=/;domain=" + domain + ";expires=" + exp.toGMTString();
console.log(document.cookie );
}
//获取绑定key
function getauth(key, sign, backurl) {
var domain = document.domain;
if (backurl == undefined) {
backurl = window.location;
}
backurl = "https://" + domain + '/oc/callback.php?callback=' + encodeURIComponent(backurl);
var url = 'https://u.changsha.cn/OcApi/?action=synUnionLogin';
url += '&type=' + wx_type;
url += '&key=' + key;
url += '&sign=' + sign;
url += '&callback=' + escape(backurl);
url += "&t=" + Math.random();
return url;
}
//解除绑定接口
function getunauth(key, sign) {
var url = 'https://u.changsha.cn/OcApi/?action=synUnbindUnionLogin';
url += '&type=' + wx_type;
url += '&key=' + key;
url += '&sign=' + sign;
url += "&t=" + Math.random();
return url;
}
//获取登录key
function getlogin(key, backurl) {
var domain = document.domain;
if (backurl == undefined) {
backurl = window.location;
}
//var backurl = "https://" + domain + '/index.php?d=login&a=login&m_callback=' + encodeURIComponent(window.location);
// backurl = "https://" + domain + '/oc/callback.php?callback=' + encodeURIComponent(backurl);
//backurl = "https://" + getCookie('callback_domain') + '/oc/callback.php?callback=' + encodeURIComponent(backurl);
var url = 'https://u.changsha.cn/OcApi/?action=synUnionLogin';
url += '&type=' + wx_type;
url += '&key=' + key;
url += '&callback=' + encodeURIComponent(backurl);
url += "&t=" + Math.random();
console.log('returnUrl : ', url);
return url;
}
//获取绑定状态key
function getbindstate(key) {
var url = 'https://u.changsha.cn/OcApi/?action=synUnionState';
url += '&type=' + wx_type;
url += '&key=' + key;
url += "&t=" + Math.random();
return url;
}
function isweixin() {
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
}
return false;
}
function getkey() {
var openid = getCookie("openid");
return openid;
}
function getWxUserinfo() {
var userinfo = getCookie("wx_userinfo");
console.log(userinfo);
if (isnull(userinfo)) {
return null;
}
// userinfo = JSON.parse(userinfo);
return userinfo;
}
function isnull(v) {
if (v == undefined || v == null || v == "") {
return true;
}
return false;
}
//初始化微信KEY
function init(siteid) {
var openid = getkey();
if (!isweixin() && isDebug == true) {
setCookie("openid", "otTtC1i4CGSX9r5VnNYBtI01mjlk");
//setCookie("openid","otTtC1gv0J57GpdYNuvqmoqDy9Vk");
return;
}
siteid = siteid || 8;
weixin.init({
siteid: siteid,
userinfo: true,
islogin: true,
callback: function () {
// console.log(weixin.userinfo);
openid = weixin.userinfo.openid;
var wx_userinfo = weixin.userinfo;
if (isweixin()) {
setCookie("openid", openid);
setCookie("wx_userinfo", encodeURI(JSON.stringify(wx_userinfo), 'utf8'));
}
console.log(wx_userinfo);
$(wx_union).trigger("over", [openid, wx_userinfo, false]);
}
});
}
//微信绑定
function bindwx(sign, backfunc) {
var key = getkey();
var msg = "";
Debug("openid:" + key);
if (key == undefined || key == "") {
msg = "openid为空,请确认已经授权";
backfunc(msg, -1);
return;
}
if (sign == undefined || sign == "") {
msg = "请先登录";
backfunc(msg, -2);
return;
}
var backurl = getauth(key, sign);
console.log(backurl);
window.location = backurl;
}
//解除微信绑定
function unbindwx(sign, backfunc) {
var key = getkey();
var msg = "";
Debug("openid:" + key);
if (key == undefined || key == "") {
msg = "openid为空,请确认已经授权";
backfunc(msg, -1);
return;
}
if (sign == undefined || sign == "") {
msg = "请先登录";
backfunc(msg, -2);
return;
}
var url = getunauth(key, sign);
$.ajax({
url: url,
dataType: "json",
success: function (data) {
Debug(data);
backfunc(data.msg, data.code);
}
});
}
//微信登录
function wxlogin(backfunc, backurl) {
var key = getkey();
var msg = "";
Debug("openid:" + key);
if (key == undefined || key == "") {
msg = "openid为空,请确认已经授权";
backfunc(msg, -1);
return;
}
var backurl = getlogin(key, backurl);
//alert(backurl);
//$("body").append(backurl);
window.location = backurl;
}
var union = {
init: function (option) {
var opt = {
isDebug: false,
};
$.extend(opt, option);
isDebug = opt.isDebug;
init();
},
wxlogin: function (backfunc, autobind) {
backfunc = backfunc || function () {
};
wx_union.isbind(function (msg, code) {
if (code == "yes" || autobind != undefined) {
wxlogin(backfunc);
} else {
backfunc(msg, code);
}
});
},
wxloginauto: function (sign, backurl, backfunc) {
backfunc = backfunc || function () {
};
//if (!isnull(sign)) {
// backfunc("已经登录", 0);
// return;
//}
wx_union.isbind(function (msg, code) {
if (code == "yes") {
wxlogin(backfunc, backurl);
} else {
backfunc(msg, code);
}
});
},
bindwx: function (sign, backfunc) {
backfunc = backfunc || function () {
};
bindwx(sign, backfunc);
},
unbindwx: function (sign, backfunc) {
backfunc = backfunc || function () {
};
unbindwx(sign, backfunc);
},
getsign: function () {
return getCookie("sign");
},
isbind: function (backfunc) {
backfunc = backfunc || function () {
};
var key = getkey();
var url = getbindstate(key);
$.ajax({
url: url,
dataType: "json",
success: function (data) {
backfunc(data.msg, data.code);
console.log(data);
}
});
},
WxUserinfo: function () {
return getWxUserinfo();
},
clear: function (backfunc) {
setCookie("openid", "");
setCookie("wx_userinfo", "");
setCookie("sign", "");
backfunc("清除成功", 0);
},
setCookie: function (name, value, domain, time) {
Debug("设置Cookies:" + name + "=" + value);
time = time || 3600 * 24 * 30;
var strsec = time;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
//document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
domain = "changsha.cn";
document.cookie = name + "=" + escape(value) + ";path=/;domain=" + domain + ";expires=" + exp.toGMTString();
},
};
return union;
})
(window.JQuery || $);
var oc = (function () {
var ishttps = 'https:' == document.location.protocol ? true : false;
var http = document.location.protocol + "//";
var base_url = http + 'u.changsha.cn';
var oc_url = base_url + "/OcApi/";//用户中心地址
var oc_callback = http + document.domain + "/oc/callback.php";//回调地址
oc_callback = oc_callback + "?m_callback=" + encodeURIComponent(window.location.href);//此处需和同步回调同步处理
// var oc_callback = http + "u.changsha.cn" + "/oc/callback.php";//回调地址
var opt;
var isDebug = false;
Debug("ishttps:" + ishttps);
Debug("https:" + http);
var user;//用户对象
var pub_data;//返回数据对象
var sign;//签名保存
var signdata;//签名数据
var oc_obj;//显示登录状态对象
var oc_qr_obj;//显示二维码对象
var CheckQR_Flag = false;//检测二维码登录状态
/*构造授权链接*/
function getBaseUrl(action) {
var url = oc_url + "?action=" + action + "&callback=" + encodeURIComponent(oc_callback) + "&t1_FromDomain=" + document.domain + "&debug=" + isDebug + "&t=" + Math.random();
return url;
}
function loadcss(src, stype) {
var oHead = document.getElementsByTagName('HEAD').item(0);
var oCss = document.createElement("link");
oCss.type = "text/css";
if (stype == "1") {
oCss.href = base_url + "/OcApi/res/css/" + src;
} else {
oCss.href = src;
}
oCss.rel = "stylesheet";
oHead.appendChild(oCss);
}
function loadjs(src, stype) {
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement("script");
oScript.type = "text/javascript";
if (stype == "1") {
oScript.src = base_url + "/OcApi/res/js/" + src;
} else {
oScript.src = src;
}
oHead.appendChild(oScript);
}
function incjs(js) {
document.write("");
}
/*构造SessionID*/
function getSessionID() {
var sid = getCookie("PHPSESSID");
return sid;
}
/*调试信息*/
function Debug(log, flag) {
flag = flag || "console";
if (isDebug) {
console.log("【" + flag + "】");
console.log(log);
$(oc).trigger("onDebug", [log, flag]);
}
}
function GenCodeApi() {
center.ajax({
type: "post",
url: getBaseUrl("synGenCodeApi"),
data: {},
dataType: "json",
success: function (data) {
//var rect=JsonLower(data.rect);
var rect = data.rect;
if (data.code == "yes") {
setCookie("PHPSESSID", rect.PHPSESSID);
}
$(oc).trigger("onListenCodeLogin", [data, sign]);
},
error: function (a, b, c) {
console.log(c);
}
});
}
/*获取url中的参数*/
function Request(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r == null) {
//window.parent.location.search.substr(1).match(reg); //匹配目标参数
}
if (r != null) return unescape(r[2]);
return null; //返回参数值
}
/*
* 获取用户信息
*/
function _get(key, table, data) {
data = data || user;
table = maptable(table);
// console.log(table+"================");
if (data != undefined) {
table = table || "user";
key = key.toLowerCase();
table = table.toLowerCase();
if (data[table] != undefined) {
if (data[table][key] != undefined) {
return data[table][key];
} else {
return null;
}
}
}
return null;
}
function maptable(key) {
var mp = {
"user": "t1",
"userinfo": "t2",
"userrole": "t3",
"usrsitelevel": "t4",
"union_user": "t5",
"usercontrol": "t6"
};
$.each(mp, function (k, v) {
if (key == v) {
key = k;
return;
}
}
);
return key;
}
/*
* 获取Cookies
*/
// function getCookie(name) {
// Debug("获取Cookies:" + name);
// var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
// if (arr = document.cookie.match(reg)) {
// if(name=="sign"){
// console.log(arr);
// }
// Debug(unescape(arr[2]), "getCookie");
// return unescape(arr[2]);
// } else {
// return null;
// }
// }
function getCookie(name) {
var reg = new RegExp("(^|)("+name+")=([^;]*)(;|$)", 'gi');
var obj={};
document.cookie.replace(reg, (match, p1, p2,p3) => {
// console.log(match, p1, p2,p3)
Object.defineProperty(obj, name, {
value: p3,
enumerable: true,
writable: true
});
return null;
});
return (obj[name]||null);
}
/*
* 设置Cookies
*/
function setCookie(name, value, domain, time) {
if (http + document.domain == base_url) {
//return;
}
Debug("设置Cookies:" + name + "=" + value);
time = time || 3600 * 24 * 30;
var strsec = time;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
// document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
// domain = "changsha.cn" || document.domain;
domain = document.domain;
// domain="changsha.cn";
document.cookie = name + "=" + escape(value) + ";path=/;domain=" + domain + ";expires=" + exp.toGMTString();
}
/*
* 删除Cookies
*/
function delCookie(name, domain) {
Debug("删除Cookies:" + name);
var exp = new Date();
exp.setTime(exp.getTime() - 300);
document.cookie = name + "=;path=/;expires=" + exp.toGMTString();
domain = "changsha.cn" || document.domain;
//domain="changsha.cn";
document.cookie = name + "=;path=/;expires=" + exp.toGMTString() + ";domain=" + domain;
}
/*
* Json对象转换为小写
* */
function JsonLower(data) {
return JSON.parse(JSON.stringify(data).toString().toLocaleLowerCase());
}
// 转为unicode 编码
function encodeUnicode(str) {
var res = [];
for (var i = 0; i < str.length; i++) {
res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
}
return "\\u" + res.join("\\u");
}
// 解码
function decodeUnicode(str) {
str = str.replace(/\\/g, "%");
return unescape(str);
}
function encodeUnicodeJson(json) {
return json;
console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++");
console.log(json);
var values = json.match(/(\:\"([^\x00-\xff])+|(\w)+\")/g);
$.each(values, function (a, b) {
console.log(a + "|" + b + "|" + b.substr(2, b.length - 3) + "====================");
json = json.replace(b.substr(2, b.length - 3), encodeUnicode(b));
});
return json;
console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++");
}
function urlArgs(url) {
var args = {};
var index = url.indexOf('?');
var query = url.substring(index + 1);
var pairs = query.split('&');
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos == -1) {
continue;
} // 如果没找到,就跳过
var name = pairs[i].substr(0, pos); // 获得名称
var value = pairs[i].substr(pos + 1); // 提取value
value = decodeURIComponent(value); // 解码value ,如果地址栏的参数没有转码的话则不需要这一步
args[name] = value;
}
return args
}
function mergeJSON(target, source) {
for (var obj in source) {
target[obj] = source[obj];
}
return target;
}
/*生成GUID*/
function GUID() {
this.date = new Date();
/* 判断是否初始化过,如果初始化过以下代码,则以下代码将不再执行,实际中只执行一次 */
if (typeof this.newGUID != 'function') {
/* 生成GUID码 */
GUID.prototype.newGUID = function () {
this.date = new Date();
var guidStr = '';
sexadecimalDate = this.hexadecimal(this.getGUIDTime(), 16);
sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
for (var i = 0; i < 9; i++) {
guidStr += Math.floor(Math.random() * 16).toString(16);
}
guidStr += sexadecimalDate;
guidStr += sexadecimalTime;
while (guidStr.length < 32) {
guidStr += Math.floor(Math.random() * 16).toString(16);
}
return this.formatGUID(guidStr);
};
/*
* 功能:获取当前日期的GUID格式,即8位数的日期:19700101
* 返回值:返回GUID日期格式的字条串
*/
GUID.prototype.getGUIDDate = function () {
return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay());
};
/*
* 功能:获取当前时间的GUID格式,即8位数的时间,包括毫秒,毫秒为2位数:12300933
* 返回值:返回GUID日期格式的字条串
*/
GUID.prototype.getGUIDTime = function () {
return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10));
};
/*
* 功能: 为一位数的正整数前面添加0,如果是可以转成非NaN数字的字符串也可以实现
* 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串
* 返回值: 如果符合条件,返回添加0后的字条串类型,否则返回自身的字符串
*/
GUID.prototype.addZero = function (num) {
if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
return '0' + Math.floor(num);
} else {
return num.toString();
}
};
/*
* 功能:将y进制的数值,转换为x进制的数值
* 参数:第1个参数表示欲转换的数值;第2个参数表示欲转换的进制;第3个参数可选,表示当前的进制数,如不写则为10
* 返回值:返回转换后的字符串
*/
GUID.prototype.hexadecimal = function (num, x, y) {
if (y != undefined) {
return parseInt(num.toString(), y).toString(x);
} else {
return parseInt(num.toString()).toString(x);
}
};
/*
* 功能:格式化32位的字符串为GUID模式的字符串
* 参数:第1个参数表示32位的字符串
* 返回值:标准GUID格式的字符串
*/
GUID.prototype.formatGUID = function (guidStr) {
var str1 = guidStr.slice(0, 8) + '-',
str2 = guidStr.slice(8, 12) + '-',
str3 = guidStr.slice(12, 16) + '-',
str4 = guidStr.slice(16, 20) + '-',
str5 = guidStr.slice(20);
return str1 + str2 + str3 + str4 + str5;
}
}
}
var center = {
guid: function (isUpper) {
isUpper = false | isUpper;
var guid = new GUID();
guid = guid.newGUID();
if (isUpper) {
guid = guid.toLocaleUpperCase();
}
return guid;
},
loadjs: function (src, stype) {
stype = 1 | stype;
loadjs(src, stype);
},
loadcss: function (src, stype) {
stype = 1 | stype;
loadcss(src, stype);
},
syncookie: function (force) {
return;
if (base_url == http + document.domain) {
return;
}
force = force | false;
var _sign = center.getsign();
var _his = getCookie("his");
// console.log(_sign);
// console.log(_his);
var url = opt.syn_url
+ "&sign=" + _sign
+ "&his=" + _his;
var client_url = opt.syn_session_url
+ "&sign=" + _sign;
if (force == false) {
if (_his == null || _sign == null) {
return;
}
} else {
url = opt.syn_url
+ "&his=" + _his;
client_url = "";
}
// console.log("url",url);
// console.log("client_url",client_url);
// alert(url);
// alert(client_url);
if (url != "") {
// $("body").append("");
}
if (client_url != "") {
$("body").append("");//同步用户BUG
}
$.each(opt.syn_other_url, function (k, v) {
var other_url = v + "/oc/callback.php"
+ "?noredirect=false";
// console.log("other_url:"+other_url);
if (_sign != "") {
other_url += "&sign=" + _sign;
}
if (_his != "") {
other_url += "&his=" + _his;
}
$("body").append("");
});
// console.log("url", url);
// console.log("client_url", client_url);
// console.log("syncookie");
},
//填充表单数据
fillform: function (obj, data) {
$(obj).each(function (k, v) {
try {
var name = $(this).attr("name").replace(/t[0-9]_/, "");
var table = $(this).attr("name").match(/t\d+/g);
var val = _get(name.toLocaleLowerCase(), table, data);
// console.log(k+"|"+v+"|"+name+"|"+table+"|"+$(this).attr("type"));
if ($(this).attr("type") != "hidden" && table != null) {
$(this).val(val);
}
} catch (e) {
// console.log(e);
}
});
},
hasinit: false,//是否初始化过
/**初始化接口
* _oc_base_domain 域名
* oc_obj_id 显示登录对象
* oc_qr_obj_id 显示二维码对象
* options 参数
*/
init: function (_oc_base_domain, oc_obj_id, oc_qr_obj_id, options) {
// console.log("init oc");
oc_obj_id = oc_obj_id || "loginbox";
oc_qr_obj_id = oc_qr_obj_id || "loginQRCODE";
oc_obj = "#" + oc_obj_id;
oc_qr_obj = "#" + oc_qr_obj_id;
base_url = _oc_base_domain || base_url;
oc_url = base_url + "/OcApi/";
var normal_opt = {
//常规参数
isDebug: false,//是否启用调试 默认为关闭
PHPSESSID: getSessionID(),//SESSIONID
base_url: base_url,//接口域名
oc_qr_obj_id: oc_qr_obj_id,//二维码对象ID
type: "wx_web",//启用微信登录
//同步接口
syn_url: oc_url + "?action=synCookies",//同步COOKIE接口SESSION和COOKIE
syn_session_url: oc_callback + "&noredirect=false",//同步应用SESSION和COOKIE
syn_other_url: {},//同步其它应用SESSION和COOKIE
};
var defaultopt = {
//短信接口
sms_api: getBaseUrl("synSendSms"),//发送短信接口
sms_code: getBaseUrl("synSendSmsCode"),//发送短信验证码接口
sms_check: getBaseUrl("synCheckSmsCode"),//验证短信验证码接口
//二维码登录参数
listencodeurl: getBaseUrl("synGetCodeApi"),//二维码登录监听接口
gencodeurl: getBaseUrl("synGenCodeApi"),//获取登录二维码接口
gencodeqrurl: getBaseUrl("showLoginQR"),//显示登录二维码URL
//登录参数
loginapiurl: getBaseUrl("synLoginApi"),//登录接口
loginurl: getBaseUrl("showLogin"),//显示登录页面URL
logouturl: getBaseUrl("synLogout"),//退出接口
//注册参数
regurl: getBaseUrl("showRegist"),//显示注册用户URL
reguserapi: getBaseUrl("synRegUserApi"),//注册用户接口
token: getBaseUrl("synUserToken"),//会话更新
//用户信息参数
getuserurl: getBaseUrl("synGetuser"),//获取用户信息接口
authurl: getBaseUrl("synAuthApi"),//认证用户信息接口
updateurl: getBaseUrl("showUpdate"),//显示修改信息页面URL
updateapi: getBaseUrl("synUpdateApi"),//显示修改信息页面URL
//模板参数
qrcode_template: '
',//二维码显示模板
// loginstate_normal_template: "
" +
// " 登录 注册",//登录状态显示模板未登录
loginstate_normal_template: "
" +
" 登录 注册",//登录状态显示模板未登录
loginstate_ucenter_template: "{[user_UserName]}[{[userInfo_NickName]}]|修改|退出"//登录状态显示模板未登录
};
$.extend(defaultopt, normal_opt);
$.extend(defaultopt, options);
opt = defaultopt;
isDebug = opt.isDebug;
if (opt.type == "wx_web") {
opt.loginapiurl += "&type=wx_web";
opt.loginurl += "&type=wx_web";
}
Debug(opt);
try {
center.getsign();
center.checklogin();
} catch (e) {
console.log(e);
}
Debug("初始化参数");
Debug(opt, "Init");
center.briagesign().then(briage_sign=>{
if(briage_sign){
delCookie("sign");
setCookie("sign", briage_sign);
console.log("briage_sign",briage_sign)
}
});
$(document).ready(function () {
var html = center.replacetemplate(opt.qrcode_template);
// $(oc_obj).parent().append(html);
// $("body").append(html);
$(oc).trigger("inited", []);
});
center.hasinit = true;
},
briagesign:function(){
return new Promise(function (res, rej) {
try {
console.log("briagesign");
bridgeImpl.getUserInfo(function (data) {
console.log(data);
data=data.replace(/O0O0O/g, "=")//=号
.replace(/o000o/g, "+")//+号
.replace(/oo00o/g, "/");// /号
userInfo = JSON.parse(Base64.decode(data)); //由JSON字符串转换为JSON对象
var briage_sign = userInfo.userSign;
// alert("briage_sign:"+briage_sign);
// bridgeImpl.showMsg(JSON.stringify(userInfo),false);
if (briage_sign != undefined && briage_sign != "") {
res(briage_sign);
}
$(oc).trigger("onbridge", [userInfo, briage_sign]);
}, function (e) {
rej(e);
// console.log(e)
});
} catch (e) {
res();
// rej(e)
// console.log(e)
}
})
},
replacetemplate: function (str) {
var html = str;
html = html.replace(/\{loginurl\}/g, opt.loginurl);
html = html.replace(/\{base_url\}/g, opt.base_url);
html = html.replace(/\{logouturl\}/g, opt.logouturl);
html = html.replace(/\{regurl\}/g, opt.regurl);
html = html.replace(/\{oc_qr_obj_id\}/g, opt.oc_qr_obj_id);
html = html.replace(/\{updateurl\}/g, opt.updateurl);
var data = html.match(/\{\[(\w+)\]\}/ig);
$(data).each(function (k, v) {
var vkey = v.replace(/\{\[|\]\}/ig, "");
var arr = vkey.split("_");
html = html.replace(v, center.get(arr[1], arr[0]));
});
return html;
},
option: function () {
return opt;
},
/*显示登录二维码*/
getQRCode: function () {
Debug("显示登录二维码");
var frm_box = $(oc_qr_obj);
$(frm_box).css("left", $(document).width() / 2 - $(frm_box).width() / 2);
$(frm_box).css("top", $(document).height() / 2 - $(frm_box).height());
var frm = $(frm_box).find("iframe");
$(frm).attr("src", opt.gencodeqrurl);
$(frm_box).show();
$(oc_qr_obj).find(".RefreshQRCode").on("click", function () {
$(frm).attr("src", opt.gencodeqrurl);
});
center.ListenCodeLogin();
},
/*检测登录*/
checklogin: function () {
Debug("检测登录");
// console.log("checklogin");
setCookie("his", window.location.href);
this.showState();
center.getsign();
$(oc).trigger("onchecklogin", [null, sign]);
this.AuthApi();
},
gen_mac_sn: function (code) {
var url = oc_url + "?action=gen_mac_code&sn=" + code;
$("body").append("
");
},
getsign: function () {
center.briagesign().then(briage_sign=>{
if(briage_sign){
delCookie("sign");
setCookie("sign", briage_sign);
console.log("briage_sign",briage_sign)
}
});
sign = Request("sign")||getCookie("sign");
return sign;
},
/*检测是否登录*/
state: function () {
return center.getsign();
},
hasAuth: false,//是否认证
/*认证用户*/
AuthApi: function () {
// console.log("AuthApi");
Debug("认证用户");
var _sign = center.getsign();
// center.showState(oc.oc_obj);
console.log(_sign + "===================");
if (_sign == null || _sign == undefined || _sign == "") {
center.syncookie(true);
return;
}
if (user != null || user != undefined) {
$(oc).trigger("onAuthApi", [pub_data, _sign]);
return;
}
if (center.hasAuth == true) {
//锁定请求
return;
}
center.hasAuth = true;
center.ajax({
type: "post",
url: opt.authurl,
data: { "sign": _sign },
dataType: "json",
success: function (data) {
//var rect=JsonLower(data.rect);
var rect = data.rect;
// alert(JSON.stringify(data.rect));
if (data.code == "yes") {
user = rect;
pub_data = data;
center.syncookie();
} else {
user = null;
pub_data = null;
delCookie("sign");
}
center.showState(oc.oc_obj);
$(oc_qr_obj).hide("slow");
$(oc).trigger("onAuthApi", [data, _sign]);
},
error: function (a, b, c) {
Debug(c, "AuthApi");
}
});
center.showState(oc.oc_obj);
}
,
Token:function(){
var _sign = center.getsign();
center.ajax({
type: "get",
url: opt.token,
data: { "sign": _sign },
dataType: "json",
success: function (data) {
//var rect=JsonLower(data.rect);
var rect = data.rect;
// alert(JSON.stringify(data.rect));
if (data.code == "yes") {
user = rect;
pub_data = data;
center.syncookie();
} else {
user = null;
pub_data = null;
delCookie("sign");
}
$(oc).trigger("onToken", [data, _sign]);
},
error: function (a, b, c) {
Debug(c, "Token");
}
});
},
//发送验证码
SendCode: function (phone, codetemplate, len, verify) {
Debug("登录接口");
verify = verify || "星辰在线";
len = len || 6;
codetemplate = codetemplate || "您的验证码:[code]";
center.ajax({
type: "post",
url: opt.sms_code,
data: { "phone": phone, "codetemplate": codetemplate, "verify": verify, "len": len },
dataType: "json",
success: function (data) {
var rect = data.rect;
// alert(JSON.stringify(data));
setCookie("code_sid", data.session_id);
$(oc).trigger("onSendCode", [data]);
},
error: function (a, b, c) {
Debug(c, "SendCode Error");
}
});
},
//验证验证码
AuthSmsCode: function (code, phone) {
Debug("验证验证码");
center.ajax({
type: "post",
url: opt.sms_check,
data: { "PHPSESSID": getCookie("code_sid"), "code": code, "phone": phone },
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
$(oc).trigger("onAuthSmsCode", [data]);
},
error: function (a, b, c) {
Debug(c, "AuthSmsCode Error");
}
});
},
Login: function (username, userpass, siteid) {
center.LoginForm({ "username": username, "issafe":1,"userpass": userpass, "siteid": siteid });
},
LoginForm: function (data) {
Debug("登录接口");
center.ajax({
type: "post",
url: opt.loginapiurl,
data: data,
dataType: "json",
success: function (data) {
// var rect=JsonLower(data.rect);
var rect = data.rect;
// alert(JSON.stringify(data.rect));
if (data.code == "yes") {
user = rect;
setCookie("sign", data.sign);
} else {
user = null;
}
$(oc).trigger("onLogin", [data, data.sign]);
},
error: function (a, b, c) {
Debug(c, "Login Error");
}
});
},
//用户注册接口
Registor: function (data) {
Debug("注册接口", "Registor");
center.ajax({
type: "post",
url: opt.reguserapi,
data: data,
dataType: "json",
success: function (data) {
// var rect=JsonLower(data.rect);
var rect = data.rect;
if (data.code == "yes") {
user = rect;
setCookie("sign", data.sign);
} else {
user = null;
}
$(oc).trigger("onRegistor", [data, data.sign]);
},
error: function (a, b, c) {
Debug(c, "Registor Error");
}
});
},
//用户注册接口
UpdateUser: function (data) {
Debug("修改用户资料" + opt.updateapi, "UpdateUser");
center.ajax({
type: "post",
url: opt.updateapi,
data: { "data": data, "sign": center.getsign() },
dataType: "json",
success: function (data) {
var rect = data.rect;
if (data.code == "yes") {
user = rect;
} else {
user = null;
}
$(oc).trigger("onUpdateUser", [data, data.sign]);
},
error: function (a, b, c) {
Debug(c, "UpdateUser Error");
}
});
},
//用户注册接口
Request: function (url,data,type,callback) {
data=$.extend({"data": data, "sign": center.getsign()},data);
return center.ajax({
type: type||"post",
url: url,
data: data,
dataType: "json",
success: function (data) {
if(callback) callback(data);
},
error: function (a, b, c) {
}
});
},
UpdatePage: function () {
Debug("更新接口");
//delCookie("sign");
//delCookie("his");
console.log(opt.updateurl);
window.location = opt.updateurl;
},
RegPage: function () {
Debug("注册接口");
//delCookie("sign");
//delCookie("his");
console.log(opt.regurl);
window.location = opt.regurl;
},
LoginPage: function () {
Debug("登录接口");
//delCookie("sign");
//delCookie("his");
console.log(opt.loginurl);
// setCookie("his",window.location.href);
window.location = opt.loginurl;
},
Logout: function () {
Debug("退出接口");
//delCookie("sign");
//delCookie("his");
console.log(opt.logouturl);
setCookie("his", window.location.href);
window.location = opt.logouturl;
var data = { "code": "yes", "msg": "退出成功" };
$(oc).trigger("onLogout", [data]);
}
,
BindState: function (type, callback) {
if (user["unionuser"] == undefined) {
return;
}
type = type || "quan";
var arr = [];
$(user["unionuser"]).each(function (k, v) {
if (v["fromtype"] == type) {
// console.log(v);
if (callback === undefined) {
$(oc).trigger("onBindState", [v, true]);
} else {
callback(v, true);
}
return true;
}
});
},
/*监听二维码登录*/
ListenCodeLogin: function () {
Debug("监听二维码登录");
center.ajax({
type: "post",
url: opt.listencodeurl,
data: { "PHPSESSID": getCookie("SID") },
dataType: "json",
success: function (data) {
//var rect=JsonLower(data.rect);
var rect = data.rect;
if (data.code == "yes") {
if (data.sign != null) {
sign = data.sign;
$(oc_qr_obj).find(".RefreshQRCode").html(data.msg);
setCookie("sign", data.sign);
CheckQR_Flag = true;
setTimeout(center.AuthApi(), 6000);
if (data.callback != undefined) {
window.location = data.callback;
} else {
window.location = window.location;
}
Debug("二维码登录成功");
}
}
$(oc).trigger("onListenCodeLogin", [data, sign]);
if (!CheckQR_Flag) {
setTimeout(center.ListenCodeLogin, 6000);
}
},
error: function (a, b, c) {
console.log(c);
if (!CheckQR_Flag) {
setTimeout(center.ListenCodeLogin, 6000);
}
}
});
}
,
/*显示状态*/
showState: function () {
Debug("显示状态");
var loginstate = "";
try {
if (sign == "" || sign == null || user == null) {
loginstate = center.replacetemplate(opt.loginstate_normal_template);
} else {
// Debug(user);
loginstate = center.replacetemplate(opt.loginstate_ucenter_template);
$(oc).trigger("onshowState", [user, sign]);
}
} catch (e) {
}
// alert(loginstate);
$(oc_obj).html(loginstate);
},
/*获取用户信息*/
getuser: function () {
Debug("获取用户信息");
if (center.getsign() == null) {
return;
}
center.ajax({
type: "post",
url: opt.getuserurl,
data: { "sign": center.getsign() },
dataType: "json",
success: function (data) {
if (user == null || user == undefined) {
user = data.rect;
pub_data = data;
}
$(oc).trigger("ongetuser", [data, sign]);
}
});
}
,
//获取数据对象
data: function (isFormat) {
var data = null;
isFormat = isFormat || true;
try {
data = pub_data.rect;
if (isFormat) {
data = JSON.stringify(data);
}
} catch (e) {
}
return data;
},
//获取数据对象数据
data_sign: function () {
var data = null;
try {
data = { "sign": pub_data.data_sign, "data": pub_data.rect };
} catch (e) {
data = { "sign": null, "data": null };
}
return data;
},
//获取用户数据
get: function (key, table, data) {
return _get(key, table, data);
},
//获取COOKIE
cookie: function (key) {
return getCookie(key);
},
mergeJSON: function (main, source) {
return mergeJSON(main, source)
},
urlArgs: function (url) {
return urlArgs(url);
},
//调用远程数据接口
ajax: function (option, callback) {
var _url = option.url.split("?")[0];
var _data = urlArgs(option.url);
option.data = option.data || [];
_data = mergeJSON(_data, option.data);
option.url = _url;
option.data = _data;
// console.log(_url);
// console.log(option.data);
// console.log(_data);
var args = {
url: option.url,
type: option.type || "post",
data: option.data,
dataType: option.dataType || "json",
addData: false,//附加签名
addCookie: false,//附加Cookie
// xhrFields:{
// withCredentials:true
// },
success: function (data, state) {
if (typeof callback === "function") {
callback(data, state, null, option);
} else {
$(oc).trigger(callback, [data, state, null, option]);
}
},
error: function (data, state, error) {
if (typeof callback === "function") {
callback(data, state, error, option);
} else {
$(oc).trigger(callback, [data, state, error, option]);
}
}
};
$.extend(args, option);
//附加签名数据
if (args.addData) {
args.data["__sign"] = center.getsign();
args.data["__data_sign"] = center.data_sign().sign;
args.data["__signdata"] = center.data_sign().data;
}
// console.log(args);
//附加Cookies数据
if (args.addCookie) {
var _cookie = document.cookie;
_cookie = _cookie.replace(/\s+/ig, '');
_cookie = _cookie.replace(/;/ig, '","');
_cookie = _cookie.replace(/=/ig, '":"');
_cookie = '{"' + _cookie + '"}';
_cookie = JSON.parse(_cookie);
args.data["__cookies"] = _cookie;
}
$.ajax(args);
},
//调试接口
Debug: function (log, flag) {
if (opt.isDebug) {
Debug(log, flag);
}
},
/*测试*/
test: function () {
Debug("测试");
Debug(opt);
Debug("oc_url:" + oc_url);
Debug("oc_obj:" + oc_obj);
Debug("oc_qr_obj:" + oc_qr_obj);
}
};
return center;
})(window.jQuery || $);
/*
* JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/* global define */
(function ($) {
'use strict';
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRotateLeft(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt))
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b)
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn((b & c) | ((~b) & d), a, b, x, s, t)
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & (~d)), a, b, x, s, t)
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t)
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | (~d)), a, b, x, s, t)
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binlMD5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i;
var olda;
var oldb;
var oldc;
var oldd;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i;
var output = '';
var length32 = input.length * 32;
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i;
var output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0
}
var length8 = input.length * 8;
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32)
}
return output
}
/*
* Calculate the MD5 of a raw string
*/
function rstrMD5(s) {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8))
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstrHMACMD5(key, data) {
var i;
var bkey = rstr2binl(key);
var ipad = [];
var opad = [];
var hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binlMD5(bkey, key.length * 8)
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C
}
hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binlMD5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hexTab = '0123456789abcdef';
var output = '';
var x;
var i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hexTab.charAt((x >>> 4) & 0x0F) +
hexTab.charAt(x & 0x0F)
}
return output
}
/*
* Encode a string as utf-8
*/
function str2rstrUTF8(input) {
return unescape(encodeURIComponent(input))
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function rawMD5(s) {
return rstrMD5(str2rstrUTF8(s))
}
function hexMD5(s) {
return rstr2hex(rawMD5(s))
}
function rawHMACMD5(k, d) {
return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d))
}
function hexHMACMD5(k, d) {
return rstr2hex(rawHMACMD5(k, d))
}
function md5(string, key, raw) {
if (!key) {
if (!raw) {
return hexMD5(string)
}
return rawMD5(string)
}
if (!raw) {
return hexHMACMD5(key, string)
}
return rawHMACMD5(key, string)
}
if (typeof define === 'function' && define.amd) {
define(function () {
return md5
})
} else if (typeof module === 'object' && module.exports) {
module.exports = md5
} else {
$.md5 = md5
}
}(this));