微信公众号扫一扫接口开发
因为个人兴趣,研究了一下微信扫码支付接口
实战
1、 首先搭建一个springboot+mybatis+maven项目,创建html页面和js文件、确保直接访问html能够正常运行、html页面引入jweixin-1.0.0.js和jquery-3.2.1.min.js和自己添加的js页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>微信扫一扫</title>
<!--<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>-->
<script type="text/javascript" src="/jweixin-1.0.0.js"></script>
<script type="text/javascript" src="/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/weixin.js"></script>
</head>
<body>
<input id="timestamp" type="hidden" value="${timestamp}" />
<input id="noncestr" type="hidden" value="${nonceStr}" />
<input id="signature" type="hidden" value="${signature}" />
</body>
</html>
2、接下来进入js页面、首先执行微信JS-SDK验证,获取生成签名的时间戳、生成签名的随机串、签名。注意这里的url必须要实时动态的获取,(已踩坑)
$(document).ready(function(){
getWeixinParams();
});
/**
* 微信JS-SDK验证
*/
function getWeixinParams(){
var pageUrl ={
url:(window.location.href).split('#')[0]
};
$.ajax({
type:"post",
url:"./getSign",
data:pageUrl,
datatype:"json",
success:function(data){
var timestamp=data["weixin"]["timestamp"];
var noncestr=data["weixin"]["nonceStr"];
var signature=data["weixin"]["signature"];
getWeixinParamsCallBack(timestamp,noncestr,signature);
},
error:function(){
alert("error");
}
});
}
3、后台Controller类方法
/**
* 获取签名算法
*/
@RequestMapping(value="/getSign",method=RequestMethod.POST)
@ResponseBody
public JSONObject getSign(HttpServletRequest request,
HttpServletResponse response,String url){
JSONObject jsonObject=new JSONObject();
//String url="http://###########/weixin/index.html";
Map<String, String> ret =WxJSUtil.sign(url);
System.out.println("map="+ret.toString());
jsonObject.put("weixin", ret);
return jsonObject;
}
4、WxJSUtil验签工具类,appId、appSecret 在微信公众号开发者应用里面寻找
public static Map<String, String> sign(String url) {
String appId = "###########";
String appSecret = "###########";
String access_token = getTokenTool(appId, appSecret).getString("access_token");
JSONObject ticketJson = getTicketTool(access_token);
System.out.println(ticketJson.toString());
String jsapi_ticket = ticketJson.getString("ticket");
Map<String, String> ret = new HashMap<String, String>();
//这里的jsapi_ticket是获取的jsapi_ticket。
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
System.out.println("crypt=" + crypt.toString());
System.out.println("string1=" + string1);
System.out.println("signature=" + signature);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
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);
}
public static JSONObject getTicketTool(String access_token) {
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
// System.out.println(HttpRequestUtil.httpRequest(url, "GET", ""));
return HttpRequestUtil.httpRequest(url, "GET", "");
}
public static JSONObject getTokenTool(String appId, String appSecret) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
// System.out.println(HttpRequestUtil.httpRequest(url, "GET", ""));
return HttpRequestUtil.httpRequest(url, "GET", "");
}
5、通过ajax回调把获取(生成签名的时间戳、生成签名的随机串、签名)到的数据赋值给调取wx.config方法、见注释。
- jsApiList有很多接口,不同接口填写不同值、如扫一扫:scanQRCode。
- 开启debug(debug : true)模式,调取摄像头会出现弹框,提示调用成功,获取数据过后也会出现弹 框,显示你从二维码获取到的值。
- needResult:1 通过二维码扫出来的值,是需要格式解析,
- needResult:0 扫描结果由微信处理,不用进行格式解析,二维码中存的是什么,返回值就是什么
- scanType: [“qrCode”,“barCode”], 可以指定扫二维码还是一维码,默认二者都有
/**
* 选择要调用的接口,jsApiList:接口名称
*/
function getWeixinParamsCallBack(_timestamp,_noncestr,_signature){
wx.config({
debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId : '###########', // 必填,公众号的唯一标识
timestamp : _timestamp, // 必填,生成签名的时间戳
nonceStr : _noncestr, // 必填,生成签名的随机串
signature : _signature,// 必填,签名,见附录1
jsApiList : [ 'scanQRCode' ]
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function(){
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
wx.scanQRCode({
needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
}
});
});
wx.error(function(res){
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
alert(res);
});
}
6:通过扫一扫获取二维码中的值,进行支付接口调用
/**
* 对获取的结果进行处理
*/
function getWeixinResultCallBack(_myResult){
//window.href=_myResult;
alert(_myResult);
// var myResult='http://localhost:8081/payment.html?moeny="+moeny+"&code"+code';
$.ajax({
type:"post",
url:"/payment",
data:{myResult:myResult},
datatype:"json",
success:function(data){
//进入后台验证session如果存在返回1、跳转支付界面。不存在返回0、跳转登录界面
if(data==1){
//支付界面
window.location.href="http://localhost:8081/weixin/payment.html?moeny=\"+moeny+\"&code\"+code";
}else{
//登录界面
//window.location.href="http://localhost:8081/payment.html";
}
}
});
}