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

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

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

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
}

 

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

上一篇:微信开发第5章 通过accesstoken获取用户基本信息并修改用户备注


下一篇:微信公众号开发--开发服务器接入微信服务器