首页 > 编程语言 >重点--微信公众号(事件回调&生成带参数二维码&扫码关注事件&消息模板推送)java版

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

时间:2022-11-25 23:45:24浏览次数:51  
标签:扫码 java String -- token new import wxServiceMsgDto out

 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.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static final String TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESSTOKEN";
private static final String CODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
private static final String TEMPLATE_ID = "****公众号配置****";


/***
* 微信服务器触发get请求用于检测签名
* @return
*/
@GetMapping("/receiveWx")
@ResponseBody
public 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";
//应用ID
String appid = APPID;
//密钥
String secret = APPSECRET;
// 接口地址拼接参数
String getTokenApi = "https://api.weixin.qq.com/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.weixin.qq.com/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 {
//获取AccessToken
try {
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 java.net.HttpURLConnection;
import java.net.URL;
import java.net.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)
@Data
public 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;

}

 

转自:https://blog.csdn.net/qq_37176273/article/details/124289442

 

标签:扫码,java,String,--,token,new,import,wxServiceMsgDto,out
From: https://www.cnblogs.com/javalinux/p/16926669.html

相关文章

  • 102. 二叉树的层序遍历
    102.二叉树的层序遍历给你二叉树的根节点root,返回其节点值的层序遍历。(即逐层地,从左到右访问所有节点)。示例1:输入:root=[3,9,20,null,null,15,7]输出:[[3],......
  • 2022-2023-1 20221318 《计算机基础和程序设计》第十三周学习总结
    作业信息这个作业属于那个班级https://edu.cnblogs.com/campus/besti/2022-2023-1-CFAP作业要求https://www.cnblogs.com/rocedu/p/9577842.html#WEEK13作业目标学习......
  • Git and GitHub workflow
    GitandGitHubworkflowgitclone//到本地gitcheckout-bxxx切换至新分支xxx(相当于复制了remote的仓库到本地的xxx分支上修改或者添加本地代码(部署在硬盘的源文......
  • 《ASP.NET Core技术内幕与项目实战》精简集-DDD准备5.3:值对象
    本节内容,部分为补充内容,部分涉及到9.3(P321-326)。主要NuGet包:无 一、使用值对象的两种情形及其EFCore映射配置1、没有标识符的从属实体类如商店的地理位置,包含经度和......
  • P3387 缩点
     缩点求DAG最长路#include<bits/stdc++.h>usingnamespacestd;constintN=1e4+2;intn,m,pool,a[N];intlow[N],dfn[N];intkcnt,id[N];intf[N],v......
  • 【Java】EasyCaptcha 封装验证码接口
     依赖坐标:<dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId><version>1.6.2......
  • go文件&&目录操作
    一:常规文件1.go读取文件第一种做法【案例就是复制文件】filePath:="./show.txt"copyFilepath:="./copy.txt"file,_:=os.Open(filePath)deferfile.Close()......
  • flex布局
    网页布局(layout)是CSS的一个重点应用。  Flex是FlexibleBox的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性。任何一个容器都可以指定为Flex布局。.box{di......
  • 一文了解 Go 中的指针和结构体
    耐心和持久胜过激烈和狂热。前言前面的两篇文章对Go语言的基础语法和基本数据类型以及几个复合数据类型进行介绍,本文将对Go里面的指针和结构体进行介绍,也为后续文章做铺......
  • 2015年热恋的肉肉们
    整理笔记,顺便留个纪念。 2.293.11​​​​​​​​康平寿​​​​​​​​桃美人白鸟​​​​​​​​​​​​白美人钱串新玉缀雪域女雏密叶莲静夜​​​​​​​​​​​......