uniapp之h5公众号分享和授权

一,微信分享

1,安装jweixin-module

npm i jweixin-module

uniapp之h5公众号分享和授权

2,在需要分享的页面引入

<script>
	// #ifdef H5
	let jweixin = require('jweixin-module')
	// #endif
    
.....
</script>

3,设置分享内容(或者点击触发分享)

distributrShare() {
    this.$http({
        apiName: "wxJsdkConfig",
        type: "POST",
        data: {
            url: encodeURIComponent(window.location.href),
            //后台通过域名进行授权
        }
    }).then(res = >{
        var _self = this jweixin.config({
            debug: true,
            // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: res.data.appId,
            // 必填,公众号的唯一标识
            timestamp: res.data.timestamp,
            // 必填,生成签名的时间戳
            nonceStr: res.data.nonceStr,
            // 必填,生成签名的随机串
            signature: res.data.signature,
            // 必填,签名
            jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData', ] // 必填,需要使用的JS接口列表
        })
 
        jweixin.ready(function(res) {
            //分享给朋友
            jweixin.updateAppMessageShareData({
                title: _self.title,
                desc: "快来嗨购吧!",
                link: window.location.href + "&inviteCode=" + _self.userInfo.inviteCode,
                imgUrl: _self.picUrl,
                trigger: function trigger(res) {
                    // alert(res);
                },
                success: function success(res) {
 
                    // alert('已分享');
                },
                cancel: function cancel(res) {
                    // alert('已取消');
                },
                fail: function fail(res) {
                    // alert(2, JSON.stringify(res));
                }
            });
        }) jweixin.error(err = >{
            // console.log("jsapi错误:",err)
        })
    }).
    catch(err = >{
        // console.log(3,err)
    })
 
},

注意几点:

a:公众号的分享只能通过右上角h5的分享触发,默认分享当前页面,分享只是配置分享内容 

b:当前分享页面的链接必须在后台配置JS接口安全域名和网页授权域名

c:传到后台的链接需要encodeURIComponent转码,不能包括端口号,

d:安卓上可以,IOS上报fail link must be in js secure domain list参考:解决微信H5网页分享报错:fail link must be in js secure domain list

e:invalid signature参考:关于微信公众号开发config:invalid signature错误的解决方法

二,授权登录
页面:

...async onShow() {
    // #ifdef H5 
    if (utils.isWxBrowser()) {
        if (window.location.href.includes('code=')) {
            await utils.wxJsdkAuthorize('', true)
        }
    }
    // #endif
},
...
 
methods: {
    async oAuth(e) {
        // #ifdef H5
        if (utils.isWxBrowser()) {
            uni.showLoading({
                title: "授权中...",
                mask: true
            }) await this.wxJsdkLogin();
            uni.hideLoading()
        }
        // #endif
        // #ifdef APP-PLUS
        var type = e.currentTarget.dataset.logintype uni.login({
            provider: type,
            success: (res) = >{
                uni.getUserInfo({
                    provider: type,
                    success: (info) = >{
                        uni.setStorageSync('appInfo', info.userInfo) console.log(info.userInfo) this.$http({
                            apiName: 'appWxLogin',
                            type: 'POST',
                            data: {
                                appOpenId: info.userInfo.openId,
                                headUrl: info.userInfo.avatarUrl,
                                wuserName: info.userInfo.nickName
                            }
                        }).then(res = >{
                            console.log(res) uni.showToast({
                                title: '登录成功',
                                mask: false,
                                duration: 1500
                            });
                            utils.setSesion(res.data) utils.getUserInfo() utils.afterLoginJump()
 
                        }).
                        catch(err = >{
                            console.log(err) if (err.code == 500070) {
                                uni.redirectTo({
                                    url: './bindMobile'
                                })
                            } else {
                                uni.redirectTo({
                                    url: '../set/loginPwd'
                                })
                            }
 
                        })
                    }
                })
            }
        })
        // #endif
    }
 
}

utils.js

//判断是否是微信浏览器
isWxBrowser() {
    if (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
},
//jdk配置
async configWeiXin(callback) {
    //获取公众号配置
    let resConfig = await http({
        apiName: "wxJsdkConfig",
        type: "POST",
        data: {
            url: encodeURIComponent(window.location.href),
            //后台通过域名进行授权
        }
    }) if (resConfig) {
        let apiList = [ // 可能需要用到的能力
        'onMenuShareAppMessage', 'onMenuShareTimeline', 'hideOptionMenu', 'showOptionMenu', 'chooseWXPay'];
        let info = {
            // debug: true, // 调试,发布的时候改为false
            appId: resConfig.data.appId,
            nonceStr: resConfig.data.nonceStr,
            timestamp: resConfig.data.timestamp,
            signature: resConfig.data.signature,
            jsApiList: apiList
        };
        jweixin.config(info);
        jweixin.error(err = >{
            console.log('config fail:', err);
        });
        jweixin.ready(res = >{
            console.log(3, res) if (callback) callback(jweixin, resConfig.data.appId); // 配置成功回调
            // uni.setStorageSync('msg',JSON.stringify(res.data))
 
            // uni.setStorageSync('msg',JSON.parse(res.message.replace(/"/,/'/)))
 
        });
    }
},
//公众号授权
async wxJsdkAuthorize(_appid, isLogin = false) {
    let link = window.location.href;
    // let link=window.location.origin+'/pages/public/middlePage'
    let _code = ''
    if (link.includes("code=")) {
        _code = link.split("code=")[1].split('&')[0]
    }
    // 如果拿到_code,调用授权接口,没有拿到就跳转微信授权链接获取
    if (_code) {
        if (isLogin) {
            await http({
                apiName: "wxWebLogin",
                type: 'POST',
                data: {
                    code: _code
                }
            }).then(res = >{
 
                uni.showToast({
                    title: '登录成功',
                    mask: false,
                    duration: 1500
                });
                this.setSesion(res.data) this.getUserInfo() this.afterLoginJump()
            }).
            catch(err = >{
                uni.setStorageSync('msg', err.data) console.log(uni.getStorageInfoSync('msg').openId) if (err.code == 500070) {
                    uni.redirectTo({
                        url: '/pages/public/bindMobile'
                    })
                } else {
                    uni.redirectTo({
                        url: '/pages/set/loginPwd'
                    })
                }
            })
        } else {
            await http({
                apiName: "wxJsdkLogin",
                data: {
                    code: _code
                }
            }).then(res = >{
 
})
            //code传到后台关联账户
            uni.setStorageSync("wxJsdkLogin", true)
        }
 
    } else {
        let appid = _appid;
        let uri = encodeURIComponent(link);
        let authURL = `https: //open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
        window.location.href = authURL;
 
    }
},
jsApiCall(data, callback_succ_func, callback_error_func) {
    //使用原生的,避免初始化appid问题  
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
        appId: data['appId'],
        timeStamp: data['timeStamp'],
        nonceStr: data['nonceStr'],
        // 支付签名随机串,不长于 32 位  
        package: data['package'],
        // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)  
        signType: data['signType'],
        // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'  
        paySign: data['paySign'],
        // 支付签名  
    },
    function(res) {
        var msg = res.err_msg ? res.err_msg: res.errMsg;
        //WeixinJSBridge.log(msg);  
        switch (msg) {
        case 'get_brand_wcpay_request:ok':
            //支付成功时  
            if (callback_succ_func) {
                callback_succ_func(res);
            }
            break;
        default:
            //支付失败时  
            WeixinJSBridge.log('支付失败!' + msg + ',请返回重试.');
            if (callback_error_func) {
                callback_error_func({
                    msg: msg
                });
            }
            break;
        }
    })
},
//WeixinJSBridge判断
wxJsPay(data, callback_succ_func, callback_error_func) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
        }
    } else {
        this.jsApiCall(data, callback_succ_func, callback_error_func);
    }
},

转自:uniapp之h5公众号分享和授权

上一篇:网址为 xxx 的网页可能暂时无法连接,或者它已永久性地移动到了新网址。 ERR_UNSAFE_PORT


下一篇:react引入antd并配置按需加载和自定义主题