承接上一篇,今天主要講述如何實現定時獲取微信access_token功能的實現。html
access_tokenweb
首先咱們根據微信的開發指南,任何對微信的操做都要使用合法獲取的access_token,微信獲取access_token限制每日次數,且每次token有效時間爲7200秒。json
獲取token的API:windows
//http請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
參數說明:api
參數 | 是否必須 | 說明 |
---|---|---|
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微信
定時任務app
根據其限制,這裏獲取token的策略爲:一小時一次,採用定時任務的方式執行。定時任務的實現方式採用Azure WebJob來實現,具體原理爲:Azure定時調用任務程序訪問指定Url,調用相應方法更新靜態access_token字段。async
定時任務程序爲簡單控制檯程序,點擊Web項目右鍵添加->新建Web Job項目,將會生成默認模版項目,簡單修改一下,其代碼以下:post
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