换取微信公众号二维码第一步需要去设置ip白名单 本机电脑的ip地址(既百度输入ip所得到的地址)
不多说直接上代码
package com.kosn.base.controller;
import com.alibaba.fastjson.JSON;
import com.kosn.base.kit.PropKit;
import com.kosn.base.model.WechatQRCode;
import com.kosn.base.utils.HttpClientUtil;
import com.kosn.base.utils.WeixinUtill;
import com.wxpay.config.WXPayConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;
import java.net.URLEncoder;
import java.util.Map;
@Controller
public class QrCodeController {
private static final String APPID = "自己的APPID";
private static final String SECRET = "自己的SECRET";
@RequestMapping("/token")
@ResponseBody
public static String getQR() {
String getTokenUrl1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+SECRET; // 微信公众号token
String tokenResult = HttpClientUtil.doGet(getTokenUrl1);
Map<String, String> tokenResultMap = JSON.parseObject(tokenResult, Map.class);
String access_token = tokenResultMap.get("access_token");
return access_token;
}
// 临时二维码
// sceneid 自定义参数
@RequestMapping("/qrcode")
@ResponseBody
public static String qr(int sceneid) { //获得token不再说明
String assesstoken = getQR();
WechatQRCode wechatQRCode = createTemporaryTicket(assesstoken, 900, sceneid);
return getRQcode(wechatQRCode.getTicket());
}
// 永久二维码
// sceneid 自定义参数
@RequestMapping("/foreverqrcode")
@ResponseBody
public static String getForeverQrCode(int sceneid) {
String assesstoken = getQR();
String ticket = createForeverTicket(assesstoken, sceneid);
return getRQcode(ticket);
}
/**
* @param accessToken 接口访问凭证
* @param expireSeconds 二维码有效时间 单位为秒 最长 1800秒 (30天)
* @param sceneId 场景id 临时二维码场景值Id为32位非0整数 永久二维码的场景值ID取1~10000
* 也就是说永久二维码一共可以创建10000个 临时的多
* @return
*/
public static WechatQRCode createTemporaryTicket(String accessToken, int expireSeconds, int sceneId) {
WechatQRCode wechatQRCode = null;
// 拼接请求地址
String requestUrl = " https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
requestUrl = requestUrl.replace("TOKEN", accessToken);
// 需要提交json数据
String jsonmsg = "{\"expire_seconds\":%d,\"action_name\": \"QR_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":%d}}}";
// 创建永久带参二维码
JSONObject jsonObject = WeixinUtill.httpRequest(requestUrl, "POST", String.format(jsonmsg, expireSeconds, sceneId));
if (null != jsonObject) {
System.out.println(jsonObject);
try {
wechatQRCode = new WechatQRCode();
wechatQRCode.setTicket(jsonObject.getString("ticket"));
wechatQRCode.setExpire_seconds(jsonObject.getInt("expire_seconds"));
System.out.println("零时带参二维码ticket成功=" + wechatQRCode.getTicket() + "Expire_seconds=" + wechatQRCode.getExpire_seconds());
} catch (Exception e) {
wechatQRCode = null;
int err = jsonObject.getInt("errcode");
String errormsg = jsonObject.getString("errmsg");
}
}
return wechatQRCode;
}
/**
* 永久二维码
*
* @param accessToken
* @param sceneId 场景iD 1~10000
* @return
*/
public static String createForeverTicket(String accessToken, int sceneId) {
String url = null;
// 拼接请求地址
String requestUrl = " https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
requestUrl = requestUrl.replace("TOKEN", accessToken);
// 需要提交json数据
String jsonmsg = "{\"action_name\": \"QR_LIMIT_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":%d}}}";
// 创建永久带参二维码
JSONObject jsonObject = WeixinUtill.httpRequest(requestUrl, "POST", String.format(jsonmsg, sceneId));
if (null != jsonObject) {
try {
url = jsonObject.getString("ticket");
} catch (Exception e) {
int err = jsonObject.getInt("errcode");
String errormsg = jsonObject.getString("errmsg");
}
}
String ticke = null;
try {
ticke = String.format(URLEncoder.encode(url, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ticke;
}
public static String getRQcode(String ticket) {
String filepath = null;
String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
requestUrl = requestUrl.replace("TICKET", ticket);
// try {
// URL url = new URL(requestUrl);
// HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// conn.setDoInput(true);
// conn.setRequestMethod("GET");
//
// if (!savepath.endsWith("/")) {
// savepath += "/";
// }
// // 将ticket 作为文件名
// filepath = savepath + ticket + ".jpg";
//
// // 将微信服务器返回的输入流写入文件
//
// BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
// FileOutputStream fos = new FileOutputStream(new File(filepath));
//
// byte[] buf = new byte[8096];
// int size = 0;
// while ((size = bis.read(buf)) != -1)
// fos.write(buf, 0, size);
// fos.close();
// bis.close();
//
// conn.disconnect();
// } catch (Exception e) {
// filepath = null;
// }
// return filepath;
return requestUrl;
}
}
## 所用到的工具类
```java
package com.kosn.base.utils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
/**
* @author zhangbo
* 2019/11
*/
public class HttpClientUtil {
public static String doGet(String uri) {
//1:创建一个HttpClient的实例
CloseableHttpClient httpclient = HttpClients.createDefault();
//2:创建一个get请求实例
HttpGet httpGet = new HttpGet(uri);
//请求的响应:
CloseableHttpResponse response1 = null;
try {
//3:使用HttpClient的实例执行get请求
response1 = httpclient.execute(httpGet);
//http请求的状态:404 500 200
// System.out.println(response1.getStatusLine());
int statusCode = response1.getStatusLine().getStatusCode();
if (statusCode == 200) {
//请求成功:
HttpEntity entity1 = response1.getEntity();
String result = EntityUtils.toString(entity1, "utf-8");
return result;
} else {
//请求失败:自己做自己的业务逻辑
System.out.println("请求失败......:"+statusCode);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
## 要实现的类
```java
package com.kosn.base.utils;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
微信公众平台接口类
package com.kosn.base.utils;
import java.awt.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.b505.pojo.*;
//
/**
* *
* * 公众平台通用接口工具类
* * @author
* *
*
*/
public class WeixinUtill {
private static Logger log = LoggerFactory.getLogger(WeixinUtill.class);
/**
*
* * 发起https请求并获取结果
* *
* * @param requestUrl 请求地址
* * @param requestMethod 请求方式(GET、POST)
* * @param outputStr 提交的数据
* * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
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 httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
}
}
package com.kosn.base.model;
import java.util.Objects;
public class WechatQRCode {
// 获取的二维码
private String ticket;
// 二维码的有效时间,单位为秒,最大不超过2592000(即30天)
private int expire_seconds;
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public int getExpire_seconds() {
return expire_seconds;
}
public void setExpire_seconds(int expire_seconds) {
this.expire_seconds = expire_seconds;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WechatQRCode that = (WechatQRCode) o;
return expire_seconds == that.expire_seconds &&
Objects.equals(ticket, that.ticket);
}
@Override
public int hashCode() {
return Objects.hash(ticket, expire_seconds);
}
@Override
public String toString() {
return "WechatQRCode{" +
"ticket='" + ticket + '\'' +
", expire_seconds=" + expire_seconds +
'}';
}
}