当前位置:网站首页>Use WeChat official account to send information to designated WeChat users
Use WeChat official account to send information to designated WeChat users
2022-08-01 20:03:00 【Su Qi qaq】
1.Write an interface to verify whether the WeChat party is successfully connected
/*参数 描述
signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数.
timestamp 时间戳
nonce 随机数
echostr 随机字符串*/
@ApiOperation("Verify whether the WeChat party is successfully connected")
@GetMapping("/weChat") //getThe method is to verify whether the WeChat party is successfully connected
public String validate(String signature,String timestamp,String nonce,String echostr)
{
//1)将token、timestamp、nonce三个参数进行字典序排序
String[] arr = {WeChatUtils.TOKEN,timestamp,nonce};
Arrays.sort(arr);
//2)将三个参数字符串拼接成一个字符串进行sha1加密
String str = arr[0]+arr[1]+arr[2];
String mySignature = sha1(str);
//Get your own encrypted signature
//3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
if(StringUtils.equals(mySignature,signature))
{
//原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
return echostr;
}
return null;
}
注意:tokento be configured withtoken一致
package com.guigusuqi.commonutils.utils;
public class WeChatUtils
{
public static final String TOKEN = "guigusuqi7";
}
2.配置接口信息,In order to verify whether the WeChat party is successfully connected
The premise is that it needs to be usednginx把80端口的URLProxy to the interface path in the project
upstream questionnaire
{
server 127.0.0.1:8002;
}
server
{
listen 80;
server_name suqiqaq.cn;
location ~ /officialAccount/weChat
{
proxy_pass http://questionnaire;
}
}
3.Start using the test number of the WeChat public platform to call the interface
WeChat test number configures the test number
4.配置yaml:
weChat:
appID: wx6dda2178c44e613a
appsecret: 0ea9dc58811790c5115e4d44f86ed5f2
templateID: lcNTMFxkf0TlhOVryVHSadjgBG9G5nXaVefkyZ8O9es # 模板id
getAccessTokenUrl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${weChat.appID}&secret=${weChat.appsecret} # 获取accessTokenUrl
url: https://wj.qq.com/s2/9294970/8014 # 用户点击信息 跳转的url
5.编写接口,Send user request
@Override
public Result sendTemplateInfo(JSONObject jsonData) throws Exception
{
//获取小程序accessToken
String accessToken = obtainAccessTokenUtils.obtainAccessToken();
//消息推送接口
String path = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
String result = HttpClientUtils.doPost(path, jsonData.toJSONString());
//Parse the WeChat return result into json对象
//Determine the result of sending the template message
JSONObject obj = JSONObject.parseObject(result);
//将json对象赋值给map
Map<String, Object> map = obj;
//获取错误码 如果code为0,errmsg为ok 代表成功
Integer code = (Integer)map.get("errcode");
String msg = map.get("errmsg").toString();
if (0 != code || !"ok".equals(msg))
{
return Result.fail().code(code).message("消息推送失败,"+msg);
}
return Result.success().message("消息推送成功!");
}
5.1编写接口,通过发送请求getAccessTokenUrl获取access_token
package com.guigusuqi.commonutils.utils;
import com.alibaba.fastjson.JSONObject;
import com.guigusuqi.commonutils.exceptionHandler.GlobalExceptionHandler;
import com.guigusuqi.commonutils.exceptionHandler.HospitalException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
import java.util.Map;
/**
* The official account sends template information to what users needaccess_token
*/
@Component
public class ObtainAccessTokenUtils
{
@Value("${weChat.getAccessTokenUrl}")
String getAccessTokenUrl;
/**
* 获取AccessToken
* @return
*/
public String obtainAccessToken() throws IOException
{
// 返回的用户信息json字符串
String result = HttpClientUtils.doPost(getAccessTokenUrl, "");
JSONObject obj = JSONObject.parseObject(result);
Map<String, Object> map =obj;
try {
//Take it out of the resultsaccess_token
String access_token = map.get("access_token").toString();
return access_token;
}catch (Exception e){
//If the returned result has errcode和errmsg,Indicates that the interface call failed
Integer errCode = (Integer) map.get("errcode");
String errMsg = map.get("errmsg").toString();
throw new HospitalException(errCode,"Obtained from WeChat public platformaccess_token失败,"+errMsg);
}
}
}
HttpClientUtils:
package com.guigusuqi.commonutils.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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 java.io.IOException;
public class HttpClientUtils
{
//发起一个get请求,The return data is yesjson格式返回
public static JSONObject doGet(String url) throws IOException
{
JSONObject jsonObject = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null)
{
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.parseObject(result);
}
httpGet.releaseConnection();;
return jsonObject;
}
//发起一个post请求,The return data is yesjson格式返回
public static String doPost(String url,String jsonParam) throws IOException
{
System.out.println(jsonParam);
// 获取连接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
try {
// 创建POST请求对象s
HttpPost httpPost = new HttpPost(url);
if (!"".equals(jsonParam)){
// 创建请求参数
StringEntity s = new StringEntity(jsonParam, "utf-8");
//设置参数到请求对象中
httpPost.setEntity(s);
}
//添加请求头信息
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
httpPost.addHeader("Content-Type", "application/json");
// 执行请求
response = httpClient.execute(httpPost);
// 获得响应
HttpEntity entity = response.getEntity();
// Convert the response result to a string
entityStr = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放连接
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
System.out.println("释放连接出错");
e.printStackTrace();
}
}
}
// 打印响应内容
System.out.println("打印响应内容:"+entityStr);
return entityStr;
}
}
5.2 获得access_token之后,请求消息推送接口,Get the sent result
@Override
public Result sendTemplateInfo(JSONObject jsonData) throws Exception
{
//获取小程序accessToken
String accessToken = obtainAccessTokenUtils.obtainAccessToken();
//消息推送接口
String path = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
String result = HttpClientUtils.doPost(path, jsonData.toJSONString());
//Parse the WeChat return result into json对象
//Determine the result of sending the template message
JSONObject obj = JSONObject.parseObject(result);
//将json对象赋值给map
Map<String, Object> map = obj;
//获取错误码 如果code为0,errmsg为ok 代表成功
Integer code = (Integer)map.get("errcode");
String msg = map.get("errmsg").toString();
if (0 != code || !"ok".equals(msg))
{
return Result.fail().code(code).message("消息推送失败,"+msg);
}
return Result.success().message("消息推送成功!");
}
5.3 得到access_token了,url也有了,The next step is to see what parameters are required to send template messages
{
"touser":"oLiuN6Z8zlX-ONrjPFsW8FoKKtdI",
"template_id":"lcNTMFxkf0TlhOVryVHSadjgBG9G5nXaVefkyZ8O9es",
"data":{
"first": {
"value":"恭喜你购买成功!",
"color":"#173177"
},
"keyword1":{
"value":"巧克力",
"color":"#173177"
},
"keyword2": {
"value":"39.8元",
"color":"#173177"
},
"remark":{
"value":"欢迎再次购买!",
"color":"#173177"
}
}
}
touserThis parameter must be concerned with this public account:
模板id就是yaml文件指定的templateID
边栏推荐
- 【多任务学习】Modeling Task Relationships in Multi-task Learning with Multi-gate Mixture-of-Experts KDD18
- MySQL你到底都加了什么锁?
- SIPp 安装及使用
- 多线程之生产者与消费者
- Pytorch模型训练实用教程学习笔记:一、数据加载和transforms方法总结
- XSS靶场中级绕过
- "Torch" tensor multiplication: matmul, einsum
- AcWing 797. 差分
- Software you should know as a programmer
- 不恰当Equatable协议==方法的实现对SwiftUI中@State修饰属性的影响
猜你喜欢
[Multi-task model] Progressive Layered Extraction: A Novel Multi-Task Learning Model for Personalized (RecSys'20)
【Untitled】
Greenplum Database Source Code Analysis - Analysis of Standby Master Operation Tools
KDD2022 | 自监督超图Transformer推荐系统
Pytorch模型训练实用教程学习笔记:一、数据加载和transforms方法总结
网络不通?服务丢包?这篇 TCP 连接状态详解及故障排查,收好了~
启明云端分享|盘点ESP8684开发板有哪些功能
专利检索常用的网站有哪些?
XSS range intermediate bypass
第60章 ApplicationPart自动集成整体性和独立性插件项
随机推荐
17. Load balancing
【无标题】
内网穿透 lanproxy部署
LTE time domain and frequency domain resources
C语言实现-直接插入排序(带图详解)
不同的操作加不同的锁详解
【kali-信息收集】(1.5)系统指纹识别:Nmap、p0f
【kali-信息收集】(1.2)SNMP枚举:Snmpwalk、Snmpcheck;SMTP枚举:smtp-user-enum
30天刷题计划(五)
【nn.Parameter()】生成和为什么要初始化
【kali-信息收集】(1.4)识别活跃的主机/查看打开的端口:Nmap(网络映射器工具)
环境变量,进程地址空间
用户体验好的Button,在手机上不应该有Hover态
漏刻有时文档系统之XE培训系统二次开发配置手册
我的驾照考试笔记(3)
Pytorch模型训练实用教程学习笔记:一、数据加载和transforms方法总结
智能硬件开发怎么做?机智云全套自助式开发工具助力高效开发
Compose实战-实现一个带下拉加载更多功能的LazyColumn
面试突击70:什么是粘包和半包?怎么解决?
我的驾照考试笔记(4)