本文是 后段程序向測試號發消息
1,微信掃碼登錄下面網址
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
掃碼登錄成功后,就會給我們生成微信公號的appid和appsecret
2,當前頁往下翻,微信掃碼關注 測試號二維碼,微信給我們返回我們的openid,這個openid在推送時特別重要。代碼會用到它。
3,再往下翻 ,如圖點擊新增測試模板填寫模板標題 模板內容 點擊確定后會返回模板ID
隨便寫個模板標題
模板內容 可以自定義
{{first.DATA}} 領品:{{keyword1.DATA}} 領獎 時間: {{keyword2.DATA}} 領獎地址:{{keyword3.DATA}} 過期時間: {{keyword4.DATA}} {{remark.DATA}}
4,創建springboot工程 pom引入一下
<!--微信模版消息推送三方sdk--> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>3.3.0</version> </dependency>
5,編寫controller
@RestController public class PushController { /* * 微信測試賬號推送 * */ @GetMapping("/push") public void push() { //1,配置 WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage(); wxStorage.setAppId("wx1cc543a07a6511e8");//appID wxStorage.setSecret("d69ce22cc5c07d871ea159da526fa179");//appsecret WxMpService wxMpService = new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(wxStorage); //2,推送消息 WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() .toUser("o7put6qeqg3a1SqImNrgqP_TKIWw")//要推送的用戶openid .templateId("eTBW2GvzfMP-mTEjAECE9Owt1I72XX59PfLbydkxNq8")//模版ID .url("https://home.cnblogs.com/u/wf-zhang/")//點擊模板消息 下方詳情訪問的網址 .build(); try {
//這里的first到remark的值 和 模板消息的配置的一 一 對應 List<WxMpTemplateData> data = Arrays.asList( new WxMpTemplateData("first", "親,請記得獎品哈。"), new WxMpTemplateData("keyword1", "茅台500箱"), new WxMpTemplateData("keyword2", DateUtil.now()), new WxMpTemplateData("keyword3", "聚源大酒店"), new WxMpTemplateData("keyword4", "永不過期"), new WxMpTemplateData("remark", "歡迎再次光臨!") ); templateMessage.setData(data); wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); } catch (Exception e) { System.out.println("推送失敗:" + e.getMessage()); e.printStackTrace(); } } }
6,啟動項目 瀏覽器或者postman調用地址 http://localhost:8080/push
7,推送結果
點擊詳情就是代碼中的網址("https://home.cnblogs.com/u/wf-zhang/") 這里是博客園網址