直接上代码:
1、发送请求获取jsapiTicket
public class JsapiTicketUtil { /*** * 模拟get请求 * @param url * @param charset * @param timeout * @return */ public static String sendGet(String url, String charset, int timeout) { String result = ""; try { URL u = new URL(url); try { URLConnection conn = u.openConnection(); conn.connect(); conn.setConnectTimeout(timeout); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line=""; while ((line = in.readLine()) != null) { result = result + line; } in.close(); } catch (IOException e) { return result; } } catch (MalformedURLException e) { return result; } return result; } /*** * 获取jsapiTicket的凭证票据 * @return */ public static String getJSApiTicket(){ //获取token String acess_token= TokenThread.accessToken.getToken(); String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi"; String backData=JsapiTicketUtil.sendGet(urlStr, "utf-8", 10000); String ticket = (String) JSONObject.fromObject(backData).get("ticket"); return ticket; } //测试 public static void main(String[] args) { String jsapiTicket = JsapiTicketUtil.getJSApiTicket(); System.out.println("调用微信jsapi的凭证票据为:"+jsapiTicket); } }
2、生成配置参数
/** * 获取timestamp,nonceStr,signature三个参数(页面配置js) * 工具类 * @author xcg * @date 2018.01.09 */ public class GenerateConfigParame { /** * 生成三个配置参数:timestamp,nonceStr,signature * @param jsapi_ticket * @param url * @return */ 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; 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; } /** * byte转换为16进制字符串 * @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); } }
3、初始化微信 jsApi,生成临时凭据,设置初始化配置参数,将参数带到页面
public class WxJsInit { /** * 初始化微信 jsApi,生成临时凭据,设置初始化配置参数 * @param request */ public static void initJsapi(HttpServletRequest request) { //默认80端口,不用加入动态地址 String dynamicUrl = request.getScheme() //当前链接使用的协议 +"://" + Parame.url + request.getContextPath() //应用名称,如果应用名称为 + request.getServletPath() //请求的相对url + "?" + request.getQueryString(); //请求参数 System.out.println("------------------------" + dynamicUrl + "------------------------"); //获取jsapi_ticket临时凭据 String jsapi_ticket = JsapiTicketUtil.getJSApiTicket(); // 注意 URL 一定要动态获取,不能 hardcode String url = dynamicUrl;//url是你请求的一个action或者controller地址,并且方法直接跳转到使用jsapi的jsp界面 Map<String, String> signMap = GenerateConfigParame.sign(jsapi_ticket, url); request.setAttribute("appId", Parame.appid); request.setAttribute("timestamp", signMap.get("timestamp")); request.setAttribute("nonceStr", signMap.get("nonceStr")); request.setAttribute("signature", signMap.get("signature")); } }
4、前台页面初始化jssdk
//--------------------微信jssdk--------------------- wx.config({ //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '${appId}', // 必填,公众号的唯一标识 timestamp: '${ timestamp}' , // 必填,生成签名的时间戳 nonceStr: '${ nonceStr}', // 必填,生成签名的随机串 signature: '${ signature}',// 必填,签名,见附录1 jsApiList: ['chooseImage',//选择图片 'uploadImage',//上传图片 'downloadImage',//下载图片 'previewImage'//预览图片 ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.error(function (res) { alert("调用微信jsapi返回的状态:"+res.errMsg); }); wx.ready(function () { });
5、打开wx.config({})中,debug:true,页面弹出{config:ok}字样,及配置完成
6、若配置失败,则检查js接口域名配置是否有误,参考官方提示配置js接口域名即可!