微信推送消息--发送模板消息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信推送消息--发送模板消息相关的知识,希望对你有一定的参考价值。

工具类,详见附件,下载地址:

http://files.cnblogs.com/files/007sx/weixin_util.zip

传的参数参考微信开发者文档-发送模板消息:

http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html#.E5.8F.91.E9.80.81.E6.A8.A1.E6.9D.BF.E6.B6.88.E6.81.AF

全局返回码说明:

http://mp.weixin.qq.com/wiki/17/fa4e1434e57290788bde25603fa2fcbd.html

 

jar包(包括了微信支付所需jar此处一起列出)  pom.xml

复制代码
    <!-- weixin -->
    <dependency>
        <groupId>com.ning</groupId>
        <artifactId>async-http-client</artifactId>
        <version>1.8.13</version>
    </dependency>
    <dependency>
        <groupId>com.thoughtworks.xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
      <groupId>com.gson</groupId>
      <artifactId>wechat</artifactId>
      <version>1.0.8</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.14.4</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>okhttp</artifactId>
        <version>2.7.5</version>
    </dependency>
    <dependency>
    <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.3</version>
    </dependency>
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>org.jdom</groupId>
        <artifactId>jdom</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.7</version>
    </dependency>
复制代码

 注意com.gson wechat 1.0.8 maven中央仓库没有,需要自己导入本地仓库使用,wechat-1.0.8.jar下载地址:

http://files.cnblogs.com/files/007sx/wechat-1.0.8.zip

 

package isa.qa.blep.admin.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import isa.qa.core.weixin.util.WeixinToken;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/api")
public class WeixinMessageController {
    protected static Logger log = Logger.getLogger(WeixinMessageController.class);
    
    public static final String send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    
    /**
     * 发送模板消息
     * @param send_url
     * @param map
     * @return
     */
    @RequestMapping(value = "/weixin/sendMessage/placeOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JSONObject sendMessage(@RequestBody HashMap<String, Object> map) {
        JSONObject jsonObject = null;
        String strJson = mapToJson(map);
        
        try {
            String access_token = WeixinToken.getRecentToken();
            jsonObject = sendMessageUtil(send_url+access_token,strJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    
    /**
     * 将Map转化为Json
     * 
     * @param map
     * @return String
     */
    public static <T> String mapToJson(Map<String, T> map) {
     Gson gson = new Gson();
     String jsonStr = gson.toJson(map);
     return jsonStr;
    }
    
    
    
    /**
     * 发送post请求
     * @param url
     * @throws Exception 
     */
    public static JSONObject sendMessageUtil(String send_url,String strJson) throws Exception {
        StringBuffer sb = new StringBuffer("");
        JSONObject jsonObject = null;
        try{
            //创建连接
            URL url = new URL(send_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            
            //connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");       
            
            connection.connect();

            //POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(strJson.getBytes("UTF-8"));//这样可以处理中文乱码问题
            out.flush();
            out.close();
            
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            System.out.println(sb);
            reader.close();
             jsonObject = JSONObject.fromObject(sb.toString());
             if(jsonObject.get("errcode").equals("0")){
                 throw new Exception(jsonObject.getString("errmsg"));
             }
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    } 
}

传后台:

      {
           "touser":"oL0VOuBXNdeK6J0aFh0RB6A6LTjI",
           "template_id":"w-6o1rsYobEzI2qYfbEocKQ5wewF7bhNJctiGg7J8Fg",
           "url":"http://weixin.qq.com/download",            
           "data":{
                   "first": {
                       "value":"恭喜你购买成功!",
                       "color":"#173177" 
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177" 
                   },
                   "keynote2": {
                       "value":"39.8元",
                       "color":"#173177" 
                   },
                   "keynote3": {
                       "value":"2014年9月22日",
                       "color":"#173177" 
                   },
                   "remark":{
                       "value":"欢迎再次购买!",
                       "color":"#173177" 
                   }
           }
       }

发送成功的返回值:

{
   "errcode": 0,
   "errmsg": "ok",
   "msgid": 540227432
}

 

以上是关于微信推送消息--发送模板消息的主要内容,如果未能解决你的问题,请参考以下文章

php实现微信模板消息推送

微信推送消息--发送模板消息

微信模板消息推送

微信公众号模板消息推送

小程序关联服务号推送模板消息

微信开发-- 发送模板消息