微信公众号模板消息推送

第一步:部署中转服务器

  • 搭建一个简单的Web应用,我这里用了SpringBoot搭建的。

  • 微信授权回调地址要求经过备案的域名。所以对于没有自己域名的小伙伴,我推荐你们用免费的花生壳映射地址。以前做微信支付的时候,也用到了花生壳映射地址,所以你们一定要有自己的一个花生壳账号,花生壳分配给你的二级域名,都是备案好了的。当然你有自己本案的域名,那更好了。

    《微信公众号模板消息推送》 image.png

  • 编写一个接口方法
    关键是:拿到code参数,然后发送一个请求,获取用户的openid。

    @RequestMapping("/wxlogin")
    public String wxlogin(HttpServletRequest request) {
        System.out.println("---------------wxlogin---------------");
        String code=request.getParameter("code");
        System.out.println("code:"+code);
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        HashMap<String, Object> params=new HashMap<>();
        params.put("appid", APPID);
        params.put("secret", AppSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        Response response=OkhttpUtils.sendHttp("https://api.weixin.qq.com/sns/oauth2/access_token", 
                params, 
                null, 
                "openid",
                "post");
        String content="";
        try {
            content = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("content:"+content);
        return "index";
    }
    

第二步:设置授权地址

《微信公众号模板消息推送》 image.png

第三步:获取AccessToken

appid和secret两个参数去公众号后台界面获取:

《微信公众号模板消息推送》 image.png

这里我利用我自己写的Okhttp+Rxjava网络请求框架来发送请求:

        HttpClient httpClient = new HttpClient.Builder("https://api.weixin.qq.com/").isDebug(false)
                .connectTimeout(5000)
                .readTimeout(5000)
                .build();
        httpClient.Api().send(new HttpClient.Builder().url("cgi-bin/token")
                .add("grant_type", "client_credential")
                .add("appid", APPID)//写自己的服务号APPID
                .add("secret", AppSecret)//写自己的服务号AppSecret
                .method(Method.GET)
                .build(), new ResultSubscriber<>(new ResultListener<Object>() {

                    @Override
                    public void onResponse(Object t) {
                        System.out.println(t);
                      String access_token=JSON.parseObject(t.toString()).getString("access_token");
               
                      getSendMsgTemple(openid,access_token);
                    }
                }));

第四步:获取用户OpenId

官方文档

测试环境

《微信公众号模板消息推送》 image.png

  • 成功绑定的开发者用手机扫码登录。
    如上图的二维码,注意不是图片二维码识别,是用微信扫一扫登录。
  • 把拼接好的回调url放入开发工具中的浏览器收入框刷新调试,它会提示用户确认登录的界面,你只需要点击确认就可以。
    https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的appid&redirect_uri=你的中转服务器的action地址&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的appid&redirect_uri=你的中转服务器的action地址&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

《微信公众号模板消息推送》 确认登录,获取用户Openid

特别注意:redirect_uri=你的中转服务器的action地址
中的action地址一定要UrlEncode编码。就是redirect_uri的地址,要经过UrlEncode编码,否则微信无法识别。

UrlEncode编码/解码

http://tool.chinaz.com/tools/urlencode.aspx

《微信公众号模板消息推送》 注:回调链接一定要urlencode,不然识别不出

第五步:拼接模板消息

模板消息官方接口文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277

{
    "touser": "o8lZ9uFsI8dHoh4-Kf-EI8babwj4",
    "url":"填写你服务器的url处理地址",
    "template_id": "oi4SokVV7Is0kZz5w8VJG1b3zrLWtApqftCN4iJ3Iyc",
    "data": {
        "first": {
            "value": "小明向您提交了请假条!",
            "color": "#173177"
        },
        "keyword1": {
            "value": "骑车去旅行",
            "color": "#173177"
        },
        "keyword2": {
            "value": "事假",
            "color": "#173177"
        },
        "keyword3": {
            "value": "2018年09月30日 12:00到18:00",
            "color": "#173177"
        },
        "keyword4": {
            "value": "半天",
            "color": "#173177"
        },
  
        "remark": {
            "value": "如有异议,请点击回复!",
            "color": "#173177"
        }
    }
}

第六步:调用发送接口:

    public static void getSendMsgTemple(String openid ,String access_token){
        String json="{\"touser\":\""+openid+"\",\"template_id\":\"oi4SokVV7Is0kZz5w8VJG1b3zrLWtApqftCN4iJ3Iyc\","
                + "\"url\":\""+"http://qq784602719.imwork.net/html/welcome.html"+"\","
                + "\"data\":{\"first\":{\"value\":\"小明向您提交了请假条!\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"骑车去旅行\",\"color\":\"#173177\"},\"keyword2\":{\"value\":\"事假\",\"color\":\"#173177\"},\"keyword3\":{\"value\":\"2018年09月30日 12:00到18:00\",\"color\":\"#173177\"},\"keyword4\":{\"value\":\"半天\",\"color\":\"#173177\"},\"remark\":{\"value\":\"点击模板URL进入调转界面!!!\",\"color\":\"#173177\"}}}";
        HttpClient httpClient = new HttpClient.Builder("https://api.weixin.qq.com/").isDebug(true)  
                .build();
        httpClient.Api().send(new HttpClient.Builder()
                .url("cgi-bin/message/template/send")
                .add("access_token", access_token)
                .add("body", json)
                .httpBase(OkhttpImpl.getInstance())
                .method(Method.POST)
                .build(), new ResultSubscriber<>(new ResultListener<Object>() {

                    @Override
                    public void onResponse(Object t) {
                        System.out.println("发送消息:"+t);
                    
                    }
                }));
        
    }

第七步:最终效果:

《微信公众号模板消息推送》 看效果图,大家就有了奋斗的目标了

参考资料

    原文作者:Arison
    原文地址: https://www.jianshu.com/p/e5f35ad4e8d2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞