微信公众号获取关注者列表以及消息推送

编程入门 行业动态 更新时间:2024-10-10 23:16:04

微信<a href=https://www.elefans.com/category/jswz/34/1769853.html style=公众号获取关注者列表以及消息推送"/>

微信公众号获取关注者列表以及消息推送

一、微信公众号获取token

/*微信提供获取access_token接口地址*/private static final String access_token_url = "=client_credential";/*第三方用户唯一凭证*/private static final String APPID = "wx644f********";/*第三方用户唯一凭证密钥,即appsecret*/private static final String SECRET = "342f9a33a**********";public String getToken() {String tokenGetUrl = access_token_url;//微信提供获取access_token接口地址String appid = APPID;String secret = SECRET;JSONObject tokenJson = new JSONObject();if (StringUtils.isNotBlank(appid) && StringUtils.isNotBlank(secret)) {tokenGetUrl += "&appid=" + appid + "&secret=" + secret;tokenJson = new WeixinUtil().getUrlResponse(tokenGetUrl);try {return (String) tokenJson.get("access_token");} catch (JSONException e) {return null;}} else {return null;}}

二、获取微信公众号关注用户

官方接口文档:.html
/*获取微信公众号关注用户接口地址*/private static final String get_userInfo_url = "";//传入获取的access_token获取微信关注用户列表public Set<String> getUsers(String access_token) {String usersGetUrl = get_userInfo_url;usersGetUrl += "?access_token=" + access_token;org.json.JSONObject data = new WeixinUtil().getUrlResponse(usersGetUrl);System.out.println("~~~~~用户信息:" + data.toString());Set<String> openIds = new HashSet<String>();Integer total = 0, count = 0;try {total = (Integer) data.get("total");count = (Integer) data.get("count");//总关注用户数超过默认一万if (count < total) {openIds.addAll(getUsers(openIds, usersGetUrl, access_token, (String) data.get("next_openid")));} else {//有关注者 json才有data参数if (count > 0) {org.json.JSONObject openIdData = (org.json.JSONObject) data.get("data");JSONArray openIdArray = (JSONArray) openIdData.get("openid");for (int i = 0; i < openIdArray.length(); i++) {openIds.add((String) openIdArray.get(i));}}}} catch (JSONException e) {e.printStackTrace();}return openIds;}

获取微信关注用户具体信息包括openid和unionid

 /*** 获取用户信息* @param access_token  微信公众号token* @param useropenid 用户openid* @return*/
public Record finduserInfo(String access_token, String useropenid) {String usersfindUrl = find_userInfo_url;usersfindUrl += "?access_token=" + access_token + "&openid=" + useropenid;JSONObject data = new WeixinUtil().getUrlResponse(usersfindUrl);System.out.println("用户信息====" + data);return data;}

 

WeixinUtil()类
package com.ddm.system.qywx;
import io.swagger.annotations.Api;
import org.apachemons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import org.json.JSONObject;import org.springframework.context.annotation.Scope;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import java.io.IOException;
import java.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;@RestController
@RequestMapping(value = "/WeixinUtil")
@Api(value = "WeixinUtil.*")
@Scope("prototype")//多例模式
public class WeixinUtil {public JSONObject getUrlResponse(String url) {CharsetHandler handler = new CharsetHandler("UTF-8");try {HttpGet httpget = new HttpGet(new URI(url));HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();//HttpClientCloseableHttpClient client = httpClientBuilder.build();client = (CloseableHttpClient) wrapClient(client);return new JSONObject(client.execute(httpget, handler));} catch (Exception e) {e.printStackTrace();return null;}}public static HttpClient wrapClient(HttpClient base) {try {SSLContext ctx = SSLContext.getInstance("TLSv1");X509TrustManager tm = new X509TrustManager() {public void checkClientTrusted(X509Certificate[] xcs,String string) throws CertificateException {}public void checkServerTrusted(X509Certificate[] xcs,String string) throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return null;}};ctx.init(null, new TrustManager[]{tm}, null);SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();return httpclient;} catch (Exception ex) {return null;}}public class CharsetHandler implements ResponseHandler<String> {private String charset;public CharsetHandler(String charset) {this.charset = charset;}public String handleResponse(HttpResponse response)throws ClientProtocolException, IOException {StatusLine statusLine = response.getStatusLine();if (statusLine.getStatusCode() >= 300) {throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());}HttpEntity entity = response.getEntity();if (entity != null) {if (!StringUtils.isBlank(charset)) {return EntityUtils.toString(entity, charset);} else {return EntityUtils.toString(entity);}} else {return null;}}}
}

三、消息推送

 /*** 客户订单信息推送给用户* @param unionid 用户unionid* @return*/@PostMapping("/OrderTempMsg")public boolean OrderTempMsg(Object unionid) {String openId = "o1NS86Qshm94aftSCew******"; //用户openidString templateId = "WCOPQyRW_9QolNU********";//消息模板idRecord json = new Record();json.set("first", new Record().set("value","您已成功下达订单,商家将在5分钟内受理订单"));json.set("keyword1", new Record().set("value","20160822161230")); //订单编号json.set("keyword2", new Record().set("value","2023/04/04 15:30:25")); //下单时间json.set("remark", new Record().set("value","如有疑问,请联系点送客服 5008654228......"));return sendTempMsg(openId, templateId, json);}//针对用户openid发送消息推送
public boolean sendTempMsg(String openId, String template_id, Record data) {Record json = new Record();Record json1 = new Record();json1.set("appid","123******");json1.set("pagepath","pages/login/login");//消息模板跳转微信小程序(需要小程序与公众号进行关联)json.set("touser", openId);json.set("template_id", template_id);json.set("url", "");json.set("miniprogram", json1);json.set("data", data);String url = "=" + getAccessToken();String jsonStr = HtmlTools.postJSON(url, json.toJson());JSONObject jsonObject = JsonTools.strToJson(jsonStr);if (jsonObject.get("errcode") != null && jsonObject.getInteger("errcode") == 0) {return true;} else {logger.info("weixin sendTempMsg 错误:" + jsonObject);return false;}}

更多推荐

微信公众号获取关注者列表以及消息推送

本文发布于:2024-03-23 18:11:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1741245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:公众   消息   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!