vue wx-open-launch-weapp功能封装

import wx from 'weixin-js-sdk'
import vue from '@/main'
import {isEmpty, getBrowserType, setWechatRole, urlChange} from '@/utils/common'

/** 
 * 打开小程序 
 * @param info {
 *  boxId:  元素ID
 *  boxWidth 元素宽度
 *  boxHeight 元素高度
 *  domId 待添加元素ID - 非必填,默认xcx_btn
 *  appid 小程序id  gh_****
 *  url  小程序页面路径
 * }
*/
const openXCX = (info:any) => {
    if(getBrowserType() !='wechat') {
        return
    }
    let btn = document.getElementById(info.boxId) as HTMLElement
    if(isEmpty(info.domId)) {
        if(btn.querySelector('#xcx_btn')) {
            return 
        }
    } else {
        if(btn.querySelector(`#${info.domId}`)) {
            return 
        }
    }
    async function initDom() {
        let status
        if(isEmpty(sessionStorage.weichatConfig)) {
            status = await initConfig()
            sessionStorage.weichatConfig = status?1:0
        } else {
            status = sessionStorage.weichatConfig == 1?true: false
        }
        if(!status) {
            let dom = document.createElement('div')
            dom.setAttribute('style',`position:absolute; top: 0; left:0; width:${info.boxWidth}px; height: ${info.boxHeight}px;`)
            dom.addEventListener('click',()=>{
                console.log('不支持小程序')
            })
            btn.appendChild(dom)
            return
        }
        let dom = document.createElement('wx-open-launch-weapp')
        dom.setAttribute('style',`position:absolute; top: 0; left:0; width:${info.boxWidth}px; height: ${info.boxHeight}px;`)
        dom.setAttribute('id',isEmpty(info.domId)?'xcx_btn':info.domId)
        dom.setAttribute('username',info.appid)
        dom.setAttribute('path',info.url)
        dom.innerHTML = `<script type='text/wxtag-template'>
                <style scoped>
                    .open_btn{
                        position: relative;
                        width:${info.boxWidth}px; height: ${info.boxHeight}px;
                        opacity: 0;
                    }
                </style>
                <div class='open_btn'></div>
            </script>`
        btn.appendChild(dom)
        dom.addEventListener('launch', (e:any)=> {
            console.log('xcxLaunch')
        })
        dom.addEventListener('error', (e:any)=> {
            console.log('xcxLaunch')
            alert(`xcxLaunch跳转异常 - ${e.detail}`)
        })
    }
    initDom()
}

/** 
 * 分享 
 * @param info {
 *  title:  标题
 *  des 描述
 *  linkurl 分享链接
 *  img 分享图片
 * }
*/
const share = async(info:any)=>{
    await initConfig()
    wx.onMenuShareAppMessage({
        title: info.title,
        desc: info.des,
        link: info.linkurl,
        imgUrl: info.img,
        success:(res:any) =>{
            console.log('已分享');
        },
        cancel: (res:any)=> {
            console.log('已取消');
        },
        fail: (res:any) => {
            console.log(JSON.stringify(res));
        }
    })
    wx.onMenuShareTimeline({
        title: info.title,
        link: info.linkurl,
        imgUrl: info.img,
        success:(res:any) =>{
            console.log('已分享');
        },
        cancel: (res:any)=> {
            console.log('已取消');
        },
        fail: (res:any) => {
            console.log(JSON.stringify(res));
        }
    });
}

/** 
 * 初始化微信sdk,获取权限
 * @param 
 * @return {Boolean} true-支持  false-不支持
*/
const initConfig = ()=>{
    return new Promise((resolve,reject)=>{
        if(getBrowserType() != 'wechat') {
            resolve(false)
        }
        if(!checkWechatVersion()) {
            resolve(false)
        }
        let isError = false
        vue.$axios.post(`${vue.$request.c}/v1/wechat/jssdk`, {
            url: encodeURIComponent(`${window.location.href.indexOf('#')<0?window.location.href:window.location.href.split('#')[0]}`)
        }).then((res: any) => {
            if (res.code == 200 && wx) {
                wx.config({
                    debug: false, 
                    appId: res.data.appid, // 必填,公众号的唯一标识
                    timestamp: res.data.timestamp, // 必填,生成签名的时间戳
                    nonceStr: res.data.noncestr, // 必填,生成签名的随机串
                    signature: res.data.signature, // 必填,签名
                    openTagList: [
                        'wx-open-launch-app',
                        'wx-open-launch-weapp'
                    ],
                    jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline']
                })
                wx.ready(()=> {
                    if(isError) {
                        resolve(false)
                        console.log(111)
                    } else {
                        resolve(true)
                    }
                })
                wx.error((res:any)=> {
                    isError = true
                    resolve(false)
                })
            } 
        })
    })
}

/** 
 * 判断当前微信版本号是否支持
 * @param 
 * @return {Boolean} true-支持  false-不支持
*/
const checkWechatVersion = ()=>{
    document.addEventListener('WeixinOpenTagsError', (e)=> {
        return false
    })
    let wechat:any
    wechat = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i)
    let judgewechat = wechat[1].split('.')
    if(
        Number(judgewechat[0])>7 || 
        (Number(judgewechat[0])==7 && Number(judgewechat[1])>0) || 
        (Number(judgewechat[0])==7 && Number(judgewechat[1])==0 && Number(judgewechat[2])>=12)){
        return true
    } else {
        return false
    }
}

export {
    openXCX,
    share,
    initConfig
}

调用方法:
import {openXCX} from ‘@/utils/weiChatUtils’
openXCX({
boxId: ,
boxWidth: ,
boxHeight: ,
domId: ,
appid: ,
url:
})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值