【微信公众号】验证用户OpenID是否关注某个公众号
1、获取OpenID
#region 获取微信支付的OpenId /// <summary> /// 获取微信支付的OpenId /// </summary> /// <returns></returns> public string GetPayOpenID() { try {
string code = Request.QueryString["code"]; if (string.IsNullOrEmpty(code)) { string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Constant.WX_PAY_APPID + "&redirect_uri=" + HttpUtility.UrlEncode(Request.Url.ToString()) + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect"; } else { string url = "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";
string jsonResult = new System.Net.Http.HttpClient().GetStringAsync(url).Result; JToken jtoken = JToken.Parse(jsonResult); string openid = jtoken.Value<string>("openid"); return openid; } } catch (Exception ex) { } return ""; } #endregion
2、获取Token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=***&secret=***
响应结果:
{ "access_token":"O3PwqnKoiiYmsHeAh8viWLQyhGRrGU6RT9o53pvlmhIBWQnTXeZDSkYNw6YufzIDUspzQguvxtmLXtAWmQd2NmurXKa4N4PsbwG7RvI25pqzSC3-cLl50iqSW5VaZ4xmGXQgAFAJAT", "expires_in":7200 }
3、使用Token和OpenID获取用户信息
https://api.weixin.qq.com/cgi-bin/user/info?access_token=***&openid=***&lang=zh_CN
响应结果:
{ "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":[ ] }
根据接口返回的subscribe字段判断是否关注公众号
1=关注;0=未关注;
subscribe:用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
没有关注的情况下,显示这个。。。
今天又遇到这个问题了
1=关注;0=未关注;
subscribe:用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
没有关注的情况下,显示这个。。。
今天又遇到这个问题了
{"subscribe":0,"openid":"oeQDZtzPrIYwOPXdzgKmd0gYPG44","unionid":"oGCG8tzd2NwsOYAeWAZMwV9rMmPU","tagid_list":[]}