当前位置:网站首页>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 # 用户点击信息 跳转的url5.编写接口,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
边栏推荐
- 第58章 结构、纪录与类
- 【节能学院】智能操控装置在高压开关柜的应用
- LTE time domain and frequency domain resources
- Creo5.0 rough hexagon is how to draw
- 我的驾照考试笔记(4)
- [Multi-task model] Progressive Layered Extraction: A Novel Multi-Task Learning Model for Personalized (RecSys'20)
- 根据Uniprot ID/PDB ID批处理获取蛋白质.pdb文件
- Does LabVIEW really close the COM port using VISA Close?
- 自定义指令,获取焦点
- ARTS_202207W2
猜你喜欢

nacos installation and configuration

用户体验好的Button,在手机上不应该有Hover态

如何记录分析你的炼丹流程—可视化神器Wandb使用笔记【1】

58:第五章:开发admin管理服务:11:开发【管理员人脸登录,接口】;(未实测)(使用了阿里AI人脸识别)(演示了,使用RestTemplate实现接口调用接口;)

我的驾照考试笔记(3)

【多任务模型】Progressive Layered Extraction: A Novel Multi-Task Learning Model for Personalized(RecSys‘20)

智能硬件开发怎么做?机智云全套自助式开发工具助力高效开发

我的驾照考试笔记(1)

【kali-信息收集】(1.4)识别活跃的主机/查看打开的端口:Nmap(网络映射器工具)

因斯布鲁克大学团队量子计算硬件突破了二进制
随机推荐
瀚高数据导入
研究生新同学,牛人看英文文献的经验,值得你收藏
Pytorch模型训练实用教程学习笔记:二、模型的构建
nacos installation and configuration
环境变量,进程地址空间
数字孪生北京故宫,元宇宙推进旅游业进程
【kali-信息收集】(1.3)探测网络范围:DMitry(域名查询工具)、Scapy(跟踪路由工具)
小数据如何学习?吉大最新《小数据学习》综述,26页pdf涵盖269页文献阐述小数据学习理论、方法与应用
Acrel-5010重点用能单位能耗在线监测系统在湖南三立集团的应用
安全作业7.25
Greenplum数据库源码分析——Standby Master操作工具分析
KDD2022 | 自监督超图Transformer推荐系统
作为程序员你应该会的软件
easyUI中datagrid中的formatter里面向后台发送请求获取数据
58: Chapter 5: Develop admin management services: 11: Develop [admin face login, interface]; (not measured) (using Ali AI face recognition) (demonstrated, using RestTemplate to implement interface cal
[Multi-task learning] Modeling Task Relationships in Multi-task Learning with Multi-gate Mixture-of-Experts KDD18
锐捷交换机基础配置
AcWing 797. 差分
【kali-信息收集】(1.6)服务的指纹识别:Nmap、Amap
Pytorch模型训练实用教程学习笔记:四、优化器与学习率调整