最近开发一个食堂项目,项目中用到使用微信扫一扫实现项目中的扫一扫的功能。
1、添加点击扫一扫的触发事件的按钮
扫一扫
2、添加微信扫一扫的js引用
3、后台调用微信扫一扫的相关参数的获取(后面会说)
4、方法调用
$(function() {
scanCode();
});
5、开启微信扫一扫
function scanCode() {
wx.config({
debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId : $("#appId").val(), // 必填,公众号的唯一标识
timestamp : $("#timestamp").val(), // 必填,生成签名的时间戳
nonceStr : $("#nonceStr").val(), // 必填,生成签名的随机串
signature : $("#signature").val(),// 必填,签名,见附录1
jsApiList : [ 'scanQRCode' ]// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
6、调用微信扫一扫
$("#scanQRCode").click(function() {
wx.scanQRCode({
needResult : 1,// 默认为0,扫描结果由微信处理,1则直接返回扫描结果
scanType : [ "qrCode", "barCode" ], // 可以指定扫二维码还是一维码,默认二者都有 */
/* desc : 'scanQRCode desc', */
success : function(res) {
var url = res.resultStr;//扫码后获取结果
location.href = url;
}
});
});
后台数据的获取
url参数为:扫一扫获取的结果,一般为路径或者加密之后的结果
JSSDK获取
public static Map getJsSdk(String url) {
Map returnMap = new HashMap();
try {
String ticket = getJsapiTicket();
if(StringUtils.isNotBlank(ticket) && StringUtils.isNotBlank(url)){
returnMap = sign(ticket, url);
returnMap.put("appId", IConstants.wxgzAppID);//微信公众号appId
}
} catch (Exception e) {
}
return returnMap;
}
生成签名
public static Map sign(String jsapi_ticket, String url) {
Map result = new HashMap();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string;
String signature = "";
// 注意这里参数名必须全部小写,且必须有序
string = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "×tamp=" + timestamp + "&url=" + url;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
result.put("url", url);
result.put("jsapi_ticket", jsapi_ticket);
result.put("nonceStr", nonce_str);
result.put("timestamp", timestamp);
result.put("signature", signature);
return result;
}
public static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
public static String create_nonce_str() {
return UUID.randomUUID().toString();
}
public static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
临时票据的生成
注意:ticket有时间刷新限制
public static String getJsapiTicket() throws Exception {
String ticken = null;
try {
String access_token = getToken();
if(access_token != null && StringUtils.isNotBlank(access_token)){
// 创建HttpClient实例
HttpClient httpclient = new DefaultHttpClient();
// 创建Get方法实例
HttpGet httpgets = new HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi"); // 免费api
HttpResponse response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
String str = convertStreamToString(instreams);
JSONObject jsOb = JSONObject.fromObject(str);
httpgets.abort();
ticken = Public.mapTo(jsOb.get("ticket"), "");
}
}
} catch (Exception e) {
// TODO: handle exception
}
return ticken;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
token获取
public static String getToken() throws Exception {
String access_token = null;
// 创建HttpClient实例
HttpClient httpclient = new DefaultHttpClient();
// 创建Get方法实例需要微信公众号appId+secret
HttpGet httpgets = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ IConstants.wxgzAppID + "&secret=" + IConstants.wxgzAppSecret);
HttpResponse response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
Map maData = new HashMap();
if (entity != null) {
InputStream instreams = entity.getContent();
String str = convertStreamToString(instreams);
JSONObject jsOb = JSONObject.fromObject(str);
httpgets.abort();
access_token = Public.mapTo(jsOb.get("access_token"), "") ;
}
return access_token;
}
项目中的扫一扫功能已经上线,如果有疑问,请留言!!!