loginUtils.js 5.4 KB

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