微信公众号中调起微信扫一扫功能
前端
引入js(import):
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
初始化页面时通过接口对微信进行配置,加载页面时调用getConfig函数,wx.config配置正确时会调用wx.ready,在wx.ready中对扫一扫的按钮绑定点击事件。
getConfig:function () {
var params = {
"url" : location.href.split('#')[0]
};
$.post(basePath + '/portal/replenishment/wxOpen', JSON.stringify(params), function (res) {
var data = res.data;
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: data.appId, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature,// 必填,签名,见附录1
jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function () {
// 9.1.2 扫描二维码并返回结果
document.querySelector('#scanQRCode').onclick = function () {
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
iv.toIndex(result); //注:扫码返回结果后,如果需要对当前页面赋值等操作,需要另写函数
},
error:function (res) {
alert(res)
}
});
}
})
//初始化jsapi接口 状态
wx.error(function (res) {
console.log("调用微信jsapi返回的状态:" + res.errMsg);
});
});
},
toIndex:function (result) {
$("#input__inner").val(result);
iv.getGoodsList(result);
}
html中:
<button class="yy-button" id="scanQRCode">扫一扫</button>
后台
Controller层
@RequestMapping(value = "/portal/replenishment/wxOpen")
public Json wxOpen(@RequestBody Map map){
return json(portalReplenishmentService.wxOpen(map),ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg());
}
实现类
public static final String APPID = "wx6e3a11f5d7f8369f"; //微信公众号appid
public static final String APP_SECRET="6f9c7fd27bd842c81c0ac760462a40b3";//微信公众号APP_SECRET
@Override
public Map wxOpen(Map map) {
Map ret = new HashMap();
String url = map.get("url").toString();//前端获取配置时获取的 地址 参数
String jsapi_ticket= getJsapiTicket();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
int length=url.indexOf("#");
String uri = url;
if(length > 0){
uri=url.substring(0,length);//当前网页的URL,不包含#及其后面部分
}
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
System.out.println(string1);
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
ret.put("appId", APPID);
ret.put("url", uri);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
private String getJsapiTicket(){
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?";
String params = "grant_type=client_credential&appid=" + APPID + "&secret=" + APP_SECRET + "";
String result = this.httpGet(requestUrl+params);
String accessToken = com.alibaba.fastjson.JSONObject.parseObject(result).getString("access_token");
requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
params = "access_token=" + accessToken + "&type=jsapi";
result = this.httpGet(requestUrl+params);
String jsapi_ticket = com.alibaba.fastjson.JSONObject.parseObject(result).getString("ticket");
return jsapi_ticket;
}
private 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;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
strResult = EntityUtils.toString(response.getEntity());
} else {
}
} catch (IOException e) {
}
return strResult;
}
测试
在微信中测试时,需要有外网能够访问的域名,例如:http://agent.xxx.cn,不能用localhost,也不能用本机ip地址,只要在微信中访问页面地址,都能调起微信扫一扫