123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209 |
- import detectEthereumProvider from '@metamask/detect-provider'
- import {
- login
- } from '@/api/login.js';
- import {
- getUserInfo
- } from '@/api/user.js';
- import store from '../store';
- initEthereum ()
- // 初始化监听改变
- function initEthereum () {
- ethereum.on('accountsChanged', (accounts) => {
- // 地址修改时收到通知
- store.commit('user/logout');
- console.log('234');
- setPeovider(); // 重新登录
- });
- // 监听
- ethereum.on('chainChanged', (res)=>{
- console.log('235')
- store.commit('user/logout');
- setPeovider(); // 重新登录
- });
- // ethereum.on('connect', (connectInfo) => {
- // // 当 MetaMask 提供者第一次能够向链 提交 RPC 请求时,它会发出此事件。
- // uni.clearStorage();
- // // Time to reload your interface with accounts[0]!
- // loginDapp();
- // });
- ethereum.on('disconnect', (error) => { // 如果 MetaMask 提供者无法向任何链提 交 RPC 请求,它会发出此事件。
- console.log(error);
- // 这里可以打印一下error
- });
- // ethereum.on('message', (message) => { // MetaMask 提供者在收到一些应该通知消费者的消息时发出此事件。
- // console.log(message.data.result.hash)
- // })
- }
- export function getActionPage() {
- let pages = getCurrentPages();
- return pages[pages.length - 1]
- }
- //登录拦截
- export function interceptor() {
- let pages = getActionPage();
- // 获取当前页面
- let pageUrl = '/' + pages.route;
- let url = '/pages/public/login'
- // #ifdef H5
- // 判断是否为公众号调用微信授权登录
- // let weichatBrowser = uni.getStorageSync('weichatBrowser');
- // if (weichatBrowser) {
- // url = '/pages/public/wxLogin';
- // }
- setPeovider();
- return
- // #endif
- // #ifdef MP-WEIXIN
- url = '/pages/public/wxLogin';
- // #endif
- if (pageUrl != url) {
- uni.navigateTo({
- url
- })
- }
- }
- // 保存页面
- export function saveUrl() {
- let path = getPageUrl(true)
- uni.setStorageSync('present', path);
- }
- // 处理分享链接地址
- export function getPageUrl(showSpeard = false) {
- let page = getActionPage();
- let path = '/' + page.route;
- let url = '';
- // 获取对象可枚举键值列表
- let objKeys = Object.keys(page.options);
- // 判断有无传值
- if (objKeys.length > 0) {
- // 循环赋值对象数据
- for (let a in page.options) {
- // 判断有无邀请人
- if (a != 'speard') {
- url += a + "=" + page.options[a] + "&"
- } else {
- // 判断是否需要存储邀请人
- if (showSpeard) {
- url += a + "=" + page.options[a] + "&"
- }
- }
- }
- path += '?' + url.substr(0, url.length - 1);
- }
- // 返回处理邀请人后的邀请地址
- return path
- }
- async function setPeovider() { // 检测提供者
- uni.showLoading({
- title: '检测授权中...',
- mask: true
- });
- const provider = await detectEthereumProvider();
- if (provider) {
- startApp(provider); // Initialize your app
- } else {
- uni.showToast({
- title: '请先安装MetaMask插件',
- icon: 'none',
- duration: 3500
- });
- return false;
- }
- };
- // 检测插件
- async function startApp(provider) {
- if (provider !== window.ethereum) {
- uni.showToast({
- title: '安装了多个钱包,加载失败',
- icon: 'none',
- duration: 3500
- });
- return false
- } else {
- uni.showLoading({
- mask: true
- });
- }
- const srcid = await ethereum.request({
- method: 'eth_chainId'
- });
- console.log(srcid);
- if (srcid != '0x38') {
- try {
- const src = await ethereum.request({
- method: 'wallet_switchEthereumChain',
- params: [{
- chainId: '0x38'
- }],
- });
- console.log('233')
- eth_requestAccounts()
- } catch (switchError) {
- if (switchError.code === 4902) {
- try {
- const src = await ethereum.request({
- method: 'wallet_addEthereumChain',
- params: [{
- chainId: '0x38',
- chainName: 'BSC',
- rpcUrls: ['https://bsc-dataseed2.ninicoin.io'],
- }, ],
- });
- eth_requestAccounts()
- console.log(src, 'src');
- } catch (addError) {
- console.log(addError);
- }
- }
- }
- } else {
- eth_requestAccounts()
- }
- };
- async function eth_requestAccounts() {
- // 链接到MetaMask
- const PKR_LOGIN = 'BCMM_LOGIN' + (new Date()).getTime();
- // 链接到MetaMask
- await ethereum.request({
- method: 'eth_requestAccounts'
- })
- const res = await ethereum.request({
- "method": "personal_sign",
- "params": [
- PKR_LOGIN,
- ethereum.selectedAddress
- ]
- })
- toLogin(res, ethereum.selectedAddress, PKR_LOGIN);
- };
- // 登录
- async function toLogin(sign, account, msg) {
- const that = getApp();
- login({
- sign,
- account,
- msg: msg,
- spread: uni.getStorageSync('spread') || '' //上级推广人
- })
- .then(function(e) {
- console.log(e.data, 'e.data');
- uni.setStorageSync('token', e.data.userinfo.token);
- getUserInfo({}).then(e => {
- console.log(store);
- store.commit('user/login')
- // 保存返回用户数据
- console.log(e.data, ' e.data.userinfo');
- store.commit('user/setUserInfo', e.data);
- uni.hideLoading()
- });
- })
- .catch(function(e) {
- console.log(e);
- });
- };
|