发布时间:2023-02-17 文章分类:编程知识 投稿人:赵颖 字号: 默认 | | 超大 打印

1,微信基础配置WxContanst.java

 1 package com.pgo.modules.inv.subscribe;
 2 
 3 public class WxContanst {
 4 
 5     private static String APPID = "微信公众平台查看APPID";
 6 
 7     private static String SECRET = "微信公众平台查看SECRET";
 8     
 9     //用于测试,后期可维护到数据库中,公众平台配置
10     public static String TEMPLATE_ID_ = "z8eVgH_fEY-s-IE57-jbB0uYySJMb2hysm1yR2zPH0w";
11     
12     
13     // 微信小程序获取tokenURL
14     public static String TOKEN_URL_ = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
15             + WxContanst.APPID + "&secret=" + WxContanst.SECRET;
16 
17     // 获取小程序openid的url
18     public static String URL(String js_code) {
19         return "https://api.weixin.qq.com/sns/jscode2session?appid=" + WxContanst.APPID + "&secret=" + WxContanst.SECRET
20                 + "&js_code=" + js_code + "&grant_type=authorization_code";
21     }
22     
23     /**
24      *  获取消息订阅的Url
25      * @param accessToken接口认证
26      * @return 消息订阅的Url
27      */
28     public static String subscribeUrl(String accessToken){
29         return "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken ;
30     }
31     
32 }

2,http请求工具HttpSendUtils.java

  1 package com.pgo.modules.inv.subscribe;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.net.URI;
  7 import java.util.ArrayList;
  8 import java.util.Iterator;
  9 import java.util.List;
 10 import java.util.Map;
 11 
 12 import org.apache.http.HttpEntity;
 13 import org.apache.http.HttpResponse;
 14 import org.apache.http.HttpStatus;
 15 import org.apache.http.NameValuePair;
 16 import org.apache.http.StatusLine;
 17 import org.apache.http.client.HttpClient;
 18 import org.apache.http.client.entity.UrlEncodedFormEntity;
 19 import org.apache.http.client.methods.CloseableHttpResponse;
 20 import org.apache.http.client.methods.HttpGet;
 21 import org.apache.http.client.methods.HttpPost;
 22 import org.apache.http.entity.StringEntity;
 23 import org.apache.http.impl.client.CloseableHttpClient;
 24 import org.apache.http.impl.client.DefaultHttpClient;
 25 import org.apache.http.impl.client.HttpClients;
 26 import org.apache.http.message.BasicNameValuePair;
 27 import org.apache.http.protocol.HTTP;
 28 import org.apache.http.util.EntityUtils;
 29 import org.hibernate.internal.util.StringHelper;
 30 import org.testng.log4testng.Logger;
 31 
 32 @SuppressWarnings("deprecation")
 33 public class HttpSendUtils {
 34     private static Logger logger = Logger.getLogger(HttpSendUtils.class);
 35 
 36     /**
 37      * get请求
 38      * 
 39      * @return
 40      */
 41     public static String doGet(String url) {
 42         try {
 43             HttpClient client = new DefaultHttpClient();
 44             // 发送get请求
 45             HttpGet request = new HttpGet(url);
 46             HttpResponse response = client.execute(request);
 47 
 48             /** 请求发送成功,并得到响应 **/
 49             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
 50                 /** 读取服务器返回过来的json字符串数据 **/
 51                 String strResult = EntityUtils.toString(response.getEntity());
 52 
 53                 return strResult;
 54             }
 55         } catch (IOException e) {
 56             e.printStackTrace();
 57         }
 58 
 59         return null;
 60     }
 61 
 62     /**
 63      * post请求(用于key-value格式的参数)
 64      * 
 65      * @param url
 66      * @param params
 67      * @return
 68      */
 69     public static String doPost(String url, Map params) {
 70 
 71         BufferedReader in = null;
 72         try {
 73             // 定义HttpClient
 74             HttpClient client = new DefaultHttpClient();
 75             // 实例化HTTP方法
 76             HttpPost request = new HttpPost();
 77             request.setURI(new URI(url));
 78 
 79             // 设置参数
 80             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
 81             for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
 82                 String name = (String) iter.next();
 83                 String value = String.valueOf(params.get(name));
 84                 nvps.add(new BasicNameValuePair(name, value));
 85 
 86                 // System.out.println(name +"-"+value);
 87             }
 88             request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
 89 
 90             HttpResponse response = client.execute(request);
 91             int code = response.getStatusLine().getStatusCode();
 92             if (code == 200) { // 请求成功
 93                 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
 94                 StringBuffer sb = new StringBuffer("");
 95                 String line = "";
 96                 String NL = System.getProperty("line.separator");
 97                 while ((line = in.readLine()) != null) {
 98                     sb.append(line + NL);
 99                 }
100 
101                 in.close();
102 
103                 return sb.toString();
104             } else { //
105                 System.out.println("状态码:" + code);
106                 return null;
107             }
108         } catch (Exception e) {
109             e.printStackTrace();
110 
111             return null;
112         }
113     }
114 
115     /**
116      * post请求(用于请求json格式的参数)
117      * 
118      * @param url
119      * @param params
120      * @return
121      */
122     public static String doPost(String url, String params) throws Exception {
123         System.out.println("==============="+params+"=====================");
124         CloseableHttpClient httpclient = HttpClients.createDefault();
125         HttpPost httpPost = new HttpPost(url);// 创建httpPost
126         httpPost.setHeader("Accept", "application/json");
127         httpPost.setHeader("Content-Type", "application/json");
128         String charSet = "UTF-8";
129         if(StringHelper.isNotEmpty(params)){
130             StringEntity entity = new StringEntity(params, charSet);
131             httpPost.setEntity(entity);
132         }
133         CloseableHttpResponse response = null;
134 
135         try {
136 
137             response = httpclient.execute(httpPost);
138             StatusLine status = response.getStatusLine();
139             int state = status.getStatusCode();
140             if (state == HttpStatus.SC_OK) {
141                 HttpEntity responseEntity = response.getEntity();
142                 String jsonString = EntityUtils.toString(responseEntity);
143                 return jsonString;
144             } else {
145                 //logger.error("请求返回:" + state + "(" + url + ")");
146             }
147         } finally {
148             if (response != null) {
149                 try {
150                     response.close();
151                 } catch (IOException e) {
152                     e.printStackTrace();
153                 }
154             }
155             try {
156                 httpclient.close();
157             } catch (IOException e) {
158                 e.printStackTrace();
159             }
160         }
161         return null;
162     }
163 }

3,微信操作工具类WxUtils.java:

 1 package com.pgo.modules.inv.subscribe;
 2 
 3 import java.util.Map;
 4 
 5 import com.google.gson.Gson;
 6 import com.pgo.modules.doradoframework.base.BaseBO;
 7 
 8 public class WxUtils extends BaseBO {
 9     /**
10      * 获取微信openId
11      * 
12      * @param param
13      * @return
14      * @throws Exception
15      */
16     @SuppressWarnings("unchecked")
17     public static String getOpenIdByCode(String code, String param) throws Exception {
18         String openid = HttpSendUtils.doPost(WxContanst.URL(code), param);
19         Gson gson = new Gson();
20         Map<String, Object> res = gson.fromJson(openid, Map.class);
21         return (String) res.get("openid");
22     }
23 
24     /**
25      * 获取微信access_token_
26      * 
27      * @param param
28      * @return
29      * @throws Exception
30      */
31     @SuppressWarnings("unchecked")
32     public static String getAccessToken(String param) throws Exception {
33         String token = HttpSendUtils.doPost(WxContanst.TOKEN_URL_, param);
34         Gson gson = new Gson();
35         Map<String, Object> res = gson.fromJson(token, Map.class);
36         return (String) res.get("access_token");
37     }
38 
39     // 通过关联的用户表查找openId
40     public static String getOpenIdByUserId(String userId) throws Exception {
41         // 此处为模拟测试,后期通过登录后保存的code直接使用
42         String code = "";
43         return WxUtils.getOpenIdByCode(code, null);
44     }
45     
46     /**
47      * 获取订阅消息的Url
48      * @return url
49      * @throws Exception
50      */
51     public static String getSubUrl() throws Exception{
52         return WxContanst.subscribeUrl(WxUtils.getAccessToken(null));
53     }
54     /**
55      * 受框架影响openId可以直接从后台获取
56      * @param userId 用户的id
57      * @return openId
58      * @throws Exception
59      */
60     public static String getOpenIdDub1(String userId) throws Exception {
61         
62         return null;
63     }
64 
65 }

4,微信模板操作工具类WxSubscribeMessageUtils.java

 1 package com.pgo.modules.inv.subscribe;
 2 
 3 import java.util.HashMap;
 4 import java.util.List;
 5 import java.util.Map;
 6 import java.util.Map.Entry;
 7 
 8 import com.alibaba.fastjson.JSONObject;
 9 import com.pgo.modules.common.du.domain.Tbdub1;
10 import com.pgo.modules.core.support.Result;
11 /**
12  * 通用订阅模板发送处理类
13  * @author baolu
14  *
15  */
16 public class WxSubscribeMessageUtils {
17 
18     /**
19      * 消息模板通用设置
20      * @param parameter 模板参数
21      * @param template_id 模板ID
22      * @param userId 用户ID
23      * @param pageIndex 消息跳转的画面
24      * @return 发送结果
25      * @throws Exception
26      * 注:获取用户的openId可以灵活获取。
27      * 1,通过调用WxUtils.getOpenIdByUserId(userId),但是需要数据库存储openID和userId;
28      * 2,通过前端code调用getOpenIdByCode(code , paramer)获取openId
29      */
30     public static Result  sendMessage(String toUserOpenId , Map<String , Object> parameter , String template_id , String userId , String pageIndex) throws Exception{
31         JSONObject templateData = new JSONObject();
32         //设置用户的openId,此处受到框架后台处理,可直接取openid,
33         //所以WxUtils.getOpenIdByUserId(null)暂时弃用
34         //WxUtils.getOpenIdByUserId(null);
35         //测试发送给管理员的消息
36         templateData.put("touser", toUserOpenId);
37         //设置订阅消息模板ID
38         templateData.put("template_id", template_id);
39         //设置点击消息跳转路径
40         templateData.put("page", pageIndex);
41         //设置消息内容
42         JSONObject data = new JSONObject();
43         for(Entry<String, Object> vo : parameter.entrySet()){
44             Map<String , Object> value = new HashMap<String , Object>();
45             value.put("value", vo.getValue());
46             data.put(vo.getKey() , value);
47         }
48         templateData.put("data", data);
49         //发送订阅消息的请求
50         String resMessage = HttpSendUtils.doPost(WxUtils.getSubUrl() , templateData.toString());
51         Result res = new Result("1" , resMessage);
52         return res;
53     }
54 }

5,测试代码:

package com.pgo.modules.inv.subscribe;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.pgo.modules.core.support.Result;
/**
 * 订阅消息模板发送
 * @author baolu
 *
 */
public class SubscribeMessage {
    //测试消息发送是否成功
    public static void main(String[] arg) throws Exception{
        Map<String , Object> mp = new HashMap<String , Object>();
        mp.put("name1", "通知");
        mp.put("date2", "2013-01-01");
        mp.put("time3", "16:28:00");
        Result sendMessage = WxSubscribeMessageUtils.sendMessage("oglgM5Pi2MF8KbC6_PhCtFw6o2HI" , mp, WxContanst.TEMPLATE_ID_, "admin", "pages/login/login");
            System.out.println(sendMessage.getMessage());
    }
}

注意:access_token_有时间限制和请求次数限制,可以存放在redis或者内存中,这里没有做处理,请参考微信小程序开发手册