[Springboot] Integrate wxjava to realize WeChat applet: template message


提示:以下是本篇文章正文内容,下面案例可供参考

1. What is the template message?

Template messages are only used for official accounts to send important service notifications to users, and can only be used in service scenarios that meet their requirements, such as credit card swiping notifications, product purchase success notifications, etc. Marketing messages such as advertisements and all other messages that may harass users are not supported.

2. Integration steps:

1. WeChat applet background configuration template message

Subscribe to news:
insert image description here
Choose the template you need according to the actual business, and you can also search.

insert image description hereFor example, I choose this product expiration reminder:
click in,
insert image description here
select the information on the template, and then submit.
View your own templates
insert image description here

2. Send template message

Configuration of wxjava

backend logic code

controller

import com.example.wxjava.common.result.R;
import com.example.wxjava.domain.vo.wx.WxKefuMessageBackVo;
import com.example.wxjava.domain.vo.wx.WxKefuMessageVo;
import com.example.wxjava.service.MessageService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 成大事
 * @since 2022/7/27 23:11
 */
@Slf4j
@RestController
@RequestMapping("/wx/msg")
@AllArgsConstructor
public class WxMessageController {
    
    

    private final MessageService messageService;


    @PostMapping("/sendMessage")
    public R sendMsg() {
    
    
        return messageService.sendMessage();
    }
}

service

import com.example.wxjava.common.result.R;
import com.example.wxjava.domain.vo.wx.WxKefuMessageBackVo;
import com.example.wxjava.domain.vo.wx.WxKefuMessageVo;

/**
 * @author 成大事
 * @since 2022/7/27 23:11
 */
public interface MessageService {
    
    
    /**
     * 发送模板消息
     * @return
     */
    R sendMessage();
}

impl


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.wxjava.common.result.R;
import com.example.wxjava.domain.vo.wx.WxKefuMessageBackVo;
import com.example.wxjava.domain.vo.wx.WxKefuMessageVo;
import com.example.wxjava.service.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author 成大事
 * @since 2022/7/27 23:11
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MessageServiceImpl implements MessageService {
    
    

    private final WxMaService wxMaService;
    @Override
    public R sendMessage() {
    
    
        String userId = StpUtil.getLoginIdAsString();
        // 测试
        List<WxMaSubscribeMessage.MsgData> msgData = Arrays.asList(
                new WxMaSubscribeMessage.MsgData("thing1", "嘿嘿"),
                new WxMaSubscribeMessage.MsgData("date3", new DateTime(DateUtil.now(), DatePattern.NORM_DATETIME_FORMAT).toString())
        );
        try {
    
    
            WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
             		 // 要给谁发送
                    .toUser(userId)
                     // 模板id
                    .templateId("7oklMCAUD0zNAoTWikBOPSwVH2-XKC2-BJVqsUYGxgg")
                     // 数据
                    .data(msgData)
                    .build();
            wxMaService.getMsgService().sendSubscribeMsg(message);
            return R.ok("发送成功");
        } catch (WxErrorException e) {
    
    
            log.error(e.toString());
            return R.error(e.getError().getErrorMsg());
        }
    }

Front-end logic code

<template>
	<view style="padding: 15px;">
		<button @click="submit" type="primary">发送消息</button>
	</view>
</template>

<script>
	let that;
	export default {
      
      
		name: "sedMessage",
		data() {
      
      
			return {
      
      }
		},
		onLoad() {
      
      
			that = this;
		},
		methods: {
      
      
			submit() {
      
      
				uni.requestSubscribeMessage({
      
      
					tmplIds: ['7oklMCAUD0zNAoTWikBOPSwVH2-XKC2-BJVqsUYGxgg'],
					success(res) {
      
      
						console.log("res",res)
						uni.request({
      
      
							url: 'http://localhost:8888/wx/msg/sendMessage',
							method: 'POST',
							success(resc) {
      
      
								console.log("resc",resc)
							}
						})
					}
				});
			}
		},
	}
</script>

<style scoped>

</style>


test:

In WeChat Developer Tools
insert image description here

You can see that the message has been
insert image description here
sent

Guess you like

Origin blog.csdn.net/m0_49683806/article/details/126032661