概述
微信JS-SDK是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。
通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。
相应官方文档
微信公众平台开发文档
JS-SDK说明文档
接口调用步骤(整体步骤相对还是比较简单的)
-
1.配置JS接口安全域名(此处类似于搭建微信测试号,可通过Natapp等映射工具实现)
- 2.JS-SDK验证(具体步骤会在代码中标明)
- 3.调起微信扫一扫接口
调用思路:
1.验证JS-SDK
-
官网文档
- 下载后的示例代码
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 ret = sign(jsapi_ticket, url);
for (Map.Entry entry : ret.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
};
public static Map sign(String jsapi_ticket, String url) {
Map ret = new HashMap();
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 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 ret = new HashMap();
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 map = JsSignUtil.sign(urlDecode);
return Result.success(map);
}
-
前端接口调用代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
微信扫一扫
<%--步骤二:引入JS文件--%>
-
结果