微信支付java版本之获取Access_token
access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。 公众平台的API调用所需的access_token的使用及生成方式说明: 1、为了保密appsecrect,第三方需要一个access_token获取和刷新的中控服务器。而其他业务逻辑服务器所使用的access_token均来自于该中控服务器,不应该各自去刷新,否则会造成access_token覆盖而影响业务; 如果第三方不使用中控服务器,而是选择各个业务逻辑点各自去刷新access_token,那么就可能会产生冲突,导致服务不稳定。 公众号可以使用AppID和AppSecret调用本接口来获取access_token。AppID和AppSecret可在微信公众平台官网-开发者中心页中获得(需要已经成为开发者,且帐号没有异常状态)。注意调用所有微信接口时均需使用https协议。 接口调用请求说明 参数说明 返回说明
正常情况下,微信会返回下述JSON数据包给公众号: 错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误): 2.代码实现 APPID,APPSECRET在公众账号中可查询 package com.zhrd.bussinss.platform.scheduled; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.zhrd.bussinss.platform.constants.WeiXinId; import com.zhrd.bussinss.platform.service.AccessTokenService; import net.sf.json.JSONObject; @Component @Lazy(false) public class GetWeiXinAccessTokenScheduled { /** * 获得ACCESS_TOKEN * * @Title: getAccess_token * @Description: 获得ACCESS_TOKEN * @param @return 设定文件 * @return String 返回类型 * @throws */ @Autowired private AccessTokenService accessTokenServiceImpl; @Scheduled(fixedRateString = "${weixin.token.fixedRate.in.milliseconds}",initialDelayString = "${weixin.token.initialDelay.in.milliseconds}") public void getAccessToken() { System.out.println("====================获取token开始=============================="); String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinId.APPID+ "&secret=" + WeiXinId.APPSECRET; String accessToken = null; String expiresIn = null; 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); 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); accessToken = demoJson.getString("access_token"); expiresIn = demoJson.getString("expires_in"); System.out.println("accessToken===="+accessToken); System.out.println("expiresIn==="+expiresIn); accessTokenServiceImpl.addToken(accessToken,expiresIn); System.out.println("====================获取token结束=============================="); is.close(); } catch (Exception e) { e.printStackTrace(); } // return accessToken; } } 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |