Home Database Mysql Tutorial 微信公共平台开发-(.net实现)5--access

微信公共平台开发-(.net实现)5--access

Jun 07, 2016 pm 03:44 PM
.net accomplish platform develop WeChat

每次在于微信交互时,都要用到access_token,但是这个值限制的是有时间的,但是access_token,在以后的高级功能里面会经常用到,所以这里不得不这里对前面所讲解的access_token改造一下。 另外需要说明的是access_token是变化的,有自己的周期,官方解释为:"

    每次在于微信交互时,都要用到access_token,但是这个值限制的是有时间的,但是access_token,在以后的高级功能里面会经常用到,所以这里不得不这里对前面所讲解的access_token改造一下。
   另外需要说明的是access_token是变化的,有自己的周期,官方解释为:"有效期为7200秒",这就要求我们把获得的access_token存入一个物理文件或者Application中,请求到过期后修改这些内容,需要用的时候读出来.或者是存入数据库,到期时修改改access_token的值。
   有些人可能想到了,如果过期我就在获得一个就好了,不用物理文件和Application也可以达到同样的效果,但是需要注意了微信平台对每天获得,access_token的次数也作了限制,一个用户出发多次,如果用户多,那肯定就超出了。所以我们还是按照以上的思路实现这些功能:
    在此之前我们已经了解了获得access_token的方法(连接)http://www.cnblogs.com/QLJ1314/p/3838058.html,现在只需要保证它的随时更新就好了.

      首先建立一个Access_token类

  

微信公共平台开发-(.net实现)5--access微信公共平台开发-(.net实现)5--access

<span> 1</span>     <span>///</span> <span><summary></summary></span>  
<span> 2</span>     <span>///</span><span>Access_token 的摘要说明  
</span><span> 3</span>     <span>///</span> <span></span>  
<span> 4</span>     <span>public</span> <span>class</span><span> Access_token  
</span><span> 5</span> <span>    {  
</span><span> 6</span>         <span>public</span><span> Access_token()  
</span><span> 7</span> <span>        {  
</span><span> 8</span>             <span>//</span>  
<span> 9</span>             <span>//</span><span>TODO: 在此处添加构造函数逻辑  
</span><span>10</span>             <span>//</span>  
<span>11</span> <span>        }  
</span><span>12</span>         <span>string</span><span> _access_token;  
</span><span>13</span>         <span>string</span><span> _expires_in;  
</span><span>14</span>       
<span>15</span>         <span>///</span> <span><summary></summary></span>  
<span>16</span>         <span>///</span><span> 获取到的凭证   
</span><span>17</span>         <span>///</span> <span></span>  
<span>18</span>         <span>public</span> <span>string</span><span> access_token  
</span><span>19</span> <span>        {  
</span><span>20</span>             <span>get</span> { <span>return</span><span> _access_token; }  
</span><span>21</span>             <span>set</span> { _access_token =<span> value; }  
</span><span>22</span> <span>        }  
</span><span>23</span>       
<span>24</span>         <span>///</span> <span><summary></summary></span>  
<span>25</span>         <span>///</span><span> 凭证有效时间,单位:秒  
</span><span>26</span>         <span>///</span> <span></span>  
<span>27</span>         <span>public</span> <span>string</span><span> expires_in  
</span><span>28</span> <span>        {  
</span><span>29</span>             <span>get</span> { <span>return</span><span> _expires_in; }  
</span><span>30</span>             <span>set</span> { _expires_in =<span> value; }  
</span><span>31</span> <span>        }  
</span><span>32</span>     }  
Copy after login
View Code

微信公共平台开发-(.net实现)5--access微信公共平台开发-(.net实现)5--access

<span>1</span>     <?xml version=<span>"<span>1.0</span><span>"</span> encoding=<span>"</span><span>utf-8</span><span>"</span>?>  
<span>2</span>     <xml>  
<span>3</span>       <access_token>初始值可以随便写</access_token>  
<span>4</span>       <access_youxrq><span>1990</span>/<span>12</span>/<span>12</span> <span>16</span>:<span>06</span>:<span>38</span></access_youxrq>  
<span>5</span>     </xml>  
Copy after login
View Code

之前获得Access_token的方法改造一下,让他给Access_token实例赋值

微信公共平台开发-(.net实现)5--access微信公共平台开发-(.net实现)5--access

<span> 1</span>     <span>public</span> <span>static</span><span> Access_token GetAccess_token()  
</span><span> 2</span> <span>        {  
</span><span> 3</span>             <span>string</span> appid =<span> 你的appid ;  
</span><span> 4</span>             <span>string</span> secret =<span> 你的secret;  
</span><span> 5</span>             <span>string</span> strUrl = <span>"</span><span>https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=</span><span>"</span> + appid + <span>"</span><span>&secret=</span><span>"</span> +<span> secret;  
</span><span> 6</span>             Access_token mode = <span>new</span><span> Access_token();  
</span><span> 7</span>       
<span> 8</span>             HttpWebRequest req =<span> (HttpWebRequest)HttpWebRequest.Create(strUrl);  
</span><span> 9</span>       
<span>10</span>             req.Method = <span>"</span><span>GET</span><span>"</span><span>;  
</span><span>11</span>             <span>using</span> (WebResponse wr =<span> req.GetResponse())  
</span><span>12</span> <span>            {  
</span><span>13</span>                 HttpWebResponse myResponse =<span> (HttpWebResponse)req.GetResponse();  
</span><span>14</span>       
<span>15</span>                 StreamReader reader = <span>new</span><span> StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);  
</span><span>16</span>       
<span>17</span>                 <span>string</span> content =<span> reader.ReadToEnd();  
</span><span>18</span>                 <span>//</span><span>Response.Write(content);  
</span><span>19</span>                 <span>//</span><span>在这里对Access_token 赋值  </span>
<span>20</span>                 Access_token token = <span>new</span><span> Access_token();  
</span><span>21</span>                 token = JsonHelper.ParseFromJson<access_token><span>(content);  
</span><span>22</span>                 mode.access_token =<span> token.access_token;  
</span><span>23</span>                 mode.expires_in =<span> token.expires_in;  
</span><span>24</span> <span>            }  
</span><span>25</span>             <span>return</span><span> mode;  
</span><span>26</span>         }  </access_token>
Copy after login
View Code

以上的方法用到了Json对象的处理,所以我把JsonHelper的代码一贴出来供大家参考,一下就是JsonHelper.cs的代码:

微信公共平台开发-(.net实现)5--access微信公共平台开发-(.net实现)5--access

<span> 1</span>     <span>using</span><span> System;  
</span><span> 2</span>     <span>using</span><span> System.IO;  
</span><span> 3</span>     <span>using</span><span> System.Text;  
</span><span> 4</span>     <span>using</span><span> System.Runtime.Serialization.Json;  
</span><span> 5</span>        
<span> 6</span>        
<span> 7</span>       
<span> 8</span>     <span>public</span> <span>class</span><span> JsonHelper  
</span><span> 9</span> <span>    {  
</span><span>10</span>         <span>///</span> <span><summary></summary></span>  
<span>11</span>         <span>///</span><span> 生成Json格式  
</span><span>12</span>         <span>///</span> <span></span>  
<span>13</span>         <span>///</span> <span><typeparam name="T"></typeparam></span>  
<span>14</span>         <span>///</span> <span><param name="obj"></span>  
<span>15</span>         <span>///</span> <span><returns></returns></span>  
<span>16</span>         <span>public</span> <span>static</span> <span>string</span> GetJson<t><span>(T obj)  
</span><span>17</span> <span>        {  
</span><span>18</span>             DataContractJsonSerializer json = <span>new</span><span> DataContractJsonSerializer(obj.GetType());  
</span><span>19</span>             <span>using</span> (MemoryStream stream = <span>new</span><span> MemoryStream())  
</span><span>20</span> <span>            {  
</span><span>21</span> <span>                json.WriteObject(stream, obj);  
</span><span>22</span>                 <span>string</span> szJson = Encoding.UTF8.GetString(stream.ToArray()); <span>return</span><span> szJson;  
</span><span>23</span> <span>            }  
</span><span>24</span> <span>        }  
</span><span>25</span>         <span>///</span> <span><summary></summary></span>  
<span>26</span>         <span>///</span><span> 获取Json的Model  
</span><span>27</span>         <span>///</span> <span></span>  
<span>28</span>         <span>///</span> <span><typeparam name="T"></typeparam></span>  
<span>29</span>         <span>///</span> <span><param name="szJson"></span>  
<span>30</span>         <span>///</span> <span><returns></returns></span>  
<span>31</span>         <span>public</span> <span>static</span> T ParseFromJson<t>(<span>string</span><span> szJson)  
</span><span>32</span> <span>        {  
</span><span>33</span>             T obj = Activator.CreateInstance<t><span>();  
</span><span>34</span>             <span>using</span> (MemoryStream ms = <span>new</span><span> MemoryStream(Encoding.UTF8.GetBytes(szJson)))  
</span><span>35</span> <span>            {  
</span><span>36</span>                 DataContractJsonSerializer serializer = <span>new</span><span> DataContractJsonSerializer(obj.GetType());  
</span><span>37</span>                 <span>return</span><span> (T)serializer.ReadObject(ms);  
</span><span>38</span> <span>            }  
</span><span>39</span> <span>        }  
</span><span>40</span>     }  </t></t></t>
Copy after login
View Code

其实还可以直接饮用Newtonsoft.Json.dll 可以直接操作json,这样更方便一些。

我们还需要写一个判断access_token是否过期如果过期更新XML文件的方法。

微信公共平台开发-(.net实现)5--access微信公共平台开发-(.net实现)5--access

<span> 1</span>     <span>///</span> <span><summary></summary></span>  
<span> 2</span>         <span>///</span><span> 根据当前日期 判断Access_Token 是否超期  如果超期返回新的Access_Token   否则返回之前的Access_Token  
</span><span> 3</span>         <span>///</span> <span></span>  
<span> 4</span>         <span>///</span> <span><param name="datetime"></span>  
<span> 5</span>         <span>///</span> <span><returns></returns></span>  
<span> 6</span>         <span>public</span> <span>static</span> <span>string</span><span> IsExistAccess_Token()  
</span><span> 7</span> <span>        {  
</span><span> 8</span>       
<span> 9</span>             <span>string</span> Token = <span>string</span><span>.Empty;  
</span><span>10</span> <span>            DateTime YouXRQ;  
</span><span>11</span>             <span>//</span><span> 读取XML文件中的数据,并显示出来 ,注意文件路径  </span>
<span>12</span>             <span>string</span> filepath = Server.MapPath(<span>"</span><span>XMLFile.xml</span><span>"</span><span>);  
</span><span>13</span>       
<span>14</span>             StreamReader str = <span>new</span><span> StreamReader(filepath, System.Text.Encoding.UTF8);  
</span><span>15</span>             XmlDocument xml = <span>new</span><span> XmlDocument();  
</span><span>16</span> <span>            xml.Load(str);  
</span><span>17</span> <span>            str.Close();  
</span><span>18</span> <span>            str.Dispose();  
</span><span>19</span>             Token = xml.SelectSingleNode(<span>"</span><span>xml</span><span>"</span>).SelectSingleNode(<span>"</span><span>Access_Token</span><span>"</span><span>).InnerText;  
</span><span>20</span>             YouXRQ = Convert.ToDateTime(xml.SelectSingleNode(<span>"</span><span>xml</span><span>"</span>).SelectSingleNode(<span>"</span><span>Access_YouXRQ</span><span>"</span><span>).InnerText);  
</span><span>21</span>       
<span>22</span>             <span>if</span> (DateTime.Now ><span> YouXRQ)  
</span><span>23</span> <span>            {  
</span><span>24</span>                 DateTime _youxrq =<span> DateTime.Now;  
</span><span>25</span>                 Access_token mode =<span> GetAccess_token();  
</span><span>26</span>                 xml.SelectSingleNode(<span>"</span><span>xml</span><span>"</span>).SelectSingleNode(<span>"</span><span>Access_Token</span><span>"</span>).InnerText =<span> mode.access_token;  
</span><span>27</span>                 _youxrq = _youxrq.AddSeconds(<span>int</span><span>.Parse(mode.expires_in));  
</span><span>28</span>                 xml.SelectSingleNode(<span>"</span><span>xml</span><span>"</span>).SelectSingleNode(<span>"</span><span>Access_YouXRQ</span><span>"</span>).InnerText =<span> _youxrq.ToString();  
</span><span>29</span> <span>                xml.Save(filepath);  
</span><span>30</span>                 Token =<span> mode.access_token;  
</span><span>31</span> <span>            }  
</span><span>32</span>             <span>return</span><span> Token;  
</span><span>33</span>         }  
Copy after login
View Code

好了,完成了上面的工作,我只需要在使用到access_token的时调用如下就OK了,“客户再也不用担心token的过期”
string _access_token = IsExistAccess_Token();

 

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)

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 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...

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.

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.

C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

See all articles