loginUtils.js 4.9 KB

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