Home WeChat Applet WeChat Development How to solve the access_token expiration problem in .Net WeChat development

How to solve the access_token expiration problem in .Net WeChat development

Mar 28, 2017 pm 02:43 PM
.net WeChat

This article mainly introduces in detail how to solve the access_token expiration problem in .Net WeChat development. Interested friends can refer to it

Because access_token will be included in future advanced functions It is often used, so I have to modify the access_token explained earlier here.
It should also be noted that access_token changes and has its own cycle. The official explanation is: "validity period is 7200 seconds", which requires us to store the obtained access_token in a physical file or Application, and request it after expiration Modify these contents and read them out when needed.
Some people may have thought that if it expires, I will just get one. The same effect can be achieved without physical files and Application, but you need to pay attention to the WeChat platform The number of access_tokens obtained per day is also limited. A user can start multiple times. If there are many users, it will definitely be exceeded. So we still implement these functions according to the above ideas: before this we have already understood the method of obtaining access_token (connection), now we just need to ensure that it is updated at any time.
First create an Access_token class


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/// <summary>

///Access_token 的摘要说明

/// </summary>

public class Access_token

{

 public Access_token()

 {

 //

 //TODO: 在此处添加构造函数逻辑

 //

 }

 string _access_token;

 string _expires_in;

 

 /// <summary>

 /// 获取到的凭证

 /// </summary>

 public string access_token

 {

  get { return _access_token; }

  set { _access_token = value; }

 }

 

 /// <summary>

 /// 凭证有效时间,单位:秒

 /// </summary>

 public string expires_in

 {

  get { return _expires_in; }

  set { _expires_in = value; }

 }

}

Copy after login

Use the following XML file to store access_token, create an XMLFile.xml, and write the content of the Access_YouXRQ tag as a past time, so that we can call it at the beginning time, it is found that it has expired, and then a new access_token is obtained.


1

2

3

4

5

<?xml version="1.0" encoding="utf-8"?>

<xml>

 <Access_Token>初始值可以随便写</Access_Token>

 <Access_YouXRQ>1980/12/12 16:06:38</Access_YouXRQ>

</xml>

Copy after login

Change the previous method of obtaining Access_token and let it assign value to the Access_token instance


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

public static Access_token GetAccess_token()

 {

  string appid = 你的appid ;

  string secret = 你的secret;

  string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;

  Access_token mode = new Access_token();

 

  HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);

 

  req.Method = "GET";

  using (WebResponse wr = req.GetResponse())

  {

   HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();

 

   StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

 

   string content = reader.ReadToEnd();

   //Response.Write(content);

   //在这里对Access_token 赋值

   Access_token token = new Access_token();

   token = JsonHelper.ParseFromJson<Access_token>(content);

   mode.access_token = token.access_token;

   mode.expires_in = token.expires_in;

  }

  return mode;

 }

Copy after login

The above method uses the processing of Json objects, so I posted the code of JsonHelper for your reference. Here is the code of JsonHelper.cs:


##

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

using System;

using System.IO;

using System.Text;

using System.Runtime.Serialization.Json;

  

 

public class JsonHelper

{

 /// <summary>

 /// 生成Json格式

 /// </summary>

 /// <typeparam name="T"></typeparam>

 /// <param name="obj"></param>

 /// <returns></returns>

 public static string GetJson<T>(T obj)

 {

  DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());

  using (MemoryStream stream = new MemoryStream())

  {

   json.WriteObject(stream, obj);

   string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;

  }

 }

 /// <summary>

 /// 获取Json的Model

 /// </summary>

 /// <typeparam name="T"></typeparam>

 /// <param name="szJson"></param>

 /// <returns></returns>

 public static T ParseFromJson<T>(string szJson)

 {

  T obj = Activator.CreateInstance<T>();

  using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))

  {

   DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

   return (T)serializer.ReadObject(ms);

  }

 }

}

Copy after login

We also need a way to determine whether the access_token has expired and update the XML file if it expires.



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

/// <summary>

 /// 根据当前日期 判断Access_Token 是否超期 如果超期返回新的Access_Token 否则返回之前的Access_Token

 /// </summary>

 /// <param name="datetime"></param>

 /// <returns></returns>

 public static string IsExistAccess_Token()

 {

 

  string Token = string.Empty;

  DateTime YouXRQ;

  // 读取XML文件中的数据,并显示出来 ,注意文件路径

  string filepath = Server.MapPath("XMLFile.xml");

 

  StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8);

  XmlDocument xml = new XmlDocument();

  xml.Load(str);

  str.Close();

  str.Dispose();

  Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText;

  YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText);

 

  if (DateTime.Now > YouXRQ)

  {

   DateTime _youxrq = DateTime.Now;

   Access_token mode = GetAccess_token();

   xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token;

   _youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in));

   xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString();

   xml.Save(filepath);

   Token = mode.access_token;

  }

  return Token;

 }

Copy after login
Okay, after completing the above work, I only need to call the following when using access_token. "Customers no longer have to worry about tokens." Expiration"

string _access_token = IsExistAccess_Token();

The above is the detailed content of How to solve the access_token expiration problem in .Net WeChat development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

How to choose H5 and applets How to choose H5 and applets Apr 06, 2025 am 10:51 AM

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

How to solve the problem of JS resource caching in enterprise WeChat? How to solve the problem of JS resource caching in enterprise WeChat? Apr 04, 2025 pm 05:06 PM

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

What are the different ways of promoting H5 and mini programs? What are the different ways of promoting H5 and mini programs? Apr 06, 2025 am 11:03 AM

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

How to wake up the Android App on the WeChat H5 page? How to wake up the Android App on the WeChat H5 page? Apr 04, 2025 pm 02:03 PM

How to evoke Android App on the H5 page in WeChat? Many developers face this problem: how to directly...

See all articles