


How to solve the access_token expiration problem in .Net WeChat development
Mar 28, 2017 pm 02:43 PMThis 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
/// <summary> ///Access_token 的摘要說明 /// </summary> public class Access_token { public Access_token() { // //TODO: 在此處添加構(gòu)造函數(shù)邏輯 // } 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; } } }
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.
<?xml version="1.0" encoding="utf-8"?> <xml> <Access_Token>初始值可以隨便寫</Access_Token> <Access_YouXRQ>1980/12/12 16:06:38</Access_YouXRQ> </xml>
Change the previous method of obtaining Access_token and let it assign value to the Access_token instance
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; }
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:
##
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); } } }We also need a way to determine whether the access_token has expired and update the XML file if it expires.
/// <summary> /// 根據(jù)當(dāng)前日期 判斷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文件中的數(shù)據(jù),并顯示出來 ,注意文件路徑 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; }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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. The Origin of .NETCore When talking about .NETCore, we must not mention its predecessor .NET. Java was in the limelight at that time, and Microsoft also favored Java. The Java virtual machine on the Windows platform was developed by Microsoft based on JVM standards. It is said to be the best performance Java virtual machine at that time. However, Microsoft has its own little abacus, trying to bundle Java with the Windows platform and add some Windows-specific features. Sun's dissatisfaction with this led to a breakdown of the relationship between the two parties, and Microsoft then launched .NET. .NET has borrowed many features of Java since its inception and gradually surpassed Java in language features and form development. Java in version 1.6

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

The best cryptocurrency trading and analysis platforms include: 1. OKX: the world's number one in trading volume, supports multiple transactions, provides AI market analysis and on-chain data monitoring. 2. Binance: The world's largest exchange, providing in-depth market conditions and new currency first-time offerings. 3. Sesame Open Door: Known for spot trading and OTC channels, it provides automated trading strategies. 4. CoinMarketCap: an authoritative market data platform, covering 20,000 currencies. 5. CoinGecko: Known for community sentiment analysis, it provides DeFi and NFT trend monitoring. 6. Non-small account: a domestic market platform, providing analysis of linkage between A-shares and currency markets. 7. On-chain Finance: Focus on blockchain news and update in-depth reports every day. 8. Golden Finance: 24 small

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

The login portal for the Douyin web version is https://www.douyin.com/. The login steps include: 1. Open the browser; 2. Enter the URL https://www.douyin.com/; 3. Click the "Login" button and select the login method; 4. Enter the account password; 5. Complete login. The web version provides functions such as browsing, searching, interaction, uploading videos and personal homepage management, and has advantages such as large-screen experience, multi-tasking, convenient account management and data statistics.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

Binance C2C transactions allow users to buy and sell cryptocurrencies directly, and pay attention to the risks of counterparty, payment and price fluctuations. Choosing high-credit users and secure payment methods can reduce risks.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.
