Uniapp official account one-time subscription message (including front-end and back-end codes)

Reminder: When using uniapp as a one-time subscription message for the official account, the first thing that comes to mind is to view the WeChat open document (https://developers.weixin.qq.com/doc/offiaccount/Message_Management/One-time_subscription_info.html), and then Searching for relevant information on the Internet, I feel that it is a simple small function, but I have done it for 2 to 3 days. I have done both front and back ends, so record it for the reference of netizens. There are some pitfalls I encountered in the process in the article, which is really too much. It's a scam.

Application Scenario

Developers can allow WeChat users to authorize third-party mobile applications (access instructions) or official accounts through one-time subscription message authorization, and get the opportunity to send one subscription message to authorized WeChat users. Authorized WeChat users do not need to follow official accounts. Every time a WeChat user authorizes, the developer can obtain the permission to send messages once. (Note: Multiple authorizations by the same user under the same scene value do not accumulate permission to issue, and only one can be issued. To subscribe to multiple items, different scene scene values ​​are required)

Information on where to send messages: For those who have followed the official account, the message will be sent to the official account session; for those who have not followed the official account, the message will be sent to the service notification.

The official account or web page uses a one-time subscription message process is divided into two parts:

  1. User Authorization (Frontend)
  2. Send message (backend)

Actual operation and code

On the premise of ensuring that the WeChat official account has the authority to subscribe to the message (authenticated official accounts have the authority, you can log in to the official platform to view the interface authority list), guide the user to open the following link on the WeChat client:

https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=wxaba38c7f163da69b&scene=1000&template_id=1uDxHNXwYQfBmXOfPJcjAS3FynHArD8aWMEFNRGSbCc&redirect_url=http%3a%2f%2fsupport.qq.com&reserved=test#wechat_redirect

Let's first look at the front-end code.

auth() {
    
    
				let redirect_url = encodeURIComponent("用户同意接收后跳转的地址,注意需要加到公众号后台业务域名里边");
				let appId = 'appId自己替换哦';
				let scene = 1000(可以自己随便定义);
				let template_id = '申请的订阅消息模板id,也需要注意不是在订阅通知里看模板id,是在接口权限里的一次性订阅消息那看模板id';
				window.location.href =
					`https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=${
    
    appId}&scene=${
    
    scene}&template_id=${
    
    template_id}&redirect_url=${
    
    redirect_url}#wechat_redirect`;
			},

Then receive the parameters on the redirected page, which are probably the parameters. openid=OPENID&template_id=TEMPLATE_ID&action=ACTION&scene=SCENE
parameters can be obtained here and stored in the background, which is suitable for subscription messages of various templates.

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'
                 });
             });
        }

The background code is as follows:
WeChatMsgParam is an entity class written by myself, which is convenient for management.

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

I'll send a message next

public void sendWxMpTemplateMessage(WeChatMsgParam weChatMsgParam) {
    
    
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=" + redisUtil.get("access_token");
        String templateId = "xxx";
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("touser", weChatMsgParam.getPubopenId());
        jsonObject.put("template_id", templateId);
        jsonObject.put("title", "xxx");
        jsonObject.put("scene", "1000");

        Map<String, Map> data = new HashMap<>();
        Map<String, String> first = new HashMap<>();
        first.put("value", "信息:"+weChatMsgParam.getBidTotal()+"条\n"+"信息:"+weChatMsgParam.getCallTotal()+"条");
        first.put("color", "#000000");
        data.put("content", first);
        jsonObject.put("data", data);

        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, jsonObject, String.class);
        System.out.println(responseEntity.getBody());
    }

Tai Hang

This is the end, let's summarize it below.

  1. The front-end is about the redirection address, which is the redirect_url parameter. Using the UrlEncode mentioned in the document will report an error. You should use encodeURIComponent to prevent the combined url from being truncated by special characters such as #. The reason for the error may be that vue does not support this method or version incompatible
  2. The redirect_url must be added to the business domain name in the background, without the path
  3. Another big pit that has tortured me all day is that the front end pays attention to the hash mode. It will splice the parameters incorrectly and cannot recognize your parameters. You can process the forwarded url to obtain the corresponding parameters, or use the history mode without any requirements. Enough
  4. When 43101 is returned when sending a message in the background, it is possible that the user has not subscribed to the message, or there may be a problem with the parameters you sent, go and check it carefully! Finally, I would like to add that if the template message is approved by me, I don’t want to use the official account to subscribe to the message

running result

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_42322886/article/details/127652921