最近做微信项目,这里写了几个关于微信开发的基础功能,首先微信开发要在要在公众平台帐号上的基本配置中设置服务器连接,这里设置的url是当有消息发送的时候会直接发送到对应url地址中,token就是一个校验,每次发送的时候会对其进行校验,只有校验成功才能继续进行操作。
checkSignature 是用来校验token 的方法,校验成功返回true
getAccesstoken 是获取accessToken 的方法,基本上所有的微信接口都需要传accessToken值
getUnionID 是通过openid 获取对应的unionid方法(在这里还能获取用户的其他信息)
setIndustry 可以设置公众号的行业信息,用于模版发送
setSendTemplate 是模版发送功能,不过里面的参数我是写死的,这里其实可以根据不同情况发送对应模版
package com.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class WeChatUtil {
private static final String token = "设置的token";
public static final String WXAPPID = "微信帐号"; //公众账号appid
public static final String KEY = "微信密钥"; //秘钥
public static String industry_id1="1"; //行业id
public static String industry_id2="2";//行业id
public static final String GETURL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WXAPPID+"&secret="+KEY; //获取access_token的
public static final String setURL="https://api.weixin.qq.com/cgi-bin/template/api_set_industry";//设置所属行业
public static final String sendUrl="https://api.weixin.qq.com/cgi-bin/message/template/send"; //发送模版信息
public static final String gettemplateIdShort="https://api.weixin.qq.com/cgi-bin/template/api_add_template"; //获取template_id_short 获取模版id
public static final String getUnionID="https://api.weixin.qq.com/cgi-bin/user/info/batchget";
public static final String getSingleUnionID="https://api.weixin.qq.com/cgi-bin/user/info";
public static final String GETTOCKEN="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"; //开放平台获取openid和access_tocken
private static String ACCESS_TOKEN;
// public static long ACCESS_TOKEN_TIME=new Date().getTime()-1000;
private static long ACCESS_TOKEN_TIME=0;
/**
*
* @Description: token校验
* @param @param signature
* @param @param timestamp
* @param @param nonce
* @param @return
* @throws
* @author lvguangming
* @date 2017-4-12
*/
public static boolean checkSignature(String signature,String timestamp,String nonce){
String[] arr = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(arr);
//生成字符串
StringBuffer content = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
//sha1加密
String temp = getSha1(content.toString());
return temp.equals(signature);
}
public static String getSha1(String str){
if (null == str || 0 == str.length()){
return null;
}
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char[] buf = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
*
* @Description: 获取access_token
* @param @param args
* @throws
* @author lvguangming
* @date 2017-3-29
*/
private static String getOpenJosn(){
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL realUrl = new URL(GETURL);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
* @Description: 获取access_token并解析
* @param return 返回access_token值
* @throws
* @author lvguangming
* @date 2017-3-29
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String getAccesstoken(){
if(ACCESS_TOKEN_TIME!=0){ //判断上次获取的ACCESS_TOKEN时间是否超过6000秒,若未超过直接使用上次获取的参数
long time=(long)(new Date().getTime()-ACCESS_TOKEN_TIME)/1000;
if(time<6000L){
return ACCESS_TOKEN;
}
}
String openjosn = getOpenJosn();
// System.out.println("getaccess_token:"+openjosn);
JSONObject jsonObject;
String accessToken = "";
try {
jsonObject = JSONObject.parseObject(openjosn);
Map result = new HashMap();
Iterator iterator = jsonObject.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
value = jsonObject.getString(key);
result.put(key, value);
}
if(null!=result.get("access_token")){
accessToken = result.get("access_token").toString();
ACCESS_TOKEN_TIME=new Date().getTime();
ACCESS_TOKEN=accessToken;
}
}
catch (Exception e) {
e.printStackTrace();
}
return accessToken;
}
/**
*
* @Description: 发送信息
* @param @param args
* @throws
* @author lvguangming
* @date 2017-3-29
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
*
* @Description: 获取一个集合的openid的unionid
* @param @param openids
* @param @return
* @throws
* @author lvguangming
* @date 2017-4-1
*/
public static String getUnionIDs(List openids){
String accessToken=getAccesstoken();
String postURL=getUnionID+"?access_token="+accessToken;
Map sendMap=new HashMap();
List