loginUtils.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import detectEthereumProvider from '@metamask/detect-provider'
  2. import {
  3. login
  4. } from '@/api/login.js';
  5. import {
  6. getUserInfo
  7. } from '@/api/user.js';
  8. import store from '../store'
  9. export function getActionPage() {
  10. let pages = getCurrentPages();
  11. return pages[pages.length - 1]
  12. }
  13. //登录拦截
  14. export function interceptor() {
  15. let pages = getActionPage();
  16. // 获取当前页面
  17. let pageUrl = '/' + pages.route;
  18. let url = '/pages/public/login'
  19. // #ifdef H5
  20. // 判断是否为公众号调用微信授权登录
  21. // let weichatBrowser = uni.getStorageSync('weichatBrowser');
  22. // if (weichatBrowser) {
  23. // url = '/pages/public/wxLogin';
  24. // }
  25. setPeovider();
  26. return
  27. // #endif
  28. // #ifdef MP-WEIXIN
  29. url = '/pages/public/wxLogin';
  30. // #endif
  31. if (pageUrl != url) {
  32. uni.navigateTo({
  33. url
  34. })
  35. }
  36. }
  37. // 保存页面
  38. export function saveUrl() {
  39. let path = getPageUrl(true)
  40. uni.setStorageSync('present', path);
  41. }
  42. // 处理分享链接地址
  43. export function getPageUrl(showSpeard = false) {
  44. let page = getActionPage();
  45. let path = '/' + page.route;
  46. let url = '';
  47. // 获取对象可枚举键值列表
  48. let objKeys = Object.keys(page.options);
  49. // 判断有无传值
  50. if (objKeys.length > 0) {
  51. // 循环赋值对象数据
  52. for (let a in page.options) {
  53. // 判断有无邀请人
  54. if (a != 'speard') {
  55. url += a + "=" + page.options[a] + "&"
  56. } else {
  57. // 判断是否需要存储邀请人
  58. if (showSpeard) {
  59. url += a + "=" + page.options[a] + "&"
  60. }
  61. }
  62. }
  63. path += '?' + url.substr(0, url.length - 1);
  64. }
  65. // 返回处理邀请人后的邀请地址
  66. return path
  67. }
  68. async function setPeovider() { // 检测提供者
  69. uni.showLoading({
  70. title: '检测授权中...',
  71. mask: true
  72. });
  73. const provider = await detectEthereumProvider();
  74. if (provider) {
  75. startApp(provider); // Initialize your app
  76. } else {
  77. uni.showToast({
  78. title: '请先安装MetaMask插件',
  79. icon: 'none',
  80. duration: 3500
  81. });
  82. return false;
  83. }
  84. };
  85. // 检测插件
  86. async function startApp(provider) {
  87. if (provider !== window.ethereum) {
  88. uni.showToast({
  89. title: '安装了多个钱包,加载失败',
  90. icon: 'none',
  91. duration: 3500
  92. });
  93. return false
  94. } else {
  95. uni.showLoading({
  96. mask: true
  97. });
  98. }
  99. const srcid = await ethereum.request({
  100. method: 'eth_chainId'
  101. });
  102. if (srcid != '0x38') {
  103. try {
  104. const src = await ethereum.request({
  105. method: 'wallet_switchEthereumChain',
  106. params: [{
  107. chainId: '0x38'
  108. }],
  109. });
  110. console.log('233')
  111. login_metamask()
  112. } catch (switchError) {
  113. if (switchError.code === 4902) {
  114. try {
  115. const src = await ethereum.request({
  116. method: 'wallet_addEthereumChain',
  117. params: [{
  118. chainId: '0x38',
  119. chainName: 'BSC',
  120. rpcUrls: ['https://bsc-dataseed2.ninicoin.io'],
  121. }, ],
  122. });
  123. login_metamask()
  124. console.log(src, 'src');
  125. } catch (addError) {
  126. console.log(addError);
  127. }
  128. }
  129. }
  130. } else {
  131. login_metamask()
  132. }
  133. };
  134. async function login_metamask() {
  135. eth_requestAccounts(); // 拿到账户对应的账号
  136. ethereum.on('accountsChanged', (accounts) => { // 地址修改时收到通知
  137. store.commit('user/logout');
  138. console.log('234');
  139. setPeovider(); // 重新登录
  140. });
  141. // 监听
  142. // ethereum.on('chainChanged', (res)=>{
  143. // console.log('235')
  144. // store.commit('user/logout');
  145. // setPeovider(); // 重新登录
  146. // });
  147. // ethereum.on('connect', (connectInfo) => {
  148. // // 当 MetaMask 提供者第一次能够向链 提交 RPC 请求时,它会发出此事件。
  149. // uni.clearStorage();
  150. // // Time to reload your interface with accounts[0]!
  151. // loginDapp();
  152. // });
  153. ethereum.on('disconnect', (error) => { // 如果 MetaMask 提供者无法向任何链提 交 RPC 请求,它会发出此事件。
  154. console.log(error);
  155. // 这里可以打印一下error
  156. });
  157. // ethereum.on('message', (message) => { // MetaMask 提供者在收到一些应该通知消费者的消息时发出此事件。
  158. // console.log(message.data.result.hash)
  159. // })
  160. };
  161. async function eth_requestAccounts() {
  162. // 链接到MetaMask
  163. ethereum.request({
  164. method: 'eth_requestAccounts'
  165. }).then((account) => {
  166. console.log(account, 'account');
  167. // this.$store.commit('accounts/connect_wallet', account[0]);
  168. // localStorage.setItem('accounts', account)
  169. const PKR_LOGIN = 'PKR_LOGIN' + (new Date()).getTime();
  170. ethereum.request({
  171. "method": "personal_sign",
  172. "params": [
  173. PKR_LOGIN,
  174. account[0]
  175. ]
  176. }).then((res) => {
  177. console.log(res, 'res');
  178. console.log(res.length, 'reschangdu');
  179. toLogin(res, account[0], PKR_LOGIN);
  180. });
  181. });
  182. };
  183. // 登录
  184. async function toLogin(sign, account, msg) {
  185. const that = getApp();
  186. login({
  187. sign,
  188. account,
  189. msg: msg,
  190. spread: uni.getStorageSync('spread') || '' //上级推广人
  191. })
  192. .then(function(e) {
  193. uni.setStorageSync('token', e.data.token);
  194. getUserInfo({}).then(e => {
  195. console.log(store);
  196. store.commit('user/login')
  197. // 保存返回用户数据
  198. // obj.setUserInfo();
  199. store.commit('user/setUserInfo', e.data);
  200. uni.hideLoading()
  201. });
  202. })
  203. .catch(function(e) {
  204. console.log(e);
  205. });
  206. };