大致思路是这样的,首先,根据微信官方文档(https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115),这里不予言表
第一步:配置微信config
1.先获取微信access_token,在拿到json对象里面的ticket,access_token和ticket都是获取之后2个小时后失效,并且微信每天获取的次数有限,所有必须要做缓存,本人采用的方法是通过单例模式
public class WeChatAccessTicket {
private String access_token;
private String ticket;
private int expires_in_access;
private int expires_in_ticket;
private Date time = new Date();
public boolean isExpiresAccess() {
long secends = System.currentTimeMillis() - this.time.getTime();
return secends > this.expires_in_access * 1000 ? true : false;
}
public boolean isExpiresTicket() {
long secends = System.currentTimeMillis() - this.time.getTime();
return secends > this.expires_in_ticket * 1000 ? true : false;
}
//类静态对象
private static WeChatAccessTicket weChatAccessTicket;
//单例模式实现
public static WeChatAccessTicket getAccessTicket() {
if (weChatAccessTicket == null) {
try {
weChatAccessTicket = new WeChatAccessTicket();
JSONObject jo = getWeChatAccessToken();
weChatAccessTicket.setAccess_token(jo.optString("access_token"));
weChatAccessTicket.setExpires_in_access(jo.optInt("expires_in"));
JSONObject jo1 = getWeChatTicket(jo.optString("access_token"));
weChatAccessTicket.setTicket(jo1.optString("ticket"));
weChatAccessTicket.setExpires_in_ticket(jo1.optInt("expires_in"));
} catch (Exception e) {
e.printStackTrace();
}
}
if (weChatAccessTicket.isExpiresAccess()){
try {
JSONObject jo = getWeChatAccessToken();
weChatAccessTicket.setAccess_token(jo.optString("access_token"));
weChatAccessTicket.setExpires_in_access(jo.optInt("expires_in"));
} catch (Exception e) {
e.printStackTrace();
}
}
if (weChatAccessTicket.isExpiresTicket()){
try {
JSONObject jo1 = getWeChatTicket(weChatAccessTicket.getAccess_token());
weChatAccessTicket.setTicket(jo1.optString("ticket"));
weChatAccessTicket.setExpires_in_ticket(jo1.optInt("expires_in"));
} catch (Exception e) {
e.printStackTrace();
}
}
return weChatAccessTicket;
}
/**
* 发起get请求,获取token
* @author tianyu
* 时间:2017-6-6 下午9:15:33
*/
public static JSONObject getWeChatAccessToken(){
JSONObject jo = null;
try {
String postData = HttpUtil.httpSendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4ff373785975e0a1&secret=d1a934bacca29df214aaa62e0d2b2ca7");
jo = JSONObject.fromObject(postData);
} catch (Exception e) {
e.printStackTrace();
}
return jo;
}
/**
* 发起get请求,获取ticket
* @author tianyu
* 时间:2017-6-7 下午3:02:36
*/
public static JSONObject getWeChatTicket(String token){
JSONObject jo = null;
try {
String str = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=&type=jsapi";
StringBuilder sb = new StringBuilder(str);
sb.insert(64, token);
String url = sb.toString();
String postData = HttpUtil.httpSendGet(url);
jo = JSONObject.fromObject(postData);
} catch (Exception e) {
e.printStackTrace();
}
return jo;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public int getExpires_in_access() {
return expires_in_access;
}
public void setExpires_in_access(int expires_in_access) {
this.expires_in_access = expires_in_access;
}
public int getExpires_in_ticket() {
return expires_in_ticket;
}
public void setExpires_in_ticket(int expires_in_ticket) {
this.expires_in_ticket = expires_in_ticket;
}
}
“`
2.将微信的参数进行sha1签名,参考微信官方文档提供的参数,这里不做详细说明(注:对所有签名的参数必要严格按照ASC||从小到大排序,必要全部是小写,参数之间用&连接)
签名sha1工具方法
public static String sha1Encrypt(String str){
StringBuffer sb = new StringBuffer();
StringBuilder buf = null;
try {
MessageDigest messageDigest = MessageDigest.getInstance(“sha1”);
messageDigest.update(str.getBytes());
char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
byte[] bytes= messageDigest.digest();
int len = bytes.length;
buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return buf.toString();
}`
public void wxConfig(){
logger.info("微信公众号基本配置");
PrintWriter out = WebUtil.JsonWriter();
try {
Map<String,String> map = new HashMap<String, String>();
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonceStr = OtherUtils.create_nonce_str();
//String url = request.getScheme()+"://"+request.getServerName()+request.getRequestURI();
WeChatAccessTicket accessTicket = WeChatAccessTicket.getAccessTicket();
String str = "jsapi_ticket="+accessTicket.getTicket()+"&noncestr="+nonceStr+"×tamp="+timestamp+"&url="+url;
String sign = OtherUtils.sha1Encrypt(str);
map.put("appid", "wx4ff373785975e0a1");
map.put("timestamp", timestamp);
map.put("noncestr", nonceStr);
map.put("sign", sign);
out.print(FastjsonUtil.toJson(map));
} catch (Exception e) {
logger.error("微信公众号基本配置错误", e);
}
}
js代码(注:需要引入微信线上的js http://res.wx.qq.com/open/js/jweixin-1.2.0.js)
var uri = window.location.href;
$.ajax({
url:’/before/user/user/wxConfig/’,
type:’POST’,
data:{url:uri},
dataType:’json’,
success:function(data){
if(data!=null){
var appid = data.appid;
var timestamp = data.timestamp;
var sign = data.sign;
var noncestr = data.noncestr;
//alert(appid+”—”+timestamp+”—”+sign+”—”+noncestr);
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: appid, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature: sign,// 必填,签名,见附录1
jsApiList: [‘chooseImage’,’uploadImage’] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}else{
alert(“数据为空”);
}
},
error:function(){
alert(“服务器繁忙,轻稍后再试”);
}
});
wx.ready(function(){
$(‘#btn’).on(‘click’,function(){
//调用选择图片的jssdk;
wx.chooseImage({
count: 1,
needResult: 1,
sizeType: [‘original’, ‘compressed’], // 可以指定是原图还是压缩图,默认二者都有
sourceType: [‘album’, ‘camera’], // 可以指定来源是相册还是相机,默认二者都有
success: function (data) {
var localIds = data.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
(‘#pic’).attr(‘src’, localIds.toString());
wx.uploadImage({
localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
var medias = {‘lid’:localIds.toString(), ‘sid’:res.serverId};
//从腾讯服务器下载到本地服务器;.ajax({
url: “/before/user/user/uploadPersonalPhoto/”,
data: {
media: $.trim(medias.sid)
},
type: “post”,
dataType: “json”,
success: function (data) {
if(data.info==true){
alert(“上传成功”);
}
else{
alert(data.info);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(“提交失败” + textStatus);
}
});
},fail:function(res){
alert(“上传失败”);
}
});
},
fail: function (res) {
alterShowMessage(“操作提示”, JSON.stringify(res), “1”, “确定”, “”, “”, “”);
}
});
});
注:在公众号平台–公众设置–功能设置里面配置JS接口安全域名,否则无法调用
3.流读取微信服务器图片存到七牛
/**
* 多媒体下载接口
* @comment 不支持视频文件的下载
* @param method 请求方式
* @param mediaId 素材ID(对应上传后获取到的ID)
* @param key 七牛key值(图片名字)
* @return 素材文件
* @author tianyu
* 时间:2017-6-10 下午2:47:57
*/
public static File httpRequestToFile(String fileName,String key,String method, String mediaId,String body) {
if(method==null){
return null;
}
String access_token = WeChatAccessTicket.getAccessTicket().getAccess_token();
String path = “https://api.weixin.qq.com/cgi-bin/media/get?access_token=“+access_token+”&media_id=”+mediaId;
File file = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
//请求微信URL
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
inputStream = conn.getInputStream();
//文件保存url
String saveUrl = “\upload\weixinImage\”;
fileName = fileName+saveUrl;
file = new File(fileName);
//创建文件夹
if(!file.exists()){
file.mkdirs();
}
fileName =fileName+key+”.jpg”;
//写入文件
if(inputStream!=null){
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
byte[] data = new byte[1024];
int len = -1;
while ((len = inputStream.read(data)) != -1) {
bos.write(data,0,len);
}
bos.close();
inputStream.close();
}else{
return file;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(conn!=null){
conn.disconnect();
}
}
return file;
}
附:微信get请求返回jsonstring工具类
public static String httpSendGet(String url) throws Exception {
String responseMsg = “”;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);// GET请求
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,”UTF-8”);
httpClient.executeMethod(getMethod);// 发送请求
byte[] responseBody = getMethod.getResponseBody();
responseMsg = new String(responseBody, “utf-8”);
getMethod.releaseConnection();// 关闭连接
return responseMsg;
}
不尽详细,希望能给大家帮助。