微信API授权过程代码

xiaoxiao2021-02-28  8

/** * 第一步、获取access_token * APPIDAPPSECRET可以去微信公众平台---“开发----基本配置中查找。 */ public static String getAccessToken() { String access_token = cacheUtil.getString(ACCESS_TOKEN); if (StringUtils.isBlank(access_token)) { String grant_type = "client_credential";//获取access_token填写client_credential //这个url链接地址和参数皆不能变 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appId + "&secret=" + appSecret; try { URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30 http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String message = new String(jsonBytes, "UTF-8"); JSONObject demoJson = JSONObject.fromObject(message); logger.info("=getAccessToken==JSON字符串=" + demoJson); access_token = demoJson.getString("access_token"); is.close(); } catch (Exception e) { logger.error("getAccessToken", e); } cacheUtil.setString(ACCESS_TOKEN, access_token, EXPIRE_TIME); } logger.info("=getAccessToken=" + access_token); return access_token;

}

/** * 第二步、获取jsapi_ticket */ public static String getTicket(String access_token) { String ticket = cacheUtil.getString(JSAPI_TICKET); if (StringUtils.isBlank(ticket)) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";//这个url链接和参数不能变 try { URL urlGet = new URL(url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30 http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String message = new String(jsonBytes, "UTF-8"); JSONObject demoJson = JSONObject.fromObject(message); logger.info("==getTicket==JSON字符串=" + demoJson); ticket = demoJson.getString("ticket"); is.close(); } catch (Exception e) { logger.error("=getTicket=" + e); } cacheUtil.setString(JSAPI_TICKET, ticket, EXPIRE_TIME); } return ticket; } /** * sha1的加密算法 * 拿到了jsapi_ticket之后就要参数名排序和拼接字符串,并加密 */ public static String SHA1(String decript) { try { MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { logger.error("=SHA1=", e); } return ""; }获取微信API的sign //1、获取AccessToken //2、获取Ticket //3、时间戳和随机字符串 String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串 String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳 //4、将参数排序并拼接字符串 String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url; //5、将字符串进行sha1加密 String signature = SHA1(str); //6.javascript里去初始化微信API接口 引入 //res.wx.qq.com/open/js/jweixin-1.2.0.js wx.config({ debug: false, appId: data.appId, //公众号的唯一标识 timestamp: data.timestamp, //生成签名的时间戳 nonceStr: data.noncestr, //生成签名的随机串 signature: data.signature, //签名 jsApiList: [ //需要使用的JS接口列表 'onMenuShareTimeline', //分享到朋友圈 'onMenuShareAppMessage', //分享给朋友 'getLocation', 'chooseImage', 'uploadImage', 'scanQRCode' ] }); 获取微信定位 wx.getLocation({ type: 'wgs84', success: function (res) { latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90 longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180 var speed = res.speed; // 速度,以米/每秒计 var accuracy = res.accuracy; // 位置精度 } } /*分享到朋友圈*/ wx.onMenuShareTimeline({ title: data.name, // 分享标题 desc: data.message, // 分享描述 link: data.link, // 分享链接 imgUrl: data.imgUrl, // 分享图标 success: function() { // 用户确认分享后执行的回调函数 alert("您已分享"); }, cancel: function() { // 用户取消分享后执行的回调函数 alert('您已取消分享'); } }); /*分享给朋友*/ wx.onMenuShareAppMessage({ title: data.name, // 分享标题 desc: data.message, // 分享描述 link: data.link, // 分享链接 imgUrl: data.imgUrl, // 分享图标 type: 'link', // 分享类型,musicvideolink,不填默认为link dataUrl: '', // 如果typemusicvideo,则要提供数据链接,默认为空 success: function() { // 用户确认分享后执行的回调函数 alert("您已分享"); }, cancel: function() { // 用户取消分享后执行的回调函数 alert('您已取消分享'); } }); wx.error(function(res) { alert(res.errMsg); });

转载请注明原文地址: https://www.6miu.com/read-2150156.html

最新回复(0)