java后端实现微信分享接口

南笙酒味 提交于 2019-12-31 02:07:33

微信官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

步骤:

1,得到需要分享的页面链接,必传部分以#结束
2,获取到#前的链接
3,根据微信appid获取access_token(这个与网页授权的access_token不一样,并且7200秒内只能获取一次)

			String 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.parseObject(message);
				System.out.println("JSON字符串:" + demoJson);
				access_token = demoJson.getString("access_token");
				if (StringUtils.isNotBlank(access_token)) {
					String key = RedisDBase.BGY_MEMBER + "access_token";
					redisTemplate.set(key, RedisDBase.DBASE_BASE, access_token, 7200);
				} else {
					return message + "微信返回错误提示";
				}
				is.close();
			} catch (Exception e) {
				logger.error("call getAccessToken error",e);
			}

最好是保存在redis里,可根据提示返回的5位数结果码查询问题
4,根据access_token获取jsapi_ticket

		String ticket = null;
		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.parseObject(message);
			System.out.println("JSON字符串:"+demoJson);
			ticket = demoJson.getString("ticket");
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

这个值也是两个小时只能获取一次,最好保存在redis里
5,生成8位数的随机字符串

public static String getRandomStr(int length) {
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		int randomNum;
		char randomChar;
		Random random = new Random();
		// StringBuffer类型的可以append增加字符
		StringBuffer str = new StringBuffer();

		for (int i = 0; i < length; i++) {
			// 可生成[0,n)之间的整数,获得随机位置
			randomNum = random.nextInt(base.length());
			// 获得随机位置对应的字符
			randomChar = base.charAt(randomNum);
			// 组成一个随机字符串
			str.append(randomChar);
		}
		return str.toString();
	}

6,拼接数据

		long timeStampSec = System.currentTimeMillis()/1000;
		String timestamp = String.format("%010d", timeStampSec);//当前时间戳
		String nonceStr = getRandomStr(8);//随机数
		String[] signArr = new String[]{"url=" + newUrl, "jsapi_ticket=" + ticket, "noncestr=" + nonceStr, "timestamp=" + timestamp};
		Arrays.sort(signArr);
		String signStr = org.apache.commons.lang.StringUtils.join(signArr, "&");
		String resSign = DigestUtils.sha1Hex(signStr);//加密
		Map map=new HashMap();
		map.put("appId",appId);
		map.put("timeStamp",timestamp);
		map.put("nonceStr",nonceStr);
		map.put("signature",resSign);//将map放回给前端大功告成!

最主要的问题就是判断获取acces_token返回结果,并且一定要保存到Redis,设置过期时间7200秒(2小时)!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!