承接上一篇,今天主要講述如何實現定時獲取微信access_token功能的實現。
access_token
首先我們根據微信的開發指南,任何對微信的操作都要使用合法獲取的access_token,微信獲取access_token限制每日次數,且每次token有效時間為7200秒。
獲取token的API:
//http請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
參數說明:
| 參數 | 是否必須 | 說明 |
|---|---|---|
| grant_type | 是 | 獲取access_token填寫client_credential |
| appid | 是 | 第三方用戶唯一憑證 |
| secret | 是 | 第三方用戶唯一憑證密鑰,即appsecret |
返回數據示例:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
詳細請看官方文檔:http://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html
定時任務
根據其限制,這里獲取token的策略為:一小時一次,采用定時任務的方式執行。定時任務的實現方式采用Azure WebJob來實現,具體原理為:Azure定時調用任務程序訪問指定Url,調用相應方法更新靜態access_token字段。
定時任務程序為簡單控制台程序,點擊Web項目右鍵添加->新建Web Job項目,將會生成默認模版項目,簡單修改一下,其代碼如下:
public class Functions { // This function will be triggered based on the schedule you have set for this WebJob // This function will enqueue a message on an Azure Queue called queue [NoAutomaticTrigger] public static void ManualTrigger(TextWriter log, int value, [Queue("queue")] out string message) { log.WriteLine("Function is invoked with value={0}", value); message = GetAccessToken(log).Result; Console.WriteLine(message); log.WriteLine("Following message will be written on the Queue={0}", message); } public static string Url = "http://cwwebservice.azurewebsites.net/api/wx?method=token"; static async Task<string> GetAccessToken(TextWriter log) { var client = new HttpClient(); var result = await client.GetStringAsync(Url); return result; } }
class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { var host = new JobHost(); // The following code will invoke a function called ManualTrigger and // pass in data (value in this case) to the function host.Call(typeof(Functions).GetMethod("ManualTrigger"), new { value = 20 }); } }

Web程序對應方法為:
private static string Access_Token = string.Empty; //刷新access_token字段 public async Task<HttpResponseMessage> Get(string method) { var response = new HttpResponseMessage(); if (method == "token") { var api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc56a0a6310833ff9&secret=05bbade59f505c93378f5be963ba3eeb"; var client = new HttpClient(); var token = await client.GetStringAsync(api); response.Content = new StringContent(token); var json = JObject.Parse(token); if (json["access_token"] != null) Access_Token = (string)json["access_token"]; } return response; }
控制台程序發布為zip文件,上傳至Azure作業儀表板,並且設定為計划任務。



查看日志


可以看到我們預定返回的access_token字段,說明我們已經在服務器上更新了Access_Token信息,這樣可以確保下一步的動作。
關於Azure Web Job的更多信息請看:http://www.windowsazure.cn/documentation/articles/web-sites-create-web-jobs/?fb=002
另外定時任務有很多種方法,推薦好基友@Ed_Wang的一篇博客,提供了另一種方式:http://edi.wang/post/2014/7/18/how-to-run-schedule-jobs-in-aspnet
