ASP.NET微信公眾號獲取AccessToken


access_token是公眾號的全局唯一接口調用憑據,公眾號調用各接口時都需使用access_token。開發者需要進行妥善保存。access_token的存儲至少要保留512個字符空間。access_token的有效期目前為2個小時,需定時刷新,重復獲取將導致上次獲取的access_token失效。下面是使用ASP.NET WebForm實現獲取微信公眾號AccessToken的例子。附代碼和文檔。

先看效果圖,沒有輸入appid時的效果:



獲取正確的結果:


其中長長一串的字符串就是AccessToken,7200秒表示有效時間為2小時。
獲取的結果是json格式,可以使用Newtonsoft.Json.dll對json信息進行處理,在下一篇中給出示例代碼。參考:http://hovertree.com/h/bjag/l0aqhe0f.htm

HtAccessToken.aspx頁面代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HtAccessToken.aspx.cs" Inherits="ExampleHoverTree.HtWechat.HtAccessToken" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>獲取AccessToken示例_何問起</title>
</head>
<body>
    <h3>何問起代碼練習</h3>
    <form id="form1" runat="server">
        <div>
            appid:<asp:TextBox runat="server" ID="textBox_appid" />
            <br />secret:<asp:TextBox runat="server" ID="textBox_secret" />
            <br /><asp:Button runat="server" ID="button_get"  Text="獲取Access_token" OnClick="button_get_Click"/>
            <br />
            <asp:Literal runat="server" ID="literal_tips" />
        </div>
    </form>
</body>
</html>

HtAccessToken.aspx.cs代碼:

using HoverTree.HoverTreeFrame.HtWeb;
using System;
using System.Text;

namespace ExampleHoverTree.HtWechat
{
    public partial class HtAccessToken : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void button_get_Click(object sender, EventArgs e)
        {
            literal_tips.Text = HtGetAccessToken(textBox_appid.Text, textBox_secret.Text);
        }

        string HtGetAccessToken(string appid, string appsecret)
        {
            string h_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appid + "&secret=" + appsecret;

            return HtWebHelper.GetHtmlByUrl(h_url, Encoding.Default);
        }
    }
}

其中,HtWebHelper類的GetHtmlByUrl(string url, System.Text.Encoding enCode)方法請下載HoverTreeTop源碼,在HoverTreeFrame項目中。下載地址:http://hovertree.com/h/bjaf/hv6cqe5n.htm

公眾平台的API調用所需的access_token的使用及生成方式說明:
1、建議公眾號開發者使用中控服務器統一獲取和刷新Access_token,其他業務邏輯服務器所使用的access_token均來自於該中控服務器,不應該各自去刷新,否則容易造成沖突,導致access_token覆蓋而影響業務;
2、目前Access_token的有效期通過返回的expire_in來傳達,目前是7200秒之內的值。中控服務器需要根據這個有效時間提前去刷新新access_token。在刷新過程中,中控服務器對外輸出的依然是老access_token,此時公眾平台后台會保證在刷新短時間內,新老access_token都可用,這保證了第三方業務的平滑過渡;
3、Access_token的有效時間可能會在未來有調整,所以中控服務器不僅需要內部定時主動刷新,還需要提供被動刷新access_token的接口,這樣便於業務服務器在API調用獲知access_token已超時的情況下,可以觸發access_token的刷新流程。更多:http://hovertree.com/h/bjag/x6usc7ya.htm

推薦:http://www.cnblogs.com/roucheng/category/827769.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM