微信企業號要推送訊息,得先過兩關:取得 access_token,以及處理它的過期問題。本文以 C# 為例,記錄從憑證獲取、本地持久化到實際發送文字訊息的完整流程。
企業號的 gettoken 介面會回傳兩個欄位:token 本身,以及它的有效秒數。
//定義資料模型
public class Access_token
{
public Access_token()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
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; }
}
}
這裡需要兩個參數,都能在企業號後台的「設定 → 權限管理 → 系統管理組」中找到:CorpID 與 Secret。
public ActionResult index(string returnUrl)
{
GetAccess_token();
IsExistAccess_Token();
return View();
}
public static Access_token GetAccess_token()
{
string AppUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?";
string AppID = "應用組的CorpID"; //設定 -> 權限管理 -> 系統管理組
string AppSecret = "應用組的Secret"; //設定 -> 權限管理 -> 系統管理組
WebClient webClient = new WebClient();
Byte[] bytes = webClient.DownloadData(
string.Format("{0}corpid={1}&corpsecret={2}", AppUrl, AppID, AppSecret));
string result = Encoding.GetEncoding("utf-8").GetString(bytes);
JObject jObj = JObject.Parse(result);
string token = jObj["access_token"].ToString();
string expires_in = jObj["expires_in"].ToString();
Access_token mode = new Access_token();
mode.access_token = token;
mode.expires_in = expires_in;
return mode;
}
關鍵在於「不要每次都重新請求 token」。微信對 token 的獲取次數有配額限制,因此這裡把 token 與過期時間寫進 XML 檔,每次使用前先比對當前時間。
/// 根據當前日期判斷 Access_Token 是否超期
/// 如果超期則返回新的 Access_Token,否則沿用舊的
public static string IsExistAccess_Token()
{
string Token = string.Empty;
DateTime YouXRQ;
string strPath = "../../weixin/XMLFile.xml";
//string filepath = System.Web.Hosting.HostingEnvironment.MapPath(strPath);
string filepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
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;
}
object text = new {
toparty = "1",
agentid = "2",
msgtype = "text",
text = new { content = "項目名稱:xxx" }
};
string wcr = btnSend(Token, text);
return wcr;
}
這裡用 AppDomain.CurrentDomain.BaseDirectory 組出絕對路徑,比 MapPath 註解掉的那行更可靠,在各種部署方式下都能正確定位檔案。
把要送出的內容序列化成 JSON,POST 到訊息介面即可。
public static string btnSend(string Token, object text)
{
string url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + Token;
WebRequest req = WebRequest.Create(url);
JavaScriptSerializer aa = new JavaScriptSerializer();
string postData = aa.Serialize(text);
byte[] requestBytes = Encoding.UTF8.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.Default);
string backstr = sr.ReadToEnd();
sr.Close();
res.Close();
WeChatReturn WCR = aa.Deserialize<WeChatReturn>(backstr);
return WCR.errmsg;
}
把 token 寫進 XML 檔在多伺服器或高併發環境下會有檔案鎖競爭的問題。改用 MemoryCache 或 Redis,並把 expires_in 直接設為快取存活時間,會乾淨得多:
var token = _cache.Get("wx_token");
if (token == null) {
token = GetAccess_token();
_cache.Set("wx_token", token, TimeSpan.FromSeconds(int.Parse(token.expires_in) - 300));
}
注意這裡刻意減去 300 秒的緩衝——不要等到真的過期才換,否則併發請求會同時拿到無效 token。
範例只回傳了 errmsg,但判斷成功與否要看 errcode(0 才是成功)。常見錯誤如 40001(token 失效)、45009(介面呼叫頻次超限)都應該被記錄下來。
CorpID 與 Secret 應該放在設定檔或環境變數中。Secret 外流等同於把企業號的發言權交出去。