分享方法
通过微信接口获取用户信息主要分为以下几个步骤:
a、获取公众号的access_token
b、通过查询所有用户OPenid接口获取所有用户。
string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token;
c、通过获取用户openid,然后通过openid获取用户数据
d、把用户信息添加到数据库中。
1、参数化查询以及添加用户信息到数据库方法
按 Ctrl+C 复制代码
public void AddToDataBase(UserJson userInfo)
{
using (SqlConnection conn = new SqlConnection(connStrings))
{
conn.Open();
// openid, subscribe, nickname, sex, language, city, province, country, headimgurl, subscribetime, remark="";
string cmdText = @"insert into UserInfo values(@openid,@subscribe,@nickname,@sex,@language,@city,
@province,@country,@headimgurl,@subscribetime,@remark)";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("@openid",userInfo.openid);
cmd.Parameters.AddWithValue("@subscribe",userInfo.subscribe );
cmd.Parameters.AddWithValue("@nickname",userInfo.nickname);
cmd.Parameters.AddWithValue("@sex", userInfo.sex);
cmd.Parameters.AddWithValue("@language",userInfo.language );
cmd.Parameters.AddWithValue("@city", userInfo.city);
cmd.Parameters.AddWithValue("@province",userInfo.province);
cmd.Parameters.AddWithValue("@country", userInfo.country);
cmd.Parameters.AddWithValue("@headimgurl",userInfo.headimgurl);
cmd.Parameters.AddWithValue("@subscribetime",userInfo.subscribe_time);
cmd.Parameters.AddWithValue("@remark", userInfo.remark);
int res = cmd.ExecuteNonQuery();
}
}
按 Ctrl+C 复制代码
2、通过Openid调用微信接口获取用户数据
public void GetUserInfo(string openid) { string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN"; string result = HttpGet(url, ""); // json 反序列化为对象 JavaScriptSerializer serializer = new JavaScriptSerializer(); UserJson UserInfo = serializer.Deserialize<UserJson>(result); //通过这种方法反序列化,不出因为出现特殊字符而出错 AddToDataBase(UserInfo); }
3、获取所有openid
string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token; string openidList = HttpGet(url, ""); List<string> list = new List<string>(); JavaScriptSerializer serializer = new JavaScriptSerializer(); UserListJsonResult result = serializer.Deserialize<UserListJsonResult>(openidList); //通过这种方法,反序列化成功 // UserListJsonResult result = JsonHelper.GetObjFromJson<UserListJsonResult>(openidList);