login.vue 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <template>
  2. <div class="loginPage w-full h-full bg-white">
  3. <van-form show-error :show-error-message="false" @submit="onSubmit">
  4. <van-cell-group inset>
  5. <van-field v-model="username" name="username" label="用户名" placeholder="用户名" :rules="rules" />
  6. <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码" :rules="rules" />
  7. </van-cell-group>
  8. <div style="margin: 16px">
  9. <van-button round block type="primary" native-type="submit">
  10. 提交
  11. </van-button>
  12. </div>
  13. </van-form>
  14. </div>
  15. </template>
  16. <script setup>
  17. import { ref } from "vue";
  18. import { useLifecycle } from "@hooks/useCommon.js";
  19. import { LOGIN_INTERFACE, USER_ID_LOGIN, WE_CHAT_LOGIN, GET_MESSAGE_LIST } from "@hooks/useApi.js";
  20. // import { addressRedirection, obtainEnterpriseWeChatParameters } from "@utility/corpWXparam"
  21. import { addressRedirection } from "@utility/corpWXparam"
  22. import useShowToast from "../hooks/useToast";
  23. import useRouterStore from "@store/useRouterStore.js";
  24. import useInfoStore from "@store/useInfoStore.js";
  25. import requests from "@common/requests";
  26. const { toastLoading, toastSuccess, toastFail } = useShowToast();
  27. const router = useRouterStore()
  28. const userInfo = useInfoStore()
  29. const username = ref("18122222222");
  30. const password = ref("000000");
  31. const rules = ref([{ required: true }]);
  32. const isCorpWX = ref(false)
  33. const isWX = ref(false)
  34. useLifecycle({
  35. load: () => {
  36. verifyLoginEnvironment()
  37. },
  38. init: () => {
  39. verifyLoginEnvironment()
  40. }
  41. });
  42. function verifyLoginEnvironment() {
  43. const currentEnvironment = navigator.userAgent.toLowerCase();
  44. isCorpWX.value = currentEnvironment.indexOf("wxwork") > 0 ? true : false
  45. isWX.value = currentEnvironment.indexOf("micromessenger") > 0 ? true : false
  46. const href = window.location.href;
  47. if (href.indexOf("userId") > 0) {
  48. let loginUserId = href.substring(href.indexOf("userId=") + "userId=".length);
  49. if (loginUserId.includes('#/')) {
  50. loginUserId = loginUserId.substring(0, loginUserId.indexOf('#/'));
  51. }
  52. loginByUserId(loginUserId);
  53. } else {
  54. // 判断是否为企业微信授权
  55. if (isCorpWX.value) {
  56. // 判断企业微信,是否存在授权
  57. if (href.includes("com/?code")) {
  58. bindIfNessary()
  59. } else {
  60. if (href.indexOf('hasTriedAutoLogin') == -1) {
  61. tryAutoLogin()
  62. } else {
  63. //后台经过验证后,重定向过来带上了userId
  64. let loginUserId = href.substring(href.indexOf("userId=") + "userId=".length);
  65. if (loginUserId.includes('#/')) {
  66. loginUserId = loginUserId.substring(0, loginUserId.indexOf('#/'));
  67. }
  68. loginByUserId(loginUserId);
  69. }
  70. }
  71. }
  72. }
  73. }
  74. // 账号密码登录
  75. function onSubmit(fromVal) {
  76. toastLoading('登陆中...', 0)
  77. requests.post(LOGIN_INTERFACE, { ...fromVal }).then(({ data }) => {
  78. loginProcessing(data)
  79. })
  80. }
  81. // userId登录
  82. function loginByUserId(userId) {
  83. toastLoading('登陆中...', 0)
  84. // requests.post(USER_ID_LOGIN, { params: { userId } }).then(({ data }) => {
  85. requests.post(USER_ID_LOGIN, { userId }).then(({ data }) => {
  86. loginProcessing(data)
  87. })
  88. }
  89. // 授权回调重定向
  90. function tryAutoLogin() {
  91. window.location.href = addressRedirection()
  92. }
  93. function bindIfNessary() {
  94. const href = window.location.href;
  95. const requestUrl = isCorpWX.value ? '/wxcorp/bindCorpWeiXin' : isWX ? '/wechat/bindWeiXin' : '';
  96. if (requestUrl.length > 0) {
  97. //url包括 com/?code 证明为从微信跳转回来的
  98. if (href.includes("com/?code")) {
  99. const url = href; //vue自动在末尾加了 #/ 符号,截取去掉
  100. const jingPosit = url.indexOf("com/") + 4; //获取域名结束的位置
  101. const urlRight = url.substring(jingPosit, url.indexOf('#/') !== -1 ? url.indexOf('#/') : url.length); //url右侧部分
  102. const code = urlRight.substring('?code='.length, urlRight.indexOf('&state='));
  103. const passUserId = urlRight.substring(urlRight.indexOf('&state=') + '&state='.length);
  104. if (passUserId == '0') {
  105. requests.get(WE_CHAT_LOGIN, { code }).then((res) => {
  106. if (res.data != null && ((isWX.value && res.data.wxOpenid != undefined)
  107. || (isCorpWX.value && res.data.corpwxUserid != undefined))) {
  108. loginProcessing(res.data)
  109. window.location.href = '/#/index';
  110. }
  111. })
  112. } else {
  113. //绑定微信账号的回调, 调用后台接口,注册用户
  114. requests.get(requestUrl, { code, userId: passUserId }).then((res) => {
  115. if (res == null) {
  116. toastFail('绑定失败')
  117. return
  118. }
  119. if (res.data != null && ((isWX.value && res.data.wxOpenid != undefined)
  120. || (isCorpWX.value && res.data.corpwxUserid != undefined))) {
  121. loginProcessing(res.data)
  122. window.location.href = '/#/my/center';
  123. }
  124. })
  125. }
  126. }
  127. }
  128. }
  129. // 登陆前的处理
  130. function loginProcessing(data = {}) {
  131. sessionStorage.setItem('token', data.id)
  132. userInfo.updateState({
  133. userInfo: data,
  134. token: data.id,
  135. modularList: separateRouting(data.moduleList || []),
  136. permissionList: data.functionList || []
  137. })
  138. router.switchTabBar({
  139. pathName: 'home',
  140. success: function () {
  141. alert(isCorpWX.value)
  142. if (isCorpWX.value) {
  143. obtainEnterpriseWeChatParameters(data)
  144. }
  145. toastSuccess('登陆成功')
  146. setTimeout(() => {
  147. getMessageList()
  148. }, 500)
  149. }
  150. })
  151. }
  152. function getMessageList() {
  153. requests.post(GET_MESSAGE_LIST, {}).then(({ data = [] }) => {
  154. userInfo.updateState({
  155. numberOfMessages: data.filter((item) => !item.checked)?.length || ''
  156. })
  157. })
  158. }
  159. function separateRouting(list = []) {
  160. return (list || []).filter(item => item.isMenu && !(['/team', '/system', '/analysis', '/corpreport'].includes(item.path)))
  161. }
  162. function obtainEnterpriseWeChatParameters(data = {}) {
  163. const token = data.id
  164. const curUrl = window.location.href.split('#')[0]
  165. console.log('开始调用接口')
  166. requests.post(`/wxcorp/getCorpWXConfig`, { url: curUrl, token }).then((res) => {
  167. console.log(res, '<====== 返回的参数 /wxcorp/getCorpWXConfig')
  168. wx.config({
  169. beta: true,
  170. debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  171. appId: res.data.appid, // 必填,公众号的唯一标识
  172. timestamp: res.data.timestamp, // 必填,生成签名的时间戳
  173. nonceStr: res.data.noncestr, // 必填,生成签名的随机串
  174. signature: res.data.sign, // 必填,签名,见附录1
  175. jsApiList: ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'previewFile', 'getLocation', 'agentConfig']
  176. })
  177. wx.ready(function () {
  178. // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
  179. requests.post(`/wxcorp/getCorpWXAgentConfig`, { url: curUrl, token }).then((res) => {
  180. console.log(res, '<====== 返回的参数 /wxcorp/getCorpWXAgentConfig')
  181. wx.agentConfig({
  182. corpid: res.data.corpid, // 必填,企业微信的corpid,必须与当前登录的企业一致
  183. agentid: res.data.agentid, // 必填,企业微信的应用id (e.g. 1000247)
  184. timestamp: res.data.timestamp, // 必填,生成签名的时间戳
  185. nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
  186. signature: res.data.signature, // 必填,签名,见附录-JS-SDK使用权限签名算法
  187. jsApiList: ['selectExternalContact', 'openThirdAppServiceChat', 'openAppManage'], //必填,传入需要使用的接口名称
  188. success: function (result) {
  189. console.log(result, '《+========== 成功1')
  190. // wx.agentConfig成功回调后,WWOpenData 才会注入到 window 对象上面
  191. window.WWOpenData.bind(document.querySelector('ww-open-data'))
  192. },
  193. fail: function (res) {
  194. console.log(res, '<===== 失败1')
  195. if (res.errMsg.indexOf('function not exist') > -1) {
  196. alert('版本过低请升级')
  197. }
  198. },
  199. })
  200. }).catch(err => {
  201. console.log(err, '<===== 失败2')
  202. if (err.errMsg.indexOf('function not exist') > -1) {
  203. alert('版本过低请升级')
  204. }
  205. })
  206. })
  207. wx.error(function (res) {
  208. // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
  209. // alert('wxConfig发生异常:'+JSON.stringify(res));
  210. // 企业第一次授权安装进入后会报not in reliable domain的错误,刷新后正常
  211. location.reload();
  212. });
  213. }).catch(err => {
  214. alert(err);
  215. })
  216. }
  217. </script>
  218. <style lang="scss" scoped></style>