微信开发之获取openid及推送模板消息
有很多的朋友再问我怎么获取code,openid之类的问题,在这里我就给大家分享一下。
在做微信支付是需要获取openid的,推送模板消息也是需要openid包括其他一些功能分享等也都是需要的,openid是什么呢,这里给大家解释一下,是用户在公众号中的一个标识,就相当于你数据表中的ID一样,一个身份标识。
不多说废话了这里直接上代码了:
这里写一个了a标签来获取code,需要注意的是redirect_uri=接收code的回调地址(是带http://格式)可以指向下面的register
<a style="color: #fff" href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=你公众号的appid&redirect_uri=接收code的回调地址(是带http://格式)&response_type=code&scope=snsapi_base&state=wxsq123#wechat_redirect">获取openid</a>
appid:是公众号的ID,appsecrect:是公众号的密钥,code:就是上面a标签重定向的获取到的
@RequestMapping(params = "method=register", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> register(HttpServletRequest request) throws Exception { //接收来之页面a标签重定向的参数
String code = request.getParameter("code"); //返回openid
String openid = WeiXinUtils.getOpenid(appid, appsecrt, code); //推送模板消息给用户
WeiXinUtils.sendMsg(openid, "标题", "内容"); }
给一个封装的WeiXinUtils类:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse; import org.joda.time.DateTime; import com.alibaba.fastjson.JSONObject; public class WeiXinUtils { /**
* Description: 获取微信公众号token<BR>
*
* @author dsn
* @date 2018年9月21日 上午9:53:26
* @param appid
* @param secret
* @return
* @version 1.0
*/
public static String getAccessToken(String appid, String secret) {
String token = "";
String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
+ "&secret=" + secret;
JSONObject result = PayCommonUtil.httpsRequest(token_url, "POST");
if (result.get("access_token") != null) {
token = result.get("access_token").toString();
}
return token;
} /**
* Description: 获取微信ticket<BR>
*
* @author dsn
* @date 2018年9月21日 上午9:54:03
* @param token
* @return
* @version 1.0
*/
public static String getTicket(String token) {
if ("".equalsIgnoreCase(token) || null == token) {
return "";
}
String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
JSONObject result = PayCommonUtil.httpsRequest(ticket_url, "POST");
return result.get("ticket").toString(); } /**
* Description: 获取code <BR>
*
* @author dsn
* @date 2018年9月21日 下午12:02:43
* @param redirect_uri
* @param appid
* @return
* @version 1.0
*/
public static void getCode(String redirect_uri, String appid, HttpServletResponse response) {
String code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=" + redirect_uri + "&appid="
+ appid + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
try {
response.sendRedirect(code_url);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* Description: 通过code获取用户openid<BR>
*
* @author dsn
* @date 2018年9月21日 下午12:02:18
* @param appid
* @param appsecret
* @param code
* @return
* @version 1.0
*/
public static String getOpenid(String appid, String appsecret, String code) {
String openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
+ "&code=" + code + "&grant_type=authorization_code";
JSONObject result = PayCommonUtil.httpsRequest(openid_url, "POST");
if (result.containsKey("errcode")) {
return "";
} else {
return result.getString("openid");
}
} /**
* Description: 根据微信openid 获取用户是否关注公众号<BR>
*
* @author dsn
* @date 2018年9月21日 上午9:56:10
* @param openId
* @return
* @version 1.0
*/
public static Integer subscribeState(String openId) {
String tmpurl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
+ getAccessToken("wxcd1feb93b3454edc", "0a05181ac3bc53c44206a58e97d99b26") + "&openid=" + openId;
JSONObject result = PayCommonUtil.httpsRequest(tmpurl, "GET");
JSONObject resultJson = new JSONObject(result);
String errmsg = (String) resultJson.get("errmsg");
if (errmsg == null) {
//用户是否订阅该公众号标识(0代表此用户没有关注该公众号 1表示关注了该公众号)。
Integer subscribe = (Integer) resultJson.get("subscribe");
return subscribe;
}
return -1;
} /**
* Description: 推送消息给用户<BR>
*
* @author dsn
* @date 2018年9月21日 上午11:44:09
* @param openId
* @param title
* @param carname
* @version 1.0
*/
public static void sendMsg(String openId, String title, String carname) {
final String appid = "";
final String sercet = "";
//用户是否订阅该公众号标识 (0代表此用户没有关注该公众号 1表示关注了该公众号)
Integer state = WeiXinUtils.subscribeState(openId);
// 绑定了微信并且关注了服务号的用户 , 注册成功-推送注册短信
if (state == 1) {
String date = DateTime.now().toString("yyyy-MM-dd HH:mm:ss");
Map<String, TemplateData> param = new HashMap<>();
param.put("first", new TemplateData(title, "#FF0000"));
param.put("keyword1", new TemplateData(carname, "#696969"));
param.put("keyword2", new TemplateData(date, "#696969"));
param.put("remark", new TemplateData("", "#696969"));
//注册的微信-模板Id
// String regTempId = WX_TemplateMsgUtil
// .getWXTemplateMsgId(WeiXinEnum.WX_TEMPLATE_MSG_NUMBER.CAR_REMIND.getMsgNumber(), appid, sercet);
//调用发送微信消息给用户的接口
WX_TemplateMsgUtil.sendWechatMsgToUser(openId, "模板ID", "", "#000000",
WX_TemplateMsgUtil.packJsonmsg(param), appid, sercet);
}
} }
发送post请求封装的httpsRqquest方法也贴出来了:
/**
* 发送https请求
*
* @param requestUrl
* 请求地址
* @param requestMethod
* 请求方式(GET、POST)
* @param outputStr
* 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
// SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(3000);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// conn.setRequestProperty("content-type",
// "application/x-www-form-urlencoded");
// 当outputStr不为null时向输出流写数据
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
logger.error("", ce);
} catch (Exception e) {
logger.error("", e);
}
return jsonObject;
}
还需要一个模板消息封装类WX_TemplateMsgUtil:
import java.util.Map; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject; public class WX_TemplateMsgUtil {
private static Logger log = LoggerFactory.getLogger(WX_TemplateMsgUtil.class); /**
* 封装模板详细信息
*
* @return
*/
public static JSONObject packJsonmsg(Map<String, TemplateData> param) {
JSONObject json = new JSONObject();
for (Map.Entry<String, TemplateData> entry : param.entrySet()) {
JSONObject keyJson = new JSONObject();
TemplateData dta = entry.getValue();
keyJson.put("value", dta.getValue());
keyJson.put("color", dta.getColor());
json.put(entry.getKey(), keyJson);
}
return json;
} /**
* 根据模板的编号 新增并获取模板ID
*
* @param templateSerialNumber
* 模板库中模板的 "编号"
* @return 模板ID
*/
public static String getWXTemplateMsgId(String templateSerialNumber, String appid, String secret) {
String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="
+ WeiXinUtils.getAccessToken(appid, secret);
JSONObject json = new JSONObject();
json.put("template_id_short", templateSerialNumber);
JSONObject result = PayCommonUtil.HttpsRequest(tmpurl, "POST", json.toString());
JSONObject resultJson = new JSONObject(result);
String errmsg = (String) resultJson.get("errmsg");
// log.info("获取模板编号返回信息:" + errmsg);
if (!"ok".equals(errmsg)) {
return "error";
}
String templateId = (String) resultJson.get("template_id");
return templateId;
} /**
* 根据模板ID 删除模板消息
*
* @param templateId
* 模板ID
* @return
*/
public static String deleteWXTemplateMsgById(String templateId, String appid, String secret) {
String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token="
+ WeiXinUtils.getAccessToken(appid, secret);
JSONObject json = new JSONObject();
json.put("template_id", templateId);
try {
JSONObject result = PayCommonUtil.HttpsRequest(tmpurl, "POST", json.toString());
JSONObject resultJson = new JSONObject(result);
// log.info("删除" + templateId + "模板消息,返回CODE:" + resultJson.get("errcode"));
String errmsg = (String) resultJson.get("errmsg");
if (!"ok".equals(errmsg)) {
return "error";
}
} catch (Exception e) {
e.printStackTrace();
}
return "success";
} /**
* 发送微信消息(模板消息)
*
* @param touser
* 用户 OpenID
* @param templatId
* 模板消息ID
* @param clickurl
* URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)。
* @param topcolor
* 标题颜色
* @param data
* 详细内容
* @return
*/
public static String sendWechatMsgToUser(String touser, String templatId, String clickurl, String topcolor,
JSONObject data, String appid, String secret) {
String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
+ WeiXinUtils.getAccessToken(appid, secret);
JSONObject json = new JSONObject();
json.put("touser", touser);
json.put("template_id", templatId);
json.put("url", clickurl);
json.put("topcolor", topcolor);
json.put("data", data);
try {
JSONObject result = PayCommonUtil.HttpsRequest(tmpurl, "POST", json.toString());
JSONObject resultJson = new JSONObject(result);
// log.info("发送微信消息返回信息:" + resultJson.get("errcode"));
String errmsg = (String) resultJson.get("errmsg");
if (!"ok".equals(errmsg)) { //如果为errmsg为ok,则代表发送成功,公众号推送信息给用户了。
return "error";
}
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
if (templatId != null) {
//删除新增的 微信模板
// deleteWXTemplateMsgById(templatId, appid, secret);
}
}
return "success";
}
}
TemplateData类:
public class TemplateData {
public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public String getColor() {
return color;
} public void setColor(String color) {
this.color = color;
} private String value;
private String color; public TemplateData(String value, String color) {
this.value = value;
this.color = color;
} }
到这里就是一个完整的流程了,其实是很简单的,只要理解了流程。
当然还有一种用户授权登录,会弹出一个需要用户点击的确定,就可以获取用户的昵称,性别之类的信息。
https://blog.csdn.net/dsn727455218/article/details/65630151 找个地址就是授权登录的
需要注意的是a标签里面的scope为snsapi_userinfo 才能调起授权页面。
如有需要可以加我Q群【308742428】大家一起讨论技术。
后面会不定时为大家更新文章,敬请期待。
喜欢的朋友可以关注下。
微信开发之获取openid及推送模板消息的更多相关文章
- 微信公众号实现无限制推送模板消息!可向指定openID群发
微信认证的服务号才有推送模板消息接口所以本文需要在认证服务号的情况下学习 以上就是模板消息,只有文字和跳转链接,没有封面图.在服务号的后台添加功能插件-模板消息即可. 模板消息,都是在后台选择一个群发 ...
- C#微信接口之推送模板消息功能示例
本文实例讲述了C#微信接口之推送模板消息功能.分享给大家供大家参考,具体如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...
- python 微信推送模板消息
#!/usr/bin/env python #-*- coding: utf-8 -*- import httplib import json import MySQLdb #从数据库中获取acces ...
- 使用ESP8266nodeMCU 向微信推送模板数据
使用HTTPS协议向微信公众号推送消息,(使用ESP8266的低成本实现) 前几天被朋友问到这个东西的实现方式,花了一下午时间研究一下,特此记录.没有排版比较乱. 一丶前往微信公众平台注册微信微信公众 ...
- C#微信公众号开发系列教程五(接收事件推送与消息排重)
微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C ...
- 转:C#微信公众号开发之接收事件推送与消息排重的方法
本文实例讲述了C#微信公众号开发之接收事件推送与消息排重的方法.分享给大家供大家参考.具体分析如下: 微信服务器在5秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次.这样的话,问题就来了.有这 ...
- C#微信公众号开发系列教程(接收事件推送与消息排重)
微信服务器在5秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次.这样的话,问题就来了.有这样一个场景:当用户关注微信账号时,获取当前用户信息,然后将信息写到数据库中.类似于pc端网站的注册.可 ...
- iOS开发之功能模块--Apns推送中的的json格式介绍
在开发向苹果Apns推送消息服务功能,我们需要根据Apns接受的数据格式进行推送.下面接受我在进行apns推送时候总结的一点apns服务接受的Json数据格式 示例 1: 以下负载包含哦一个简单的 a ...
- Windows Phone开发(44):推送通知第二集——磁贴通知
原文:Windows Phone开发(44):推送通知第二集--磁贴通知 前面我们说了第一个类型--Toast通知,这玩意儿不知大家是不是觉得很新鲜,以前玩.NET编程应该没接触过吧? 其实这东西绝对 ...
随机推荐
- Python中使用%还是format来格式化字符串?
Python中应该使用%还是format来格式化字符串? %还是format Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了form ...
- Python+Selenium学习--案例介绍
1. 前言 前面讲解了那么多selenium的基础知识,下面用一个简单案例来介绍,此案例主要实现,运行测试,自动生成html报告,并发生邮件. 2. 测试案例 2.1 目录结构介绍 conf:配置信息 ...
- Python+Selenium学习--cookie处理
场景 有时候我们需要验证浏览器中是否存在某个cookie,因为基于真实的cookie 的测试是无法通过白盒和集成测试完成的.webdriver 可以读取.添加和删除cookie 信息.webdrive ...
- JSP中JavaScript校验用户名等重复
$(function () { $("#unitFrom").validate({ errorClass:"errorInfo", //默认为错误的样式类为:e ...
- Java线程池的构造以及使用
有时候,系统需要处理非常多的执行时间很短的请求,如果每一个请求都开启一个新线程的话,系统就要不断的进行线程的创建和销毁,有时花在创建和销毁线程上的时间会比线程真正执行的时间还长.而且当线程数量太多时, ...
- 【转】Cron表达式详解
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式: (1) Seconds Minutes Hours DayofMonth Mo ...
- surf the internet scientifically
You can get some useful information from the link below: 1. http://blog.sina.com.cn/s/blog_4891cbc50 ...
- Maven学习 一 概念介绍
一 Maven是什么 Maven是一个Apache公司的开源项目,主要有两个作用:(1)是项目构建工具.(2)是用来管理java程序中jar包的依赖. 它包含了一个项目对象模型(Project Obj ...
- python模块:random
"""Random variable generators. integers -------- uniform within range sequences ----- ...
- orabbix监控oracle
Orabbix 是一个用来监控 Oracle 数据库实例的 Zabbix 插件.下载地址: http://www.smartmarmot.com/product/orabbix/download/ O ...