微信公眾號引入「標籤」功能取代傳統「分組」,支援多維度標記粉絲屬性,單一公眾號最多建立 100 個標籤,每位使用者最多可打 3 個標籤。本文示範如何以 C# 封裝標籤管理相關 API,涵蓋標籤 CRUD、粉絲清單查詢、批量打標/取消標籤、查詢使用者身上標籤等核心功能,程式碼結構清晰,可直接套用於實際專案。
採用介面導向設計,便於單元測試與多實作切換(如正式環境/模擬環境)。
public interface ITagApi
{
/// 建立標籤(最多 100 個,名稱 30 字內)
TagJson CreateTag(string accessToken, string name);
/// 取得所有標籤清單(含粉絲計數)
List<TagCountJson> GetTagList(string accessToken);
/// 編輯標籤名稱
CommonResult UpdateTag(string accessToken, int id, string name);
/// 刪除標籤
CommonResult DeleteTag(string accessToken, int id);
/// 取得標籤下的粉絲 OpenID 清單(分頁)
GetTagResult GetTag(string accessToken, int id, string nextOpenId = null);
/// 批量為使用者打標籤(單次最多 50 個 OpenID,每用戶最多 3 標籤)
CommonResult BatchTagging(string accessToken, int tagId, List<string> openIdList);
/// 批量取消使用者標籤
CommonResult BatchUntagging(string accessToken, int tagId, List<string> openIdList);
/// 查詢使用者身上的標籤 ID 清單
List<int> GetIdList(string accessToken, string openId);
}
/// 標籤基本資訊
public class TagJson
{
public int Id { get; set; } // 微信分配的標籤 ID
public string Name { get; set; } // 標籤名稱 (UTF-8)
}
/// 含粉絲計數的標籤(繼承 TagJson)
public class TagCountJson : TagJson
{
public int Count { get; set; } // 此標籤下粉絲數
}
/// 建立標籤回傳結果
public class TagCreateResult
{
public TagJson Tag { get; set; }
}
/// 取得標籤粉絲清單結果
public class GetTagResult
{
public int Count { get; set; }
public List<string> Data { get; set; } // OpenID 清單
public string NextOpenId { get; set; }
}
public TagJson CreateTag(string accessToken, string name)
{
var url = $"https://api.weixin.qq.com/cgi-bin/tags/create?access_token={accessToken}";
var payload = new { tag = new { name } };
var json = payload.ToJson(); // 需自行實作或使用 Newtonsoft.Json
var result = JsonHelper<TagCreateResult>.ConvertJson(url, json); // 封裝的 HTTP POST + 反序列化
return result?.Tag;
}
關鍵點說明:
access_token 需定期刷新快取。{"tag":{"id":134,"name":"廣東"}},直接對應 TagCreateResult。errcode != 0 時拋出自訂例外 WeChatApiException,攜帶 errcode、errmsg。| 介面 | HTTP 方法 | 關鍵參數 | 注意事項 |
|---|---|---|---|
| GetTagList | GET | access_token | 回傳 tags 陣列,每項含 id、name、count |
| UpdateTag | POST | access_token, id, name | 名稱長度限制 30 字,不可重複 |
| DeleteTag | POST | access_token, id | 刪除後該標籤下粉絲關聯自動移除 |
| GetTag | POST | access_token, id, next_openid | 分頁查詢,每次最多 10000 個 OpenID |
| BatchTagging | POST | access_token, tagid, openid_list | 單次最多 50 個 OpenID,頻率限制 100 次/分鐘 |
| BatchUntagging | POST | access_token, tagid, openid_list | 參數結構同打標籤 |
| GetIdList | POST | access_token, openid | 回傳標籤 ID 整數陣列 |
MemoryCache 或 IDistributedCache)集中管理,避免重複請求導致頻率限制。Polly 實作指數退避重試(網路錯誤)、熔斷(持續 5xx 錯誤),提升穩定性。ITagApi 撰寫 Mock 測試,模擬各種微信回傳碼(0 成功、40001 token 失效、45058 頻率超限等)。JsonProperty 忽略未知屬性,避免反序列化失敗。WeChat.Sdk/
├── Abstractions/
│ └── ITagApi.cs
├── Models/
│ ├── TagJson.cs
│ ├── TagCountJson.cs
│ ├── TagCreateResult.cs
│ └── GetTagResult.cs
├── Impl/
│ └── TagApiClient.cs // 實作 ITagApi,內含 HttpClient 封裝
├── Exceptions/
│ └── WeChatApiException.cs
└── Extensions/
└── ServiceCollectionExtensions.cs // DI 註冊擴充方法
遵循介面隔離、單一職責、依賴反轉原則,即可建構出可維護、可測試、可擴充的微信標籤管理模組。