聊一聊微信公众号分享以及打开app的经验

一、 分享

公众号文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111
第一步:当然是将js接口安全域名放到公众平台( https://mp.weixin.qq.com)里面;
第二部:引入微信人家自己封装的js方法(里面包括分享、支付等等...);

  1. 如果你是使用uniapp最好使用npm方式引入,uniapp官方插件链接:https://ask.dcloud.net.cn/article/35380
    需要在根目录中走一下 npm init -y,这一步是将package.json安装到项目中
    然后进行安装 npm install jweixin-module --save
    然后你会在package.json中看到这个插件已安装;
    image.png

ok前提条件已经配置完毕!
接下来就开始对接,对接的过程中是需要后端配合的,因为微信官方的一些安全策略,需要将某些接口必须放到后台来执行,然后在返给前端;

针对下面方法个人总结注意事项:

  1. jsApiList:[] 里面必须要注入你所使用的的api;
  2. shareData 里面的参数是后台返给你的且必须是后台返回;
  3. 分享时候的图片也一定要放到配置的安全域名下;
// 下面是使用方法,最好是创建一个公共的js文件 如 wxShare.js 
import wx from 'weixin-js-sdk'; // 引用
const APPID = 'xxx'; // 这里是你公众号的appid
const wxShare = (shareData) => {
    wx.config({
        debug: false, 
        appId: APPID, 
        timestamp: shareData.timestamp, 
        nonceStr: shareData.nonceStr, 
        signature: shareData.signature,
        // 这里一定要将你所使用到的api提前注入进来
        jsApiList: [
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'onMenuShareAppMessage',
            'chooseWXPay',
        ]
    });
    wx.checkJsApi({
        // 这里来检查你注入的api是否能正常使用(需要提前开启debug:true)
        jsApiList: [
            'chooseImage',
            'updateAppMessageShareData',
            'onMenuShareAppMessage',
            'chooseWXPay',
        ],
        success: function(res) {
            console.log(res, 'checkJsApi');
        },
    });
    wx.ready(function() {
        //分享到朋友圈”及“分享到QQ空间”
        wx.updateTimelineShareData({
            title: '', // 分享标题
            link:'', // 分享链接 
            imgUrl: '', // 分享图标
            success: function(res) {
                // 设置成功
                console.log('分享朋友圈成功返回的信息为:', res);
            },
        });
        //“分享给朋友”及“分享到QQ”
        wx.updateAppMessageShareData({
            title: '',  // 分享标题
            desc:'',// 分享描述
            link: '', // 分享链接 
            imgUrl: '', // 分享图标
            success: function(res) {
                console.log('分享朋友成功返回的信息为:', res);
            },
        });
    });
    wx.error(function(res) {
        console.log('验证失败返回的信息:', res);
    });
};

export const share = () =>{
    let broser = window.navigator.userAgent.toLowerCase(); // 判断是否在微信中打开
    if (broser.match(/MicroMessenger/i) == 'micromessenger') {
        // 在微信中打开的
        try {
        // 要获取分享时候的参数,就要将当前页面#前面的域名入参给到后端,后端再根据你给的参数去调用微信的api
            let url = encodeURIComponent(window.location.href.split('#')[0]);
            getSignature({ // getSignature 这个接口就是你与后端协商好的接口,里面包含分享时候 所用到的参数
                url: url,
            }).then(res => {
                wxShare(res); // 在这里调用 上面定义好的方法
            });
        } catch (error) {
            console.log(error);
        }
    } else {
        // 不在微信中 给出相应的提示
        uni.showToast({
            title: '请使用微信浏览器打开',
            icon: 'none',
        });
    }
}



// ----------------分割线---------------

// 在页面中去使用 如 index.vue 中

<template>
  ...
</template>

<script>
//  在 wxShare.js 文件中 引入  方法
import { share } from '@/common/wxShare.js';
methods:{
   // 点击某个按钮
   handlerShare(){
       share()
   }
}
<script>

<style>
  ...
</style>

如果以上都配置好了,那么到分享的时候只能分享出去一串链接,不是图片+文字描述的那种卡片怎么办?
第一个办法:将你的公众号链接,收藏到微信中,再从收藏列表打开这个链接;
第二个办法:提前将公众号链接配置到公众号里面(进入公众号在tab栏里点击进入的那种);

二、公众号打开APP

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html#22
注意事项:

  1. 需要到微信开放平台(https://open.weixin.qq.com)中关联app与公众号具体方法看官方文档;

在项目中添加vue.config.js并添加一下内容(为了匹配在template中使用script标签)

module.exports = {
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap((options) => {
        options.compilerOptions = {
          ...options.compilerOptions,
          // 忽略wx-开头的组件,这些是微信的默认组件
          isCustomElement: (tag) => tag.startsWith('wx-open')
        }
        return options
      })
}

接上面封装的方法 假如在.vue页面中使用

<template>
   <view>
    <wx-open-launch-app
                v-if="isBtn"
        id="launch-btn"
        appid="wx71abce1942ba527f"
        style="
            width: 550rpx;
            height: 92rpx;
            background: #1b1b1b;
            border-radius: 46rpx;
            font-size: 32rpx;
            font-family: MiSans-Demibold, MiSans;
            font-weight: 600;
            color: #ffffff;
            line-height: 92rpx;
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
        "
        @launch="getApp"
        @error="errorOpen"
        @ready="appBtnReady"
    >
        <component :is="'script'" type="text/wxtag-template">
            <button
                style="
                    font-size: 32rpx;
                    font-weight: 600;
                    color: #ffffff;
                    line-height: 92rpx;
                    text-align: center;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                "
                class="btn"
            >
                打开APP体验
            </button>
        </component>
    </wx-open-launch-app>
   </view>
</template>

<script>
//  在 wxShare.js 文件中 引入  方法
import { share } from '@/common/wxShare.js';
export default {
   data(){
    return{
      isBtn:false
    }
   },
   methods: {
        getApp(v) {
            console.log(v);
        },
        errorOpen(err) {
            console.log(err);
        },
        appBtnReady() {
          // 由于唤醒app的按钮是异步加载的,需要去wx.config中注入且验证后才能展示出来,这里可以来一个开关
         this.isBtn = true
        },
       // 使按钮显示出来的方法
      showBtn(){
          share('这里可以入参来判断是显示按钮的,并不是分享的') // 封装的方法自行进行判断
      }
   }
}
</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。