一、获取access_token
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
可使用微信公众平台接口调试工具进行调试(登录公众号后,在左侧导航栏可找到“开发者工具”,选择第二项“在线接口调试工具”即可进行接口调试。):https://mp.weixin.qq.com/debug?token=1803714957&lang=zh_CN
首先我们需要获取access_token,有效期7200s,一天获取上限为2000次
代码实例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
public class xiaoqiang {
public static final String appid = "xxxxxxxxxxxxxxxxxx";
public static final String appsecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static Logger loger = LoggerFactory.getLogger(xiaoqiang.class);
public static void main(String args[]) {
System.out.println(getWXAccessToken());
}
public static String getWXAccessToken() {
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?" +
"grant_type=client_credential" +
// 此处填写你自己的appid
"&appid=" + appid +
// 此处填写你自己的appsecret
"&secret=" + appsecret;
JSONObject jsonObject = httpsRequest(accessTokenUrl, "GET", null);
return (String) jsonObject.get("access_token");
}
/**
* 发送https请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param data 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String data) {
JSONObject jsonObject = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.connect();
// 当data不为null时向输出流写数据
if (null != data) {
// getOutputStream方法隐藏了connect()方法
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(data.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
return jsonObject;
} catch (Exception e) {
loger.error("发送https请求失败,失败", e);
return null;
} finally {
// 释放资源
try {
if(null != inputStream) {
inputStream.close();
}
if(null != inputStreamReader) {
inputStreamReader.close();
}
if(null != bufferedReader) {
bufferedReader.close();
}
} catch (IOException e) {
loger.error("释放资源失败,失败", e);
}
}
}
}
注意:你可能会出现如下图所示“org.apache.commons.lang.exception.NestableRuntimeException”的报错
参考:https://blog.csdn.net/gu_gu_/article/details/50551775
解决:在pom.xml文件中加入下面的配置
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1</version>
</dependency>
注意:我们需要现在微信公众平台设置 IP白名单,也就是本机的外网IP地址,否则无法获取access_token
二、获取微信公众号二维码
说明:可以和上一篇文章“事件推送”配合使用。为了满足用户渠道推广分析的需要,公众平台提供了生成带参数二维码的接口。使用该接口可以获得多个带不同场景值的二维码,用户扫描后,公众号可以接收到事件推送。
目前有2种类型的二维码,分别是临时二维码和永久二维码,前者有过期时间,最大为1800秒,但能够生成较多数量,后者无过期时间,数量较少(目前参数只支持1–100000)。两种二维码分别适用于帐号绑定、用户来源统计等场景。
用户扫描带场景值二维码时,可能推送以下两种事件:
如果用户还未关注公众号,则用户可以关注公众号,关注后微信会将带场景值关注事件推送给开发者。
如果用户已经关注公众号,在用户扫描后会自动进入会话,微信也会将带场景值扫描事件推送给开发者。
获取带参数的二维码的过程包括两步,首先创建二维码ticket,然后凭借ticket到指定URL换取二维码。
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
代码实例:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
public class xiaoqiang {
public static final String appid = "xxxxxxxxxxxxxxxxxx";
public static final String appsecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static Logger loger = LoggerFactory.getLogger(xiaoqiang.class);
public static void main(String args[]) throws UnsupportedEncodingException {
// System.out.println(getWXAccessToken());
getWXPublicQRCode("1",123,"hehe");
}
/**
* 获取微信公众号二维码
* @param codeType 二维码类型 "1": 临时二维码 "2": 永久二维码
* @param sceneId 场景值ID
* scene_id 场景值ID,临时二维码时为32位非0整型,永久二维码时最大值为100000(目前参数只支持1--100000)
* scene_str 场景值ID(字符串形式的ID),字符串类型,长度限制为1到64
* @param fileName 图片名称
* @throws UnsupportedEncodingException
*/
public static void getWXPublicQRCode(String codeType, Integer sceneId, String fileName) throws UnsupportedEncodingException {
// String wxAccessToken = getWXAccessToken(); // 这里为了省略代码,可参考第一步获取access_token
Map<String, Object> map = new HashMap<>();
if ("1".equals(codeType)) { // 临时二维码
map.put("expire_seconds", 604800);
map.put("action_name", "QR_SCENE");
Map<String, Object> sceneMap = new HashMap<>();
Map<String, Object> sceneIdMap = new HashMap<>();
sceneIdMap.put("scene_id", sceneId);
sceneMap.put("scene", sceneIdMap);
map.put("action_info", sceneMap);
} else if ("2".equals(codeType)) { // 永久二维码
map.put("action_name", "QR_LIMIT_SCENE");
Map<String, Object> sceneMap = new HashMap<>();
Map<String, Object> sceneIdMap = new HashMap<>();
sceneIdMap.put("scene_id", sceneId);
sceneMap.put("scene", sceneIdMap);
map.put("action_info", sceneMap);
}
String data = JSON.toJSONString(map);
// 得到ticket票据,用于换取二维码图片
JSONObject jsonObject = httpsRequest("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + wxAccessToken, "POST", data);
String ticket = (String) jsonObject.get("ticket");
// WXConstants.QRCODE_SAVE_URL: 填写存放图片的路径
httpsRequestPicture("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" +
URLEncoder.encode(ticket, "UTF-8"), //URLEncoder.encode(ticket)已不建议使用
"GET", null, "C:\\Users\\Administrator\\Desktop", fileName, "png");
}
/**
* 发送https请求,返回二维码图片
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param data 提交的数据
* @param savePath 图片保存路径
* @param fileName 图片名称
* @param fileType 图片类型
*/
public static void httpsRequestPicture(String requestUrl, String requestMethod, String data, String savePath, String fileName, String fileType) {
InputStream inputStream = null;
try {
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.connect();
//当data不为null时向输出流写数据
if (null != data) {
//getOutputStream方法隐藏了connect()方法
OutputStream outputStream = conn.getOutputStream();
//注意编码格式
outputStream.write(data.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
inputStream = conn.getInputStream();
loger.info("开始生成微信二维码...");
inputStreamToMedia(inputStream, savePath, fileName, fileType);
loger.info("微信二维码生成成功!!!");
conn.disconnect();
} catch (Exception e) {
loger.error("发送https请求失败,失败", e);
}finally {
//释放资源
try {
if(null != inputStream) {
inputStream.close();
}
} catch (IOException e) {
loger.error("释放资源失败,失败", e);
}
}
}
/**
* 将输入流转换为图片
* @param input 输入流
* @param savePath 图片需要保存的路径
* @param fileType 图片类型
*/
public static void inputStreamToMedia(InputStream input, String savePath, String fileName, String fileType) throws Exception {
String filePath = savePath + "/" + fileName + "." + fileType;
File file = new File(filePath);
FileOutputStream outputStream = new FileOutputStream(file);
int length;
byte[] data = new byte[1024];
while ((length = input.read(data)) != -1) {
outputStream.write(data, 0, length);
}
outputStream.flush();
outputStream.close();
}
}
参考:
https://blog.csdn.net/goodbye_youth/article/details/80653132