概述
微信JS-SDK是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。
通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。
相应官方文档
接口调用步骤(整体步骤相对还是比较简单的)
-
1.配置JS接口安全域名(此处类似于搭建微信测试号,可通过Natapp等映射工具实现)
- 2.JS-SDK验证(具体步骤会在代码中标明)
- 3.调起微信扫一扫接口
调用思路:
1.验证JS-SDK
-
官网文档
来源JS-SDK说明文档附录6 - 下载后的示例代码
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
class Sign {
public static void main(String[] args) {
String jsapi_ticket = "jsapi_ticket";
// 注意 URL 一定要动态获取,不能 hardcode
String url = "http://example.com";
Map<String, String> ret = sign(jsapi_ticket, url);
for (Map.Entry entry : ret.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
};
public static Map<String, String> sign(String jsapi_ticket, String url) {
Map<String, String> ret = new HashMap<String, String>();
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;
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("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
/**
* 随机加密
*
* @param hash
* @return
*/
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;
}
/**
* 产生随机串--由程序自己随机产生
*
* @return
*/
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
/**
* 由程序自己获取当前时间
*
* @return
*/
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
2. 最主要的步骤:集齐示例所需的参数
url jsapi_ticket nonceStr(已有) timestamp(已有) signature
请注意划重点的地方
3.jsapi_ticket 的获取:
-
获取JS-SDK的 accesstoken (注意:其与获取网页授权的accesstoken不同)
JSONObject accesTokenObject = JSONObject.fromObject(Doget.get(ACCESS_TOKEN_URL));
String accesToken = (String) accesTokenObject.get("access_token");
System.out.println("微信返回的accesToken" + accesToken);
-
获取jsapiTicket
JSONObject jsapiTicketObject = JSONObject.fromObject(Doget.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesToken + "&type=jsapi"));
String jsapiTicket = (String) jsapiTicketObject.get("ticket");
System.out.println("微信返回的jsapiTicket" + jsapiTicket);
-
最后对官网给的示例进行修改即可
源码(直接复制就可使用)
-
URL请求类
package com.itcast.util.wechatUtil;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Doget {
/**
* 功能描述:向指定地址发送get请求 (**发送get请求地址的时候基本都会去调用到**)
*
* @param url
* @date: 2019/1/13 15:27
* @return:
*/
public static String get(String url) {
try {
URL urlObj = new URL(url);
//开连接
URLConnection urlConnection = urlObj.openConnection();
//读取返回的JSON对象
InputStream inputStream = urlConnection.getInputStream();
byte[] b = new byte[1024];
int leng;
StringBuilder sb = new StringBuilder();
while ((leng = inputStream.read(b)) != -1) {
sb.append(new String(b, 0, leng));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
-
完善后的SignUtil
import net.sf.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class SignUtil {
public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + SignUtil.APPID + "&secret=" + SignUtil.APPSECRET + "";
public static Map<String, String> sign(String url) {
//获取JS-SDK的 accesstoken 注意:其与获取网页授权的accesstoken不同
JSONObject accesTokenObject = JSONObject.fromObject(Doget.get(ACCESS_TOKEN_URL));
String accesToken = (String) accesTokenObject.get("access_token");
System.out.println("微信返回accesToken" + accesToken);
//获取ticket
JSONObject jsapiTicketObject = JSONObject.fromObject(Doget.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesToken + "&type=jsapi"));
String jsapiTicket = (String) jsapiTicketObject.get("ticket");
System.out.println("微信返回jsapiTicket" + jsapiTicket);
Map<String, String> ret = new HashMap<String, String>();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapiTicket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
System.out.println("string1=" + 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();
} catch (Exception e) {
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapiTicket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
ret.put("appId", 你的APPID); //此时可通过配置引入
System.out.println("1.ticket(原始)=" + jsapiTicket);
System.out.println("2.url=" + ret.get("url"));
System.out.println("3.jsapi_ticket(处理后)=" + ret.get("jsapi_ticket"));
System.out.println("4.nonceStr=" + ret.get("nonceStr"));
System.out.println("5.signature=" + ret.get("signature"));
System.out.println("6.timestamp=" + ret.get("timestamp"));
return ret;
}
/**
* 随机加密
*
* @param hash
* @return
*/
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;
}
/**
* 产生随机串--由程序自己随机产生
*
* @return
*/
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
/**
* 由程序自己获取当前时间
*
* @return
*/
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
-
控制层代码(主要就是获取URL进行JS-SDK验证)
@RequestMapping("/getwechatscan")
@ResponseBody
public Result wechatscan(@RequestParam String URL) {
//转义
String urlDecode = URLDecoder.decode(URL);
Map<String, String> map = JsSignUtil.sign(urlDecode);
return Result.success(map);
}
-
前端接口调用代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta charset="UTF-8">
<title>微信扫一扫</title>
<%--步骤二:引入JS文件--%>
<script src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<input type="text" id="tesss">
<button id="scanQRCode" onclick="getWeixinResult()">扫描二维码</button>
</body>
<script>
$(document).ready(function () {
getWeixinParams();
});
//微信JS—SDK验证
function getWeixinParams() {
//不带参数URL
// var WX_url = window.location.origin + window.location.pathname;
//请求地址
alert(window.location.origin);
//请求方法
alert(window.location.pathname);
//带参数URL
var WX_url = location.href.split('#')[0];
alert(WX_url);
$.ajax({
type: "post",
url: "/getwechatscan",
data: {"URL": WX_url},
datatype: "json",
success: function (data) {
var appId = data.data.appId;
var nonceStr = data.data.nonceStr;
var signature = data.data.signature;
var timestamp = data.data.timestamp;
getWeixinParamsCallBack(appId, timestamp, nonceStr, signature);
},
error: function () {
alert("出错了");
}
});
}
//选择要调用的接口 接口名称
function getWeixinParamsCallBack(appId, timestamp, nonceStr, signature) {
//步骤三:通过config接口注入权限验证配置
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: appId, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: nonceStr, // 必填,生成签名的随机串
signature: signature, // 必填,签名
jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表
});
//步骤四:通过ready接口处理成功验证(可不写 这里只是跟你说配置成功而已)
wx.ready(function () {
alert("成功配置了微信JS");
});
//步骤五:通过error接口处理失败验证
wx.error(function (res) {
alert("相应数据获取出错了:" + res.errMsg);
});
}
function getWeixinResult() {
//调取接口
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
// desc: 'scanQRCode desc',
scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
if (result.indexOf("=") != -1) {
result = result.split("=")[1];
} else if (result.indexOf(",") != -1) {
result = result.split(",")[1];
}
$("#tesss").val(result);
// alert("扫描成功::扫描码=" + result);
}
});
}
</script>
</html>
-
结果
网友评论