uniapp公众号一次性订阅消息(含前后端代码)

应用场景

  1. 用户授权 (前端)
  2. 下发消息 (后端)

实际操作 and 代码

首先来看前端代码吧。

然后在跳转的页面接收参数,参数大概就是这些了。openid=OPENID&template_id=TEMPLATE_ID&action=ACTION&scene=SCENE 这里可以获取到参数,存到后台,适用于多种模板的订阅消息。

if (options) {
          
   
            const {
          
   
                openid,
                action,
                scene
            } = options;
			this.$request(this.$api.Weike.subscribe, {
          
   
               openid: openid,
               action:action,
               scene:scene
             }).then(res => {
          
   
                //授权成功的处理
                 uni.showToast({
          
   
                    title: res.data.msg,
                    icon: none
                 });
             });
        }

后台代码如下: WeChatMsgParam是自己写的实体类,方便管理。

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeChatMsgParam {
          
   
    private String userId;
    private String pubopenId;	//	用户的openid
    private Integer bidTotal; //发送消息的参数,根据需求自己改
    private Integer callTotal;//发送消息的参数,根据需求自己改
}

接下来就发送消息了

大坑

至此就结束了,下面总结一下。

  1. 前端关于重定向地址也就是redirect_url参数,使用文档所说的UrlEncode 会报错,应使用encodeURIComponent,防止组合的url才不会被#等特殊字符截断,报错原因可能是因为vue不支持该方法或者是版本不兼容
  2. redirect_url一定要加到后台的业务域名里去,不要带路径

运行效果

经验分享 程序员 微信小程序 职场和发展