javaWeb学习管理后台系统

66 springboot 实现微信公众号消息推送

2019-12-29  本文已影响0人  滔滔逐浪

1,pom 文件里引入下面的类库

    <!--微信模版消息推送三方sdk-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>3.4.0</version>
        </dependency>

2,写一个java推送的controller

package com.taotao.xuexi.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

/**
 * 微信模板消息推送模拟
 */
@RestController
@RequestMapping("/")
public class PushController {


    /**
     * 微信测试账号推送
     */
    @RequestMapping("/push")
    public void push() {
  //1,配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId("wx80d3317081d39f40");//appid
        wxStorage.setSecret("4cd43fb8664340d5b4aed128d122b62d");//appsecret
         WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        //推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("ofuxIwDKv_AQd-32yMzhCMyB_8VI")/要推送的用户openid
                .templateId("ncooK_u20-7QDg5wRYM4buNjkmoVcD_yi7LdyLOVAeI")//模板id
                .url("https://www.jianshu.com/p/65a650c19aa1")//点击模板消息要访问的网址
                .build();
      //3,如果是正式版发送消息,,这里需要配置你的信息

        //        templateMessage.addData(new WxMpTemplateData("name", "value", "#FF00FF"));
        //                templateMessage.addData(new WxMpTemplateData(name2, value2, color2));
        try {
         String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            System.out.println("推送成功:" + msg);
        } catch (Exception e) {
            System.out.println("推送失败:" + e.getMessage());
        e.printStackTrace();
        }


    }


}

访问 http://localhost:8080/push

正常的企业开发,实现微信模板的消息推送,必须有微信公众号,备案的网址,并且最麻烦的一点是要获取用户的openid,作为个人,这些条件基本上都不具备,所以上面的是测试的账号.
1,微信扫码登录下面网址
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
扫码登录成功后,就会给我们生成微信公号的appid和appsecret

2 微信扫码关注 测试号二维码,微信给我们返回我们的openid,这个openid在推送时特别重要。因为你推送肯定要知道推送给 谁啊,就比如你打电话,肯定要知道用户的电话号码吧。这个openid就是我们要推送给那个用户的唯一标示。

上一篇 下一篇

猜你喜欢

热点阅读