公众号跳转打开小程序(引入微信SDK)

1.引入微信SDK(封装SDK)

sdk.js
// 微信SDK官方文档: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
const jweixin = require("./wx-jssdk");
import api from "@/api/api";
// 微信SDK全局方法
export default {

 // 初始化SDK
  async init(callback) {
    // 记录进入app时的url
    if (typeof window.entryUrl === "undefined" || window.entryUrl === "") {
      window.entryUrl = location.href.split("#")[0];
    }
    const isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
    // 进行签名的时候  Android 不用使用之前的链接, ios 需要
    const signLink = isiOS
      ? uni.getStorageSync("WxCodeUrl")
      : location.href.split("#")[0];
    // 获取当前url然后传递给后台获取授权和签名信息,后台需要解码才能使用
    // const url = encodeURIComponent(signLink + "/");
    const url = encodeURIComponent(signLink);

    // 服务端进行签名 --- 从后端api接口获取
    const res = await api.jsApiSignature({ url });
    if (!res.success) return;
    // 注意此处的返回值
    jweixin.config({
      debug: false, 
      // debug:true, // 调试时开启
      appId: res.result.appId, // 接口返回的公众号appid
      timestamp: res.result.timestamp,
      nonceStr: res.result.nonceStr,
      signature: res.result.signature,
      jsApiList: [],
      openTagList: ["wx-open-launch-weapp"], // 可选,需要使用的开放标签列表 wx-open-launch-weapp为跳转小程序的标签
    });

    jweixin.ready(() => {
      console.log("config注入成功");
      callback && callback();
    });
    jweixin.error((e) => {
      console.log(e, "失败信息");
      init()
    });
  },

  async wxOauth() {
    // 非静默授权,第一次有弹框
    const local = window.location.href; // 获取页面url
    const code = getUrlCode().code; // 截取code
    // 获取之前的code 。 避免出现新旧code
    const oldCode = uni.getStorageSync("wechatCode");
    if (code == null || code == "" || code == "undefined" || code == oldCode) {
      // 如果没有code,就去请求获取code
      console.log("当前没有code,进入授权页面");
      // const uri = encodeURIComponent(local)
      // 设置旧的code为0,避免死循环
      uni.setStorageSync("wechatCode", 0);
      const appid = "wx3eb254332bcb78a9";
      const uri = "https://...../pages/index/index"; // 授权登录成功回调的地址(域名+路径)
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
    } else {
      console.log("存在code,使用code登录");
      // 保存最新code
      uni.setStorageSync("wechatCode", code);
      // const res = await vm.$u.api.wechatLogin({
      // 	code
      // })
      console.log(res);
      // 登录成功
      vm.$u.vuex("userInfo", res.data);
      vm.$u.vuex("isLogin", true);
    }
  },
  // 微信授权登录,不需要初始化微信SDK
  async wxOauth() {
    // 非静默授权,第一次有弹框
    const local = window.location.href; // 获取页面url
    const code = getUrlCode().code; // 截取code
    // 获取之前的code 。 避免出现新旧code
    const oldCode = uni.getStorageSync("wechatCode");
    if (code == null || code == "" || code == "undefined" || code == oldCode) {
      // 如果没有code,就去请求获取code
      console.log("当前没有code,进入授权页面");
      // const uri = encodeURIComponent(local)
      // 设置旧的code为0,避免死循环
      uni.setStorageSync("wechatCode", 0);
      const appid = "wx3eb254332bcb78a9";
      const uri = "https://pos-mp-dev.kymasf.com/pages/index/index"; // 授权登录成功回调的地址(域名+路径)
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
    } else {
      console.log("存在code,使用code登录");
      // 保存最新code
      uni.setStorageSync("wechatCode", code);
      // const res = await vm.$u.api.wechatLogin({
      // 	code
      // })
      console.log(res);
      // 登录成功
      vm.$u.vuex("userInfo", res.data);
      vm.$u.vuex("isLogin", true);
    }
  },
  // 判断是否是微信客户端
  isWechat() {
    // true是微信客户端,false不是微信客户端
    const ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/micromessenger/i) == "micromessenger";
  },

  // 获取当前位置
  getLocation(callback) {
    this.init(() => {
      jweixin.getLocation({
        type: "gcj02",
        success: (res) => {
          callback && callback(res);
        },
      });
    });
  },

  // 打开位置, 参数 { lat:40.042542,lng:116.397128 }
  openLocation(params) {
    this.init(() => {
      jweixin.openLocation({
        //根据传入的坐标打开地图
        latitude: params.latitude, // 纬度,浮点数,范围为90 ~ -90
        longitude: params.longitude, // 经度,浮点数,范围为180 ~ -180。
        name: params.name || "", // 位置名
        address: params.address || "", // 地址详情说明
        scale: params.scale || 20, // 地图缩放级别,整型值,范围从1~28。默认为最大
        infoUrl: "", // 在查看位置界面底部显示的超链接,可点击跳转
      });
    });
  },

  // 自定义分享
  share(params = {}) {
    this.init(() => {
      const shareData = {
        title: params?.title || "默认标题",
        desc: params?.desc || "默认描述",
        link: params?.link || window.location.href,
        imgUrl:
          params?.imgUrl ||
          "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-weitao/d724aa70-eac6-11ea-b680-7980c8a877b8.jpg",
        success: (res) => {
          //用户点击分享后的回调,这里可以进行统计,例如分享送金币之类的
          params?.success();
        },
      };
      //分享给朋友接口
      jweixin.onMenuShareAppMessage(shareData);
      //分享到朋友圈接口
      jweixin.onMenuShareTimeline(shareData);
    });
  },

  // 扫码
  scanQRCode(callback) {
    // this.init(() => {
    jweixin.scanQRCode({
      needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
      scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
      success: (res) => {
        callback && callback(res);
      },
      // });
    });
  },

  // 截取url中的code
  getUrlCode() {
    // 截取url中的code方法
    const url = location.search;
    const theRequest = new Object();
    if (url.indexOf("?") != -1) {
      let str = url.substr(1);
      let strs = str.split("&");
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
      }
    }
    return theRequest;
  },
};

2. app.vue 记录第一次进入时的路径

<script>
import Vue from "vue";
export default { 
  onShow: function () {
    uni.setStorageSync("WxCodeUrl", location.href.split('#')[0]);
  },
};
</script>

 3.main.js 全局引入SDK

// 微信SDK
// #ifdef H5
import sdk from "./common/util/sdk.js";

// sdk 
Vue.prototype.$sdk = sdk;

4.页面使用 index.vue

<template> 
 <view>
   <wx-open-launch-weapp
        class="wxOpenLaunchWeapp"
        id="launch-btn"
        appid="小程序 appid"
        username="小程序 账号原始ID"
        path="pages/index/index 要跳转的小程序页面" 
        @launch="handleLaunch"
        @error="handleError"
      >
        <!--vue2 样式只能写在这里才能生效 -->
        <script type="text/wxtag-template">
          <style>
             .btn{
                  height: 86rpx;
                  line-height: 86rpx;
                  font-size: 40rpx;
                  text-align: center;
                  color: #20212B;
                  background-color: #fbfafc;
                }
           </style>
           <div class="btn">进入小程序</div>
        </script>

        <!--vue3要使用component内置组件,尤其是vue3的版本超过3.1.0的 -->
        <component :is="'script'" type="text/wxtag-template">
           <style>
             .btn{
                  height: 86rpx;
                  line-height: 86rpx;
                  font-size: 40rpx;
                  text-align: center;
                  color: #20212B;
                  background-color: #fbfafc;
                }
           </style>
           <div class="btn">进入小程序</div>
        </component>
      </wx-open-launch-weapp>
 </view>
</template>

<script>
export default {
  onLoad: function (option) {
    const token = uni.getStorageSync(ACCESS_TOKEN);
    if (token) {
      // 初始化微信SDK
      this.$sdk.init();
    } else {
      this.$tip.navigateTo("/pages/login/firstlogin");
    }
  },
  methods: {
    handleLaunch(e) {
      console.log("Launch", e);
    },
    handleError(e) {
      console.log("handleError", e);
    },
  },
}
</script>

5.注意事项-报错

6.解决方法

在main.js 里添加一行代码

// Vue.config.ignoredElements = ['wx-open-launch-weapp']; 错误方法 
Vue.config.ignoredElements.push('wx-open-launch-weapp') // 必须是 push,不然会让uniapp的标签失效
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值