1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 微信公众号(事件回调生成带参数二维码扫码关注事件消息模板推送)java版

微信公众号(事件回调生成带参数二维码扫码关注事件消息模板推送)java版

时间:2022-12-06 21:00:17

相关推荐

微信公众号(事件回调生成带参数二维码扫码关注事件消息模板推送)java版

1.业务处理(全部业务)

import com.alibaba.fastjson.JSONObject;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.Map;@RestController@RequestMapping("/wxPublic")public class WxPublic {private static final String APPID = "****公众号配置****";private static final String APPSECRET = "****公众号配置****";private static final String ACCESS_TOKEN_URL = "https://api./cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";private static final String TICKET_URL = "https://api./cgi-bin/qrcode/create?access_token=ACCESSTOKEN";private static final String CODE_URL = "https://mp./cgi-bin/showqrcode?ticket=TICKET";private static final String TEMPLATE_ID = "****公众号配置****";/**** 微信服务器触发get请求用于检测签名* @return*/@GetMapping("/receiveWx")@ResponseBodypublic String handleWxCheckSignature(HttpServletRequest request) {return request.getParameter("echostr");}/*** 微信公众号回调事件** @param wxServiceMsgDto* @return*/@PostMapping(value = "receiveWx")public String checkWxToken(@RequestBody(required = false) WxServiceMsgDto wxServiceMsgDto) {System.out.println("所有事件" + wxServiceMsgDto);//处理带参数请求if (null != wxServiceMsgDto &&!StringUtils.isEmpty(wxServiceMsgDto.getMsgType()) &&!StringUtils.isEmpty(wxServiceMsgDto.getEvent()) &&!StringUtils.isEmpty(wxServiceMsgDto.getEventKey())&& !wxServiceMsgDto.getEventKey().equals("null") &&(wxServiceMsgDto.getEventKey().equals("subscribe") || wxServiceMsgDto.getEvent().equals("SCAN"))) {//发送消息try {String token = getToken();SendWeChatMsg(token, wxServiceMsgDto.getFromUserName());} catch (Exception e) {e.printStackTrace();System.out.println("消息发送失败");}//关注if(wxServiceMsgDto.getEvent().equals("subscribe")){System.out.println("关注: " + wxServiceMsgDto.getFromUserName());if(wxServiceMsgDto.getEventKey().contains("FenXiangMa")){System.out.println("优惠券领取");}}//扫码if(wxServiceMsgDto.getEvent().equals("SCAN")){System.out.println("扫码: " + wxServiceMsgDto.getFromUserName());if(wxServiceMsgDto.getEventKey().contains("YaoQingMa")){System.out.println("新用户邀请");}}System.out.println("参数: " + wxServiceMsgDto.getEventKey());}return "";}/*** 获取token** @return token*/public static String getToken() {// 授予形式String grant_type = "client_credential";//应用IDString appid = APPID;//密钥String secret = APPSECRET;// 接口地址拼接参数String getTokenApi = "https://api./cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret;String tokenJsonStr = HttpUtil.doGetPost(getTokenApi, "GET", null);JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);String token = tokenJson.get("access_token").toString();return token;}/**** 发送消息** @param token*/public static void SendWeChatMsg(String token, String fromUserName) {// 接口地址String sendMsgApi = "https://api./cgi-bin/message/template/send?access_token=" + token;//封装消息Map<String, Object> params = new HashMap<String, Object>();params.put("touser", fromUserName);params.put("template_id", TEMPLATE_ID);Map<String, Object> tempdata = new HashMap<>();Map<String, Object> first = new HashMap<>();first.put("value", "测试");tempdata.put("first", first);Map<String, Object> keyword1 = new HashMap<>();keyword1.put("value", "满五十减一百");tempdata.put("keyword1", keyword1);Map<String, Object> keyword2 = new HashMap<>();keyword2.put("value", "试试");tempdata.put("keyword2", keyword2);Map<String, Object> keyword3 = new HashMap<>();keyword3.put("value", "无");tempdata.put("keyword3", keyword3);Map<String, Object> keyword4 = new HashMap<>();keyword4.put("value", "无");tempdata.put("keyword4", keyword4);Map<String, Object> keyword5 = new HashMap<>();keyword5.put("value", "请及时查看");tempdata.put("keyword5", keyword5);params.put("data", tempdata);String post = HttpUtil.doGetPost(sendMsgApi, "POST", params);System.out.println("消息发送成功: " + post);}/*** 获取公众号二维码Url** @return 返回拿到的access_token及有效期*/public static String getCodeUrl(String info) {String codeUrl = null;String access_token = null;String ticket = null;try {//获取AccessTokentry {String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);//将URL中的两个参数替换掉Map<String, Object> tokenMap = HttpUtil.doGet(url);access_token = String.valueOf(tokenMap.get("access_token"));System.out.println("access_token: " + tokenMap);} catch (Exception e) {System.out.println("获取access_token发生错误");e.printStackTrace();return null;}//获取Ticket接口try {String url = TICKET_URL.replace("ACCESSTOKEN", access_token);String data = "{\"expire_seconds\": 2592000, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + info + "\"}}}";Map<String, Object> ticketMap = HttpUtil.doPost(url, data, 5000);ticket = String.valueOf(ticketMap.get("ticket"));System.out.println("ticket: " + ticket);} catch (Exception e) {System.out.println("获取access_token发生错误");e.printStackTrace();return null;}} catch (Exception e) {System.out.println("获取公众号二维码Url发生错误");e.printStackTrace();return null;}codeUrl = CODE_URL.replace("TICKET", ticket);System.out.println("二维码地址(30天过期): " + codeUrl);return codeUrl;}public static void main(String[] args) {getCodeUrl("参数一");getCodeUrl("参数二");}}

2.引用封装

import com.alibaba.fastjson.JSON;import com.google.gson.Gson;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import .HttpURLConnection;import .URL;import .URLConnection;import java.util.HashMap;import java.util.Map;/*** http工具类*/public class HttpUtil {private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);private static final Gson gson = new Gson();/*** get方法** @param url* @return*/public static Map<String, Object> doGet(String url) {Map<String, Object> map = new HashMap<>();CloseableHttpClient httpClient = HttpClients.createDefault();RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) //连接超时.setConnectionRequestTimeout(5000)//请求超时.setSocketTimeout(5000).setRedirectsEnabled(true) //允许自动重定向.build();HttpGet httpGet = new HttpGet(url);httpGet.setConfig(requestConfig);try {HttpResponse httpResponse = httpClient.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == 200) {String jsonResult = EntityUtils.toString(httpResponse.getEntity());map = gson.fromJson(jsonResult, map.getClass());}} catch (Exception e) {e.printStackTrace();} finally {try {httpClient.close();} catch (Exception e) {e.printStackTrace();}}return map;}/*** 封装post** @return*/public static Map<String, Object> doPost(String url, String data, int timeout) {Map<String, Object> map = new HashMap<>();CloseableHttpClient httpClient = HttpClients.createDefault();//超时设置RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout) //连接超时.setConnectionRequestTimeout(timeout)//请求超时.setSocketTimeout(timeout).setRedirectsEnabled(true) //允许自动重定向.build();HttpPost httpPost = new HttpPost(url);httpPost.setConfig(requestConfig);httpPost.addHeader("Content-Type", "text/html; chartset=UTF-8");if (data != null && data instanceof String) { //使用字符串传参StringEntity stringEntity = new StringEntity(data, "UTF-8");httpPost.setEntity(stringEntity);}try {CloseableHttpResponse httpResponse = httpClient.execute(httpPost);HttpEntity httpEntity = httpResponse.getEntity();if (httpResponse.getStatusLine().getStatusCode() == 200) {String result = EntityUtils.toString(httpEntity);map = gson.fromJson(result, map.getClass());return map;}} catch (Exception e) {e.printStackTrace();} finally {try {httpClient.close();} catch (Exception e) {e.printStackTrace();}}return null;}/*** 调用接口 post* @param apiPath*/public static String doGetPost(String apiPath, String type, Map<String, Object> paramMap){OutputStreamWriter out = null;InputStream is = null;String result = null;try{URL url = new URL(apiPath);// 创建连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestMethod(type) ; // 设置请求方式connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式connection.connect();if(type.equals("POST")){out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码out.append(JSON.toJSONString(paramMap));out.flush();out.close();}// 读取响应is = connection.getInputStream();int length = (int) connection.getContentLength();// 获取长度if (length != -1) {byte[] data = new byte[length];byte[] temp = new byte[512];int readLen = 0;int destPos = 0;while ((readLen = is.read(temp)) > 0) {System.arraycopy(temp, 0, data, destPos, readLen);destPos += readLen;}result = new String(data, "UTF-8"); // utf-8编码}} catch (IOException e) {e.printStackTrace();} finally {try {is.close();} catch (IOException e) {e.printStackTrace();}}return result;}}

import lombok.Data;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;/*** 公众号返回参数封装*/@XmlRootElement(name = "xml")@XmlAccessorType(XmlAccessType.FIELD)@Datapublic class WxServiceMsgDto {@XmlElement(name = "Event")private String event;@XmlElement(name = "Content")private String content;@XmlElement(name = "MsgType")private String msgType;@XmlElement(name = "ToUserName")private String toUserName;@XmlElement(name = "EventKey")private String eventKey;@XmlElement(name="CreateTime")private String createTime;/*** fromUserName为关注人的openId**/@XmlElement(name = "FromUserName")private String fromUserName;}

欢迎关注哦~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。