Retrieve OpenID via OAuth2 Authorization
To determine whether a user has subscribed to a specific WeChat official account, the first step is obtaining their OpenID. This can be acheived using WeChat's OAuth2 authorization flow with minimal scope (snsapi_base), which does not require explicit user consent for basic information.
#region Obtain WeChat Payment OpenID
/// <summary>
/// Retrieves the user's OpenID through OAuth2 authorization.
/// </summary>
/// <returns>User's OpenID or empty string on failure</returns>
public string GetPayOpenID()
{
try
{
string code = Request.QueryString["code"];
if (string.IsNullOrEmpty(code))
{
// Redirect to WeChat OAuth2 authorization page
string redirectUrl = Request.Url.ToString();
string authorizationUrl =
"https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + Constant.WX_PAY_APPID +
"&redirect_uri=" + HttpUtility.UrlEncode(redirectUrl) +
"&response_type=code" +
"&scope=snsapi_base" +
"&state=123#wechat_redirect";
Response.Redirect(authorizationUrl);
return null;
}
else
{
// Exchange code for access token and retrieve OpenID
string accessTokenUrl =
"https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + Constant.WX_PAY_APPID +
"&secret=" + Constant.WX_PAY_APPSECRET +
"&code=" + code +
"&grant_type=authorization_code";
var httpClient = new System.Net.Http.HttpClient();
string jsonResponse = httpClient.GetStringAsync(accessTokenUrl).Result;
JObject tokenData = JObject.Parse(jsonResponse);
string openId = tokenData["openid"]?.ToString();
return openId;
}
}
catch (Exception ex)
{
// Log exception as needed
return string.Empty;
}
}
#endregion
Acquire Access Token for API Calls
Prior to querying user subscription status, your server must obtain a valid access_token by calling the client credential endpoint. This token grants temporary access to WeChat's backend APIs.
GET https://api.weixin.qq.com/cgi-bin/token?
grant_type=client_credential&appid=YOUR_APPID&secret=YOUR_SECRET
Successful response:
{
"access_token": "O3PwqnKoiiYmsHeAh8viWLQyhGRrGU6RT9o53pvlmhIBWQnTXeZDSkYNw6YufzIDUspzQguvxtmLXtAWmQd2NmurXKa4N4PsbwG7RvI25pqzSC3-cLl50iqSW5VaZ4xmGXQgAFAJAT",
"expires_in": 7200
}
Query User Subscripsion Status Using OpenID
With both the access_token and openid, you can now call the user info API to check subscription status.
GET https://api.weixin.qq.com/cgi-bin/user/info?
access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
Sample resposne when user is subscribed:
{
"subscribe": 1,
"openid": "oeQDZt0n4VCZ70wy***",
"nickname": "背上***旅行",
"sex": 1,
"language": "zh_CN",
"city": "昌平",
"province": "北京",
"country": "中国",
"headimgurl": "http://wx.qlogo.cn/mmopen/kBwGJuwqK9**********************ibVUEpgFE90LH3b3uj7AYRjZP/0",
"subscribe_time": 1474964999,
"unionid": "oGCG8t5**********jPQTPw",
"remark": "",
"groupid": 0,
"tagid_list": []
}
Response when user is not subscribed:
{
"subscribe": 0,
"openid": "oeQDZtzPrIYwOPXdzgKmd0gYPG44",
"unionid": "oGCG8tzd2NwsOYAeWAZMwV9rMmPU",
"tagid_list": []
}
The key field is subscribe:
- 1 indicates the user follows the official account.
- 0 means they do not subscribe, and only limited data (like openid and unionid) will be returned.