| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703 |
- import { getStorageDecryptData, setStorageEncryptData } from "@/utils/request";
- var wx_code = "",
- ticket = "", //票据
- accessToken = "",
- userInfo = {}, //用户信息
- AppInfo = {}, //应用参数
- deviceInfo = {}, //设备信息
- errorCode = null, //错误码
- responseText = "", //错误提示
- rootDirLocation = ""; //本地文件路劲
- async function onLogin(env) {
- //igw相关参数赋值
- AppInfo = {
- agentid: env.VUE_APP_AGENTID,
- corpid: env.VUE_APP_CORPID,
- isc_appid: env.VUE_APP_ISCAPPID,
- isc_secret: env.VUE_APP_ISCSECRET,
- ip: env.VUE_APP_IP,
- iscpPort: env.VUE_APP_ISCPPORT,
- iscpIP: env.VUE_APP_TSCPIP,
- user: env.VUE_APP_USER,
- baseUrlIp: env.VUE_APP_BASEURLIP,
- baseUrlPort: env.VUE_APP_BASEURLPORT,
- appId: env.VUE_APP_APPID,
- url_wxcode: env.VUE_APP_URL_WXCODE,
- url_ticket: env.VUE_APP_URL_TICKET,
- url_accesstoken: env.VUE_APP_URL_ACCESSTOKEN,
- url_userinfo: env.VUE_APP_URL_USERINFO,
- result: "",
- };
- return new Promise(async (resolve, reject) => {
- try {
- //获取设备信息
- await getDeviceInfo();
- wx_code = await getParam("code");
- if (wx_code) {
- //获取票据
- ticket = await getTicket();
- //获取安全交互平台的端口
- AppInfo.result = await get_ext_ISCP();
- sessionStorage.setItem("IPW_ISCP_PORT", AppInfo.result);
- if (env.NODE_ENV == "production") {
- //生产环境
- //获取密钥信息
- var myWords = await getIsolationdmc();
- sessionStorage.setItem("YDZY_APP_ISOLATIONDMC", myWords);
- //获取isc用户信息
- userInfo = await getUser();
- } else {
- //uat环境
- accessToken = await getAccessToken();
- userInfo = await getUserinfo();
- }
- resolve(userInfo);
- } else {
- //获取wxcode
- getWxCode();
- }
- } catch (error) {
- errorCode = error;
- reject(errorCode);
- }
- });
- }
- async function getParam(variable) {
- try {
- // isAndroid()
- let code = await getAuthCode();
- console.log("使用单点登录获取code成功", code)
- return code;
- } catch (error) {
- console.log("单点登录失败,使用URL参数获取", error)
- }
- let query = window.location.search.substring(1);
- let vars = query.split("&");
- console.log("单点登录获取code失败,使用微信跳转换取code", vars)
- for (let i = 0; i < vars.length; i++) {
- var pair = vars[i].split("=");
- if (pair[0] == variable) {
- return pair[1];
- }
- }
- return "";
- }
- /**
- *
- * 获取i国网的code(授权码) 替换之前getWxCode()需要 重定向页面获取wx_code
- *
- */
- function getAuthCode() {
- return new Promise((resolve, reject) => {
- wx.ready(function () {
- wx.invoke(
- "getAuthCode",
- {
- response_type: 'code', //固定值
- scope: 'snsapi_base' //固定值
- },
- function (res) {
- console.log("wx_code获取 res:", JSON.stringify(res))
- if (res.err_msg === 'getAuthCode:ok') {
- wx_code = res.code;
- resolve(res.code)
- } else {
- reject(res)
- }
- }
- );
- });
- });
- }
- // 获取密钥信息
- function getIsolationdmc() {
- // const TyEvent4006 = window.TINGYUN.createAutoEvent({
- // key: 'getIsolationdmc-4006'
- // })
- return new Promise((resolve, reject) => {
- $.ajax({
- type: "GET",
- url: "http://127.0.0.1:" + AppInfo.result + "/test.txt",
- success: function (res) {
- //更改路径之后接口返回的加密串末尾多了2个空格,导致无法解密,手动去掉
- if (res) {
- var words = res.split(",");
- var myWords = mydecrypt(words[0], words[1].trim());
- // TyEvent4006.end();
- resolve(myWords);
- } else {
- responseText = JSON.stringify(res);
- // TyEvent4006.fail();
- reject(4006);
- }
- },
- error: function (err) {
- console.log("生成秘钥失败:", err)
- responseText = JSON.stringify(err);
- // TyEvent4006.fail();
- reject(4006);
- },
- });
- });
- }
- function isAndroid() {
- console.log("是安卓:", navigator.userAgent.indexOf("Android") > -1)
- return navigator.userAgent.indexOf("Android") > -1;
- }
- function getWxCode() {
- console.log("code:" + wx_code);
- let sURL = AppInfo.url_wxcode;
- sURL += "appid=" + AppInfo.corpid;
- sURL +=
- "&redirect_uri=" + encodeURIComponent("zipapp://local.host/index.html");
- sURL += "&response_type=code";
- sURL += "&scope=SCOPE";
- sURL += "&state=STATE";
- sURL += "&agentid=" + AppInfo.agentid;
- sURL += "#wechat_redirect";
- location.href = sURL;
- }
- async function getTicket() {
- // const TyEvent4001 = window.TINGYUN.createAutoEvent({
- // key: 'getTicket-4001'
- // })
- return new Promise((resolve, reject) => {
- var _data = {
- appId: AppInfo.agentid,
- CODE: wx_code,
- };
- console.log("获取一次性票据:", _data);
- $.ajax({
- type: "post",
- data: JSON.stringify(_data),
- contentType: "application/json;charset=utf-8",
- url: AppInfo.url_ticket,
- dataType: "json",
- async: true,
- cache: false,
- success: function (res) {
- if (res.data && res.data.ticket) {
- console.log("获取票据成功:", res);
- // TyEvent4001.end();
- resolve(res.data.ticket);
- } else {
- //_data参数异常时,上报的res字符串信息
- // TyEvent4001.fail();
- console.log("获取一次性票据失败", res);
- responseText = JSON.stringify(res);
- reject(4001);
- }
- },
- error: function (err) {
- console.log("获取一次性票据err", err);
- // TyEvent4001.fail();
- //err对象里 无其他信息
- responseText = '获取一次性票据error';
- reject(4001);
- },
- });
- });
- }
- /** ------------------------分割线 上面步骤为登录,下面步骤为获取用户。根据实际情况选择是否只执行上两步,还是全部流程------------------------**/
- // 第三步: 获取接口凭证 accessToken
- // accessToken 2个小时内有效,失效前5分钟能获取到新的两个小时有效期token, 为了减少开销 建议保存到本地
- //
- // 参数说明:(无特殊说明参数可复用)
- // appId 是应用创建生成的 isc appid
- // clientSecret 是应用创建生成的 isc secret
- // 请求头 X-Clientid 是应用创建生成的 isc appid
- // 请求头 X-Acloud-Data-Sign 是对请求参数的 sm3 加密串
- function getAccessToken() {
- return new Promise((resolve) => {
- var params = {
- appId: AppInfo.isc_appid,
- clientSecret: AppInfo.isc_secret,
- };
- params = JSON.stringify(params);
- var DataSign = Sm3Utils.encryptFromText(params);
- $.ajax({
- url: AppInfo.url_accesstoken,
- headers: {
- "Content-Type": "application/json;charset=utf8",
- Accept: "*/*",
- "X-Clientid": AppInfo.isc_appid,
- "X-Acloud-Data-Sign": DataSign,
- },
- type: "POST",
- data: params,
- success: function (res) {
- if (res.code === "100001") {
- console.log("accessToken" + res);
- resolve(res.data.accessToken);
- }
- },
- error: function (err) {
- console.log(err);
- },
- });
- });
- }
- // 第四步:获取用户信息
- // 参数说明:(无特殊说明参数可复用)
- // appId 是应用创建生成的 isc appid
- // service 是应用创建时编辑的应用主页
- // ticket 是第三步返回数据中的 accessToken
- // 请求头 X-Acloud-Data-Sign 是对请求参数的 sm3 加密串
- // 请求头 X-ISC-AccessToken 中的 AccessToken 是第三步返回数据中的 accessToken
- // 注意: 'X-ISC-AccessToken': 'Client ' + AccessToken 的 Client后必须用空格 与 AccessToken隔离
- function getUserinfo() {
- return new Promise((resolve) => {
- var params = {
- appId: AppInfo.isc_appid,
- service: `zipapp://appid.${AppInfo.agentid}/index.html`,
- ticket: ticket,
- };
- params = JSON.stringify(params);
- var DataSign = Sm3Utils.encryptFromText(params);
- $.ajax({
- url: AppInfo.url_userinfo,
- headers: {
- "Content-Type": "application/json;charset=utf8",
- "X-ISC-AccessToken": "Client " + accessToken,
- Accept: "*/*",
- "X-Clientid": AppInfo.isc_appid,
- "X-Acloud-Data-Sign": DataSign,
- },
- type: "POST",
- data: params,
- success: function (res) {
- if (res.code === "100001") {
- console.log("userinfo" + res);
- // ! need delete
- sessionStorage.setItem(
- "IPW_ISC_ACCOUNTINFO",
- JSON.stringify(res.data)
- );
- setStorageEncryptData("IPW_ISC_ACCOUNTINFO_SECRET", res.data);
- resolve({
- userId: res.data.userId,
- account: res.data.account,
- });
- }
- },
- });
- });
- }
- /** get_ext_ISCP 获取安全交互平台返回信息 */
- function get_ext_ISCP() {
- console.log("ext_ISCP_Init: iscpIP ---:" + AppInfo.iscpIP);
- // const TyEvent4003 = window.TINGYUN.createAutoEvent({
- // key: 'get-ext-ISCP-4003'
- // })
- // const TyEvent4004 = window.TINGYUN.createAutoEvent({
- // key: 'ext-ISCP-GetLocalPort-4004'
- // })
- // const TyEvent4005 = window.TINGYUN.createAutoEvent({
- // key: 'ext-ISCP-GetLocalPort-4005'
- // })
- return new Promise((resolve, reject) => {
- // wx.ready(function () {
- // console.log('准备:wx.config: ready');
- // wx.invoke(
- // 'agentConfig',
- // {
- // agentid: AppInfo.agentid, // 必填,企业应用的agentid
- // corpid: AppInfo.corpid, // 必填,企业微信的corpid
- // timestamp: new Date().valueOf() / 1000, // 必填,生成签名的时间戳,int类型, 如
- // nonceStr: '', // 必填,生成签名的随机串
- // signature: '' // 必填,签名,见附录5
- // },
- // function (res) {
- // console.log('agentConfig:', res);
- // if (res.err_msg != 'agentConfig:ok') {
- // reject(4002)
- // }
- console.log("ext_ISCP_Init 初始化参数iscpIP:", AppInfo.iscpIP);
- wx.invoke(
- "ext_ISCP_Init",
- {
- // 初始化交互安全平台
- data: {
- iscpIP: AppInfo.iscpIP,
- },
- },
- function (res) {
- console.log("ext_ISCP_Init 初始化返回:", res);
- if (res.err_msg === "ext_ISCP_Init:ok") {
- // TyEvent4003.end();
- var para = {
- ip: AppInfo.ip, //安全交互平台互联网ip,从对接方获取
- port: AppInfo.iscpPort, //安全交互平台互联网port,从对接方获取
- user: AppInfo.user, //当前登录用户id,可写死
- appid: AppInfo.appId, //需要向安全交互平台申请
- iscpIP: AppInfo.iscpIP, //链路唯一标识,自己生成(建议赋值为AgentID)
- };
- console.log("ext_ISCP_ConnectService 建立链接参数: ", para);
- wx.invoke(
- "ext_ISCP_ConnectService",
- {
- // 建立安全交互平台链接
- data: para,
- },
- function (res) {
- console.log("ext_ISCP_ConnectService 建立链接返回:", res);
- if (res.err_msg === "ext_ISCP_ConnectService:ok") {
- let _data = {
- ip: AppInfo.baseUrlIp,
- port: AppInfo.baseUrlPort,
- iscpIP: AppInfo.iscpIP,
- appid: AppInfo.appId,
- };
- // TyEvent4004.end();
- console.log("ext_ISCP_GetLocalPort 转换端口参数:", _data);
- wx.invoke(
- "ext_ISCP_GetLocalPort",
- {
- // 转换端口
- data: _data,
- },
- function (res) {
- console.log("ext_ISCP_GetLocalPort 转换端口返回:", res);
- if (res.err_msg === "ext_ISCP_GetLocalPort:ok") {
- AppInfo.result = res.result;
- // TyEvent4005.end();
- resolve(res.result);
- console.log("**getZipAppDirectory");
- wx.invoke(
- "getZipAppDirectory",
- {
- type: "APP_ROOT_DIR",
- },
- function (res) {
- console.log("getZipAppDirectory end", res);
- if (res.err_msg === "getZipAppDirectory:ok") {
- rootDirLocation = res.directory;
- sessionStorage.setItem(
- "ROOT_DIR_LOCATION",
- res.directory
- );
- } else {
- console.log("getZipAppDirectory end 获取本地路径失败:", res)
- }
- }
- );
- } else {
- // TyEvent4005.fail();
- responseText = JSON.stringify(res);
- // responseText = `err_msg:${res.err_msg} - result:${res.result} - exception:${res.exception}`
- reject(4005);
- }
- }
- );
- } else {
- // TyEvent4004.fail();
- responseText = JSON.stringify(res);
- // responseText = `err_msg:${res.err_msg} - result:${res.result} - UUID:${res.UUID}`
- reject(4004);
- }
- }
- );
- } else {
- // TyEvent4003.fail();
- responseText = JSON.stringify(res);
- reject(4003);
- }
- }
- );
- // }
- // );
- // window.uexOnload && window.uexOnload(0);
- // });
- // wx.config({
- // beta: true, // 调用wx.invoke形式的接口值时,该值必须为true。
- // debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
- // appId: AppInfo.corpid, // 必填,政务微信的cropID
- // timestamp: '1608692903', // 必填,生成签名的时间戳
- // nonceStr: 'XKIvykvwOuAeIbl', // 必填,生成签名的随机串
- // signature: 'ad0c077e6b5fbfe0c9e5394703d8262a3bc21fc3', // 必填,签名,见附录1
- // jsApiList: [
- // 'multiWindows_open',
- // 'multiWindows_close',
- // 'multiWindows_subscribe',
- // 'multiWindows_publish',
- // 'multiWindows_finish',
- // 'chooseImage',
- // 'scanQRCode',
- // 'hideOptionMenu',
- // 'shareWechatMessage',
- // 'shareAppMessage',
- // 'startAutoLBS',
- // 'stopAutoLBS',
- // 'onLocationChange',
- // 'onMenuShareAppMessage',
- // 'onMenuShareWechat',
- // 'previewFile',
- // 'openChatWithMsg',
- // 'ext_Database_Open',
- // 'ext_Database_Exec',
- // 'ext_Database_Query',
- // 'ext_Database_Close',
- // 'ext_ISCP_Init',
- // 'ext_ISCP_ConnectService',
- // 'ext_ISCP_GetLocalPort',
- // 'ext_ISCP_Close',
- // 'ext_ISCP_Status',
- // 'ext_screenControl_direction',
- // 'getLocation',
- // "getZipAppDirectory",
- // "multiWindows_open",
- // "ext_DeviceInfo_GetInfo",
- // "ext_DeviceInfo_version"
- // ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
- // });
- });
- }
- //通过安全交互平台认证之后调后端接口获取用户信息
- // function getUser() {
- // if (!AppInfo.result) {
- // alert('请先获取交互平台信息');
- // return;
- // }
- // var url = 'http://127.0.0.1:' + AppInfo.result + '/yjapp/service/indexToDefect';
- // return new Promise((resolve) => {
- // var params = {
- // index: 5,
- // formData: JSON.stringify({
- // serviceTicket: ticket
- // }),
- // requestURL: '/',
- // requestMethod: 'GET'
- // };
- // $.ajax({
- // type: 'post',
- // url: url,
- // data: params,
- // success: function (response) {
- // console.log('Got USER', response.data.userId);
- // console.log('Got USER', response.data.account);
- // resolve({
- // userId: response.data.userId,
- // account: response.data.account
- // });
- // },
- // error: function (response) {
- // fail();
- // console.log('fail:' + response);
- // console.error(response);
- // }
- // });
- // });
- // }
- //通过安全交互平台认证之后调后端接口获取用户信息
- function getUser() {
- if (!AppInfo.result) {
- alert("请先获取交互平台信息");
- return;
- }
- // const TyEvent4007 = window.TINGYUN.createAutoEvent({
- // key: 'getUser-4007'
- // })
- // const TyEvenGetUserOther = window.TINGYUN.createAutoEvent({
- // key: 'getUser-other'
- // })
- var url = "http://127.0.0.1:" + AppInfo.result + "/igw-isc/isc/ipw";
- return new Promise((resolve, reject) => {
- var params = {
- serviceTicket: ticket,
- };
- $.ajax({
- type: "post",
- url: url,
- data: JSON.stringify(params),
- contentType: "application/json",
- dataType: "json",
- success: function (response) {
- //token
- sessionStorage.setItem(
- "IPW_UC_TOKEN",
- response.data.ipwToken.resultValue.value
- );
- // ! need delete
- //isc用户信息
- sessionStorage.setItem(
- "IPW_ISC_ACCOUNTINFO",
- JSON.stringify(response.data.iscInfo)
- );
- setStorageEncryptData("IPW_ISC_ACCOUNTINFO_SECRET", response.data.iscInfo);
- // TyEvent4007.end();
- // TyEvenGetUserOther.end();
- resolve({
- userId: response.data.iscInfo.userId,
- account: response.data.iscInfo.account,
- });
- },
- error: function (response) {
- console.log("===============getUser response", response)
- let tempCode;
- if (response.responseJSON && response.responseJSON.code) {
- if (response.responseJSON.code === -1) {
- tempCode = 1001;
- response.responseText = "serviceTicket参数不能为空"
- } else {
- //3002 应该是response.responseJSON.code赋予的
- tempCode = response.responseJSON.code;
- }
- // TyEvenGetUserOther.fail();
- } else {
- // TyEvent4007.fail();
- tempCode = 4007;
- //4007的响应体 特殊处理
- responseText = JSON.stringify(response);
- reject(tempCode);
- }
- responseText = response.responseText
- ? response.responseText
- : response.status
- ? response.status
- : "";
- reject(tempCode);
- },
- });
- });
- }
- //获取设备信息接口
- // 参数
- // 属性 类型 说明
- // err_msg String 方法是否成功依据
- // deviceUUID String 设备IMEI(获得不到则返回UUID)
- // deviceOS String 操作系统
- // deviceManufacturers String 厂商信息
- // deviceType String 设备机型
- // devicePlatform String 平台类型
- // isPhone String 设备种类
- // macAddress String 获取mac地址
- // lang String 获取系统语言
- function getDeviceInfo() {
- // const TyEvent4002 = window.TINGYUN.createAutoEvent({
- // key: 'getDevice-4002'
- // })
- return new Promise((resolve, reject) => {
- wx.ready(function () {
- console.log("准备:wx.config: ready");
- wx.invoke(
- "agentConfig",
- {
- agentid: AppInfo.agentid, // 必填,企业应用的agentid
- corpid: AppInfo.corpid, // 必填,企业微信的corpid
- timestamp: new Date().valueOf() / 1000, // 必填,生成签名的时间戳,int类型, 如
- nonceStr: "", // 必填,生成签名的随机串
- signature: "", // 必填,签名,见附录5
- },
- function (res) {
- console.log("agentConfig:", res);
- if (res.err_msg != "agentConfig:ok") {
- // TyEvent4002.fail();
- responseText = res.err_msg || "";
- reject(4002);
- }
- // TyEvent4002.end();
- // const TyEventGetDeviceInfo = window.TINGYUN.createAutoEvent({
- // key: 'Wx-TyEventGetDeviceInfo'
- // })
- wx.invoke("ext_DeviceInfo_GetInfo", { data: {} }, function (res) {
- console.log("获取设备信息--" + JSON.stringify(res));
- console.log("获取设备信息result--" + res.result);
- if (res.err_msg === "ext_DeviceInfo_GetInfo:ok") {
- //成功处理
- deviceInfo = { ...res };
- // //探针接口方式设置设备ID
- // window.TINGYUN && window.TINGYUN.setDid(deviceInfo.deviceUUID || 'xxx');
- // //探针接口方式设置用户ID
- // window.TINGYUN && window.TINGYUN.setUid(deviceInfo.macAddress || 'xxx.xxx');
- // TyEventGetDeviceInfo.end();
- console.log("deviceInfo--" + JSON.stringify(deviceInfo));
- resolve();
- }
- if (res.err_msg === "ext_DeviceInfo_GetInfo:fail") {
- // TyEventGetDeviceInfo.fail();
- //失败处理
- resolve();
- }
- if (res.err_msg === "ext_DeviceInfo_GetInfo:cancel") {
- // TyEventGetDeviceInfo.fail();
- //取消处理
- resolve();
- }
- });
- }
- );
- window.uexOnload && window.uexOnload(0);
- });
- wx.config({
- beta: true, // 调用wx.invoke形式的接口值时,该值必须为true。
- debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
- appId: AppInfo.corpid, // 必填,政务微信的cropID
- timestamp: "1608692903", // 必填,生成签名的时间戳
- nonceStr: "XKIvykvwOuAeIbl", // 必填,生成签名的随机串
- signature: "ad0c077e6b5fbfe0c9e5394703d8262a3bc21fc3", // 必填,签名,见附录1
- jsApiList: [
- "multiWindows_open",
- "multiWindows_close",
- "multiWindows_subscribe",
- "multiWindows_publish",
- "multiWindows_finish",
- "chooseImage",
- "scanQRCode",
- "hideOptionMenu",
- "shareWechatMessage",
- "shareAppMessage",
- "startAutoLBS",
- "stopAutoLBS",
- "onLocationChange",
- "onMenuShareAppMessage",
- "onMenuShareWechat",
- "previewFile",
- "openChatWithMsg",
- "ext_Database_Open",
- "ext_Database_Exec",
- "ext_Database_Query",
- "ext_Database_Close",
- "ext_ISCP_Init",
- "ext_ISCP_ConnectService",
- "ext_ISCP_GetLocalPort",
- "ext_ISCP_Close",
- "ext_ISCP_Status",
- "ext_screenControl_direction",
- "getLocation",
- "getZipAppDirectory",
- "multiWindows_open",
- "ext_DeviceInfo_GetInfo",
- "ext_DeviceInfo_version",
- "getAuthCode",
- ], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
- });
- });
- }
|