H5跳转微信小程序。wx-open-launch-weapp 用法

需求分析:

公众号页面内点击按钮,跳转到小程序页面。

查看官方文档。

微信开放文档

1.根据文档第一步通过config接口注入权限验证配置并申请所需开放标签

让后台提供一个接口,返回 一下数据。
appId: data.appId, // 必填,公众号的唯一标识

        timestamp: data.timestamp, // 必填,生成签名的时间戳s 必填,填任意数字即可

        nonceStr: data.nonceStr, // 必填,生成签名的随机串必填,填任意非空字符串即可

        signature: data.signature, // 必填,签名 必填,填任意非空字符串即可
 created() {
    this.wxmini();
  },
  methods: {
    wxmini() {
      let _that = this;
      let params = {
        hospitalCode: localStorage.getItem('hospitalCode'),
        url: location.href.split('#')[0] //当前的url
      }
      api('/wechat/rexxxxxxt/sxxxx', 'post', params).then(res => {
        console.log(res)
        // {
        //   \"openTagList\":[\"wx-open-launch-weapp\"],\"jsApiList\":[\"openLocation\"],\"signature\":\"sdfsdfsdflsdjfsldjflsdjfsdljfsld\",
        //   \"appId\":\"wxxxxxxxxx\",
        //   \"nonceStr\":\"\",\
        // "timestamp\":\"\"}"
        // }j

        if (res.data.data) {
          // let data = JSON.parse(res.data.data)
          let data = res.data.data
          console.log(data)
          wx.config({ // eslint-disable-line

            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印

            appId: data.appId, // 必填,公众号的唯一标识

            timestamp: data.timestamp, // 必填,生成签名的时间戳s 必填,填任意数字即可

            nonceStr: data.nonceStr, // 必填,生成签名的随机串必填,填任意非空字符串即可

            signature: data.signature, // 必填,签名 必填,填任意非空字符串即可

            // jsApiList: ['chooseImage', 'previewImage'],
            jsApiList: ['onMenuShareTimeline',
              'onMenuShareAppMessage',
              'checkJsApi',
              'scanQRCode',
              'chooseImage', 'previewImage',
            ], // 必填,需要使用的JS接口列表

            // jsApiList: data.jsApiList, // 必填,需要使用的JS接口列表

            openTagList: ['wx-open-launch-weapp'] // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
            // openTagList: data.openTagList // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']

          });



          wx.ready(function () {
            console.log('ready')
            // alert('ready')
            var btn = document.getElementById('launch-btn')
            console.log(btn);
            btn.addEventListener('launch', function (e) {
              // alert(e)
              console.log(e);
            })
            btn.addEventListener('error', function (e) {
              // alert(e.detail)
              console.log(e);
            })
          });
          wx.error(function (res) {
            console.log(res);
            // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
          });
        }


        /* eslint-disable */

      })



    },
    handleLaunchFn(e) {
      console.log('success', e);
    },
    handleErrorFn(e) {
      console.log('fail', e.detail);
    },


  },

使用的时候,打开debug ,页面弹出 config:ok,说明注入环境配置成功。
附上问后台要的代码:


/**
 * @author Edward
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/wx/ssssdfsd")
@Api(description = "微信授权")
public class WxRedirectController {

    private final WxMpService wxService;

    @Autowired
    private WxProperties wxProperties;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 创建调用jsapi时所需要的签名.(微信扫一扫)
     */
    @ApiOperation(value = "创建调用jsapi时所需要的签名.(微信扫一扫)", notes = "创建调用jsapi时所需要的签名.(微信扫一扫)")
    @RequestMapping(value = "/signature", method = RequestMethod.POST)
    public CommonResult<WxJsapiSignatureResDto> signature(@RequestBody WxJsapiSignatureReqDto reqDto) {
        log.info("\n微信授权入口,内容:{}", JsonUtils.toJson(reqDto));
        CommonResult commonResult = new CommonResult();
        String appid = wxProperties.getCodeAppidMaps().get(reqDto.getHospitalCode());
        if (org.apache.commons.lang.StringUtils.isBlank(appid)) {
            commonResult.setResult("5000", "无法找到对应【" + reqDto.getHospitalCode() + "】的公众号配置信息,请核实!");
            return commonResult;
        }
        boolean b = this.wxService.switchover(appid);
        if (!b) {
            commonResult.setResult("5000", "无法找到对应【" + appid + "】的公众号配置信息,请核实!");
            return commonResult;
        }
        //WxMpOAuth2AccessToken accessToken = null;
        //try {
        //    accessToken = wxService.oauth2getAccessToken(reqDto.getCode());
        //} catch (WxErrorException e) {
        //    e.printStackTrace();
        //    commonResult.setCode("5002");
        //    commonResult.setMsg("授权失败");
        //    return commonResult;
        //}
        //log.info("\n微信授权出口,内容:{}", JsonUtils.toJson(accessToken));
        if (StringUtils.isBlank(reqDto.getUrl())) {
            commonResult.setResult("5000", "url不能为空");
        }

        WxJsapiSignatureResDto resDto = new WxJsapiSignatureResDto();
        try {
            WxJsapiSignature jsapiSignature = wxService.createJsapiSignature(reqDto.getUrl());
            log.info("\n微信创建调用jsapi时所需要的签名.(微信扫一扫),内容:{}", JsonUtils.toJson(jsapiSignature));
            resDto.setAppId(jsapiSignature.getAppId());
            resDto.setNonceStr(jsapiSignature.getNonceStr());
            resDto.setSignature(jsapiSignature.getSignature());
            resDto.setTimestamp(jsapiSignature.getTimestamp());
            resDto.setUrl(jsapiSignature.getUrl());
        } catch (WxErrorException e) {
            log.error("错误:" + e.getMessage());
            commonResult.setCode("5002");
            commonResult.setMsg("授权失败");
            return commonResult;
        }
        log.info(resDto.toString());
        commonResult.setData(resDto);
        return commonResult;

    }

2.第二步,写html

官方提供的案例:
在这里插入图片描述
所以我们按照官方提供的案例封装成一个组件。

<template>
  <!-- 关于username 与 path的值 参考官方文档  -->
  <wx-open-launch-weapp id="launch-btn" username="gh_XXXXXXXXXX" :path="path" @launch="handleLaunchFn" @error="handleErrorFn">
    <script type="text/wxtag-template">
      <style>
      .btn {
        color:#1578FF;
        font-size:14px;  
      }
      </style>
      <span class="btn">导航</span>
    </script>
  </wx-open-launch-weapp>
</template>

重点:

记得让后台处理url转码

username:’’ // 需要跳转的小程序的id,gh_开头的那个
path:’‘// 跳转的路径,小程序提供的

例:
pages/map/mapView?buildId=0AIA01&url=https%3A%2F%2Fhis.ipalmap.com%2Fnavigation%2Fdist%2Findex.html%23%2Fmap%3FappsId%3D2098%26deptId%3D" + this.headDetail.regdeptid

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值