以前公司准备开发微信公众号,自己百度一下,学习别人的做的,具体从哪看的记不清了。这是整理的笔记。贴出代码,以供参考
后台
public class WeiXinConfigModel { public String timestamp; public String signature; public String noncestr; public String appid; public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getNoncestr() { return noncestr; } public void setNoncestr(String noncestr) { this.noncestr = noncestr; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } }
import java.sql.Timestamp; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "accesstoken") public class AccessToken { @Id private String accessTokenId; private String appid; private String secret; private String access_token; private String create_time; private Timestamp createTimeStamp; public Timestamp getCreateTimeStamp() { return createTimeStamp; } public void setCreateTimeStamp(Timestamp createTimeStamp) { this.createTimeStamp = createTimeStamp; } public String getAccessTokenId() { return accessTokenId; } public void setAccessTokenId(String accessTokenId) { this.accessTokenId = accessTokenId; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } }
import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.carlock.model.AccessToken; import com.carlock.model.WeiXinConfigModel; import com.carlock.service.AccessTokenService; @Controller @RequestMapping("/weixin") public class WeiXinController1 { Logger logger = Logger.getLogger(this.getClass()); static String AppId = "wxb2fdcdfsdfdsfs";// 第三方用户唯一凭证 static String secret = "1cd9198e6bc4sdsdsdsdsds";// 第三方用户唯一凭证密钥,即appsecret @Autowired AccessTokenService accessTokenService; public static String getAccessToken() { String access_token = ""; String grant_type = "client_credential";// 获取access_token填写client_credential // 这个url链接地址和参数皆不能变 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + AppId + "&secret=" + secret; try { URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒 http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String message = new String(jsonBytes, "UTF-8"); JSONObject demo=JSON.parseObject(message); access_token=demo.getString("access_token"); is.close(); } catch (Exception e) { e.printStackTrace(); } return access_token; } public static String getTicket(String access_token) { String ticket = null; String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";// 这个url链接和参数不能变 try { URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒 http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String message = new String(jsonBytes, "UTF-8"); JSONObject demoJson = JSON.parseObject(message); ticket = demoJson.getString("ticket"); is.close(); } catch (Exception e) { e.printStackTrace(); } return ticket; } public static String SHA1(String decript) { try { MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
@RequestMapping("/index")
@ResponseBody
public WeiXinConfigModel Index(HttpServletRequest request, HttpServletResponse response, String address,
AccessToken accessToken,Model model) {
// 1、获取AccessToken
String access_token ="";
if(access_token==null||access_token==""){
accessToken=accessTokenService.select();
if(accessToken.getAccess_token()==null||accessToken.getAccess_token().equals("")||accessToken.getAccess_token().length()<=0){
access_token=getAccessToken();
saveAccessToken(access_token);
}else{
//如果以前获取过
//access_token有失效时间,先检查以前存入的是不是已经失效
Long now = new Date().getTime();//获取当前时间的
//当前时间减去存入时间,看看是不是在失效时间范围7200S内,我这里设置的验证时间小于7200s
Long count = now - accessToken.getCreateTimeStamp();// 1000*60*2
int nowLong = 1000 * 60 * 100;// 100分钟
if (count > nowLong) {//失效了 重新获取存入
access_token=getAccessToken();
saveAccessToken(access_token);
}else{//未失效,下面直接调用,这个可以不要
}
}
}
// 2、获取Ticket
String jsapi_ticket = getTicket(access_token);
// 3、时间戳和随机字符串
String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);// 随机字符串
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
// 5、将参数排序并拼接字符串
String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url="
+ address;
// 6、将字符串进行sha1加密
String signature = SHA1(str);
WeiXinConfigModel weixin = new WeiXinConfigModel();
weixin.setSignature(signature);
weixin.setNoncestr(noncestr);
weixin.setTimestamp(timestamp);
weixin.setAppid(AppId);
return weixin;
}
//保存access_token
public void saveAccessToken(String access_token){
try {
AccessToken accessToken=new AccessToken();
accessToken.setAccess_token(access_token);//AppId
accessToken.setAppid(AppId);
accessToken.setSecret(secret);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Date date=new Date();
String time=df.format(date);
accessToken.setCreate_time(time);
accessTokenService.insert(accessToken); //保存accessToken,可以根据自己情况存入数据库
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
前台
引入微信js插件
在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script> <script type="text/javascript"> //获取微信验证 $(function() { var signature; var noncestr; var timestamp; var appid; var url1 = window.location.href; //获取当前路径 记住域名一定要在微信公众号添加了安全域名配置 $(document).ready( function() { $.ajax({ type : "post", url : "/weixin/index?address="+ window.location.href,//通过后台请求,获取微信验证信息 dataType : "json", contentType : "application/json; charset=utf-8", success : function(data) { signature = data.signature; noncestr = data.noncestr; timestamp = data.timestamp; appid = data.appid; wx.config({ debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId : appid, // 必填,公众号的唯一标识 timestamp : timestamp1, // 必填,生成签名的时间戳 nonceStr : noncestr,// 必填,生成签名的随机串 signature : signature,// 必填,签名,见附录1 jsApiList : [ 'scanQRCode' ]// 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); //config信息验证失败 wx.error(function(res) { alert("验证失败"); }); }, error : function(data) { alert('网络错误'); } }); }); }); //点击扫码按钮 $("#scanRCode").click(function(){ wx.scanQRCode({ needResult : 1,//默认0,扫描结果,微信处理,1,直接返回扫描结果 scanType : [ "qrCode" ],//指定扫二维码 success : function(res) { var url = res.resultStr;//result为1时,扫码返回的结果 url即为二维码中数据 if(url.indexOf(",")>=0){ var getresult = url.split(','); var getresult1 = getresult[1]; //弹出二维码结果 alert(getresult1); }else{ //有问题 } } }); });