微信测试号开发之四 获取access_token和jsapi_ticket

原文:https://blog.csdn.net/qq_37936542/article/details/78549233

access_token:公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。


jsapi_ticket:jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务,开发者必须在自己的服务全局缓存jsapi_ticket 。


由于上述两个标识获取都有限制,而且有效期是两个小时,所以开发时设置为每一小时获取一次


(一):导入httpclient依赖和jackson依赖

  1. <!-- httpclient -->  
  2. <dependency>  
  3. <groupId>org.apache.httpcomponents</groupId>  
  4. <artifactId>httpclient</artifactId>  
  5. <version>4.1.2</version>  
  6. </dependency>  
  7. <dependency>  
  8. <groupId>org.apache.httpcomponents</groupId>  
  9. <artifactId>httpclient-cache</artifactId>  
  10. <version>4.1.2</version>  
  11. </dependency>  
  12. <dependency>  
  13. <groupId>org.apache.httpcomponents</groupId>  
  14. <artifactId>httpmime</artifactId>  
  15. <version>4.1.2</version>  
  16. </dependency>  
  17.   
  18.   
  19. <!-- jack json -->  
  20. <dependency>  
  21. <groupId>com.fasterxml.jackson.core</groupId>  
  22. <artifactId>jackson-core</artifactId>  
  23. <version>2.7.3</version>  
  24. </dependency>  
  25. <dependency>  
  26. <groupId>com.fasterxml.jackson.core</groupId>  
  27. <artifactId>jackson-annotations</artifactId>  
  28. <version>2.7.3</version>  
  29. </dependency>  
  30. <dependency>  
  31. <groupId>com.fasterxml.jackson.core</groupId>  
  32. <artifactId>jackson-databind</artifactId>  
  33. <version>2.7.3</version>  
  34. </dependency>  

(二):封装httpclient处理get和post请求

  1. import java.io.IOException;  
  2. import java.util.List;  
  3.   
  4.   
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.entity.StringEntity;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.apache.http.util.EntityUtils;  
  14.   
  15.   
  16. import com.fasterxml.jackson.databind.ObjectMapper;  
  17. public class CommonUtils {  
  18.   
  19. private static HttpClient CLIENT = new DefaultHttpClient();  
  20.   
  21. private static ObjectMapper MAPPER = new ObjectMapper();  
  22.   
  23. public static String APPID ="wx273a3bf59a7d2fee";  
  24.   
  25. public static String SECRET="0ca672094780b3ecf9cedcf35891b129";  
  26.   
  27. /** 
  28. * 根据url获取返回对象 
  29. * @param <T> 
  30. * @param url 
  31. * @return  
  32. * @throws Exception 
  33. */  
  34. public static <T> T returnMsg(String url,Class<T> clazz) throws Exception{  
  35. HttpPost msgPost = new HttpPost(url);  
  36. String str = EntityUtils.toString(CLIENT.execute(msgPost).getEntity(),"UTF-8");  
  37. return MAPPER.readValue(str, clazz);  
  38. }  
  39.   
  40.   
  41. /** 
  42. * httpclient模拟get请求 
  43. */  
  44. public static String Get(String url) throws Exception{  
  45. HttpGet httpGet = new HttpGet(url);  
  46. String str = EntityUtils.toString(CLIENT.execute(httpGet).getEntity(),"UTF-8");  
  47. return str;  
  48. }  
  49.   
  50. /** 
  51. * http模拟post请求,请求参数是json数据 
  52. * @param url 
  53. * @param param 
  54. * @return 
  55. * @throws IOException  
  56. * @throws Exception  
  57. */  
  58. public static String Post_Json(String url, String param) throws Exception{  
  59. HttpPost httpPost = new HttpPost(url);  
  60. //防止参数乱码  
  61.         httpPost.addHeader("Content-type","application/json; charset=utf-8");    
  62.         httpPost.setEntity(new StringEntity(param, "UTF-8"));  
  63.         //执行请求  
  64.         HttpResponse execute = CLIENT.execute(httpPost);  
  65.         String resp = EntityUtils.toString(execute.getEntity());  
  66.         return resp;  
  67.   
  68. }  
  69.   
  70. /** 
  71. * httpclient模拟表单提交 
  72. * @param url 
  73. * @param param 
  74. * @return 
  75. * @throws Exception 
  76. */  
  77. public static String Post_From(String url, List<NameValuePair> list) throws Exception{  
  78. HttpPost httpPost = new HttpPost(url);  
  79. //防止参数乱码  
  80.         httpPost.addHeader("Content-type","application/json; charset=utf-8");    
  81.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");  
  82.         httpPost.setEntity(entity);  
  83.         //执行请求  
  84.         HttpResponse execute = CLIENT.execute(httpPost);  
  85.         String resp = EntityUtils.toString(execute.getEntity());  
  86.         return resp;  
  87. }  
  88.   
  89.   
  90. }  


(三):获取access_token和jsapi_ticket

  1. import org.springframework.stereotype.Service;  
  2.   
  3.   
  4. import com.mote.weixin.utils.CommonUtils;  
  5.   
  6.   
  7. /** 
  8.  * 定时刷新access_token--微信全局凭证 
  9.  * 定时刷新jsapi_ticket--调用微信js接口的临时票据 
  10.  * @author lenovo 
  11.  * 
  12.  */  
  13. @Service("tokenService")  
  14. public class TokenService {  
  15.   
  16. private String access_token;  
  17. private String jsapi_ticket;  
  18.   
  19. public String getAccess_token() {  
  20. return access_token;  
  21. }  
  22.   
  23.   
  24. public void setAccess_token(String access_token) {  
  25. this.access_token = access_token;  
  26. }  
  27.   
  28.   
  29. public String getJsapi_ticket() {  
  30. return jsapi_ticket;  
  31. }  
  32.   
  33.   
  34. public void setJsapi_ticket(String jsapi_ticket) {  
  35. this.jsapi_ticket = jsapi_ticket;  
  36. }  
  37.   
  38.   
  39. /** 
  40. * 将该方法配置成定时任务,程序启动后五秒自动调用, 
  41. * 之后每隔一小时刷新一次 
  42. */  
  43. public void flush(){  
  44.   
  45. System.out.println("===================我被调用了=================");  
  46.   
  47. try {  
  48. //获取access_token  
  49. String accessToken = CommonUtils.getAccessToken();  
  50. this.access_token = accessToken;  
  51.   
  52. //获取jsapi_ticket  
  53. String jsApiTicket = CommonUtils.getJsApiTicket(accessToken);  
  54. this.jsapi_ticket = jsApiTicket;  
  55.   
  56.   
  57. catch (Exception e) {  
  58. System.out.println("刷新access_token失败");  
  59. e.printStackTrace();  
  60. }  
  61.   
  62. }  
  63.   
  64. }  


(四):定义AccessToken对象,然后在CommonUtils中添加获取access_token和jsapi_ticket的方法

  1. public class AccessToken {  
  2.     // 接口访问凭证  
  3.     private String accessToken;  
  4.     // 凭证有效期,单位:秒  
  5.     private int expiresIn;  
  6.   
  7.     public String getAccessToken() {  
  8.         return accessToken;  
  9.     }  
  10.   
  11.     public void setAccessToken(String accessToken) {  
  12.         this.accessToken = accessToken;  
  13.     }  
  14.   
  15.     public int getExpiresIn() {  
  16.         return expiresIn;  
  17.     }  
  18.   
  19.     public void setExpiresIn(int expiresIn) {  
  20.         this.expiresIn = expiresIn;  
  21.     }  
  22. }  


  1. /** 
  2. * 获取access_token 
  3. * @return 
  4. * @throws Exception 
  5. */  
  6. public static String getAccessToken() throws Exception{  
  7. String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+SECRET+"";  
  8. AccessToken token = returnMsg(url, AccessToken.class);  
  9. return token.getAccessToken();  
  10. }  
  11.   
  12. /** 
  13.      * 获取调用微信JS接口的临时票据 
  14.      *  
  15.      * @param access_token 微信全局凭证 
  16.      * @return 
  17. * @throws IOException  
  18. * @throws Exception  
  19.      */  
  20.     public static String getJsApiTicket(String access_token) throws Exception{  
  21.         String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";  
  22.         // 发起GET请求获取凭证  
  23.         String resq = Get(url);  
  24.         JsonNode tree = MAPPER.readTree(resq);  
  25.         return tree.get("ticket").toString().replaceAll(""""");  
  26.     }  


(五):配置TokenService中的flush方法,使其生效

注意:引入xml约束

  1. xmlns:task="http://www.springframework.org/schema/task"  
  2. http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">  

配置如下:

  1. <!-- 如果TokeService添加了注解,bean可以省略 -->  
  2. <bean id="tokenService" class="com.mote.wx.service.TokenService">  
  3. </bean>  
  4. <!-- spring自带的定时刷新任务 -->  
  5. <task:scheduled-tasks>  
  6.    <!-- 程序启动5秒后执行方法,之后每隔一小时执行 -->  
  7. <task:scheduled ref="tokenService" method="flush" initial-delay="5000" fixed-delay="3600000" />  
  8. <!-- <task:scheduled ref="statJob" method="statLgj" cron="0 59 23 * * ?" /> -->  
  9. </task:scheduled-tasks>  


文末福利:

福利一:前端,Java,产品经理,微信小程序,Python等10G资源合集大放送:jianshu.com/p/e8197d4d9

福利二:微信小程序入门与实战全套详细视频教程。


【领取方法】

关注 【编程微刊】微信公众号:

回复【小程序demo】一键领取130个微信小程序源码demo资源。

回复【领取资源】一键领取前端,Java,产品经理,微信小程序,Python等资源合集10G资源大放送。





原文作者:祈澈姑娘
原文链接:jianshu.com/u/05f416aef
创作不易,转载请告知

90后前端妹子,爱编程,爱运营,爱折腾。
坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,欢迎大家一起探讨交流。


原文地址:https://www.cnblogs.com/wangting888/p/9701600.html