参考文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432
一、安装Senparc.Weixin NuGet包。
二、添加引用
using Senparc.CO2NET.Extensions;
using Senparc.Weixin.MP.Entities.Request;
三、微信公众号-开发-基本配置
Global.asax全局配置 Application_Start
//微信配置开始
var isGLobalDebug = true;//设置全局 Debug 状态
var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug);
var register = RegisterService.Start(senparcSetting).UseSenparcGlobal();//CO2NET全局注册,必须!
var isWeixinDebug = true;//设置微信 Debug 状态
var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug);
register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);微信全局注册,必须!
//注册公众号
AccessTokenContainer.Register(
System.Configuration.ConfigurationManager.AppSettings["WeixinAppId"],
System.Configuration.ConfigurationManager.AppSettings["WeixinAppSecret"],
"公众号");
//注册小程序(完美兼容)
AccessTokenContainer.Register(
System.Configuration.ConfigurationManager.AppSettings["WxOpenAppId"],
System.Configuration.ConfigurationManager.AppSettings["WxOpenAppSecret"],
"小程序");
//微信配置结束
/// <summary>
/// 微信后台验证地址(使用Get),微信后台的“接口配置信息”的Url填写如:http://sdk.weixin.senparc.com/weixin
/// </summary>
[HttpGet]
[ActionName("Index")]
public ActionResult Get(PostModel postModel, string echostr)
{
if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
{
return Content(echostr); //返回随机字符串则表示验证通过
}
else
{
return Content("failed:" + postModel.Signature + "," + MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
"如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
}
}
四、获取公众号相关信息
public static readonly string Token = WebConfigurationManager.AppSettings["WeixinToken"];//与微信公众账号后台的Token设置保持一致,区分大小写。
public static readonly string EncodingAESKey = WebConfigurationManager.AppSettings["WeixinEncodingAESKey"];//与微信公众账号后台的EncodingAESKey设置保持一致,区分大小写。
public static readonly string AppId = WebConfigurationManager.AppSettings["WeixinAppId"];//与微信公众账号后台的AppId设置保持一致,区分大小写。
public static readonly string WeixinAppSecret = WebConfigurationManager.AppSettings["WeixinAppSecret"];
五、获取token
public string GetAccessToken()
{
return Senparc.Weixin.MP.Containers.AccessTokenContainer.GetAccessToken(AppId);
}
六、自定义创建菜单
利用json更新菜单
[HttpPost]
public string CreateMenuFromJson(string token, string fullJson)
{
//TODO:根据"conditionalmenu"判断自定义菜单
var apiName = "使用JSON更新";
try
{
GetMenuResultFull resultFull = Newtonsoft.Json.JsonConvert.DeserializeObject<GetMenuResultFull>(fullJson);
//重新整理按钮信息
WxJsonResult result = null;
IButtonGroupBase buttonGroup = null;
buttonGroup = CommonAPIs.CommonApi.GetMenuFromJsonResult(resultFull, new ButtonGroup()).menu;
result = CommonAPIs.CommonApi.CreateMenu(token, buttonGroup);
var json = new
{
Success = result.errmsg == "ok",
Message = "菜单更新成功。" + apiName
};
//return Json(json);
return "菜单更新成功。" + apiName;
}
catch (Exception ex)
{
var json = new { Success = false, Message = string.Format("更新失败:{0}。{1}", ex.Message, apiName) };
//return Json(json);
return string.Format("更新失败:{0}。{1}", ex.Message, apiName);
}
}
json格式实例(一级菜单最多三个,二级菜单最多五个)
{
"menu": {
"button": [
{
"name": "一级菜单",
"sub_button": [
{
"type": "view",
"name": "二级菜单",
"url": ""
}
]
}
]
}
}
读取json
public string GetMenuJson()
{
StreamReader sr = new StreamReader(System.Web.HttpRuntime.AppDomainAppPath + "\\menu.json", Encoding.Default);
string line;
string jsonobj = "";
while ((line = sr.ReadLine()) != null)
{
jsonobj = jsonobj + line.ToString();
}
return jsonobj;
}
创建菜单
public ActionResult CreateMenu()
{
string MenuJson = GetMenuJson();
string token = GetAccessToken();
return Content(CreateMenuFromJson(token, MenuJson));
}
七、调用授权页面获取用户微信code
urlpath:回调url,此url对应域名需要配置在微信公众号-接口权限-网页服务-网页授权-网页授权获取用户基本信息
public void GetWeixinCode(string urlpath)
{
string state = Guid.NewGuid().ToString("N");
string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect", AppId, urlpath);
Response.Redirect(url);
}
八、根据code获取用户openid
post访问地址
public static string WebRequestPostOrGet(string sUrl, string sParam)
{
byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);
Uri uriurl = new Uri(sUrl);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);
req.Method = "Post";
req.Timeout = 120 * 1000;
req.ContentType = "application/x-www-form-urlencoded;";
req.ContentLength = bt.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bt, 0, bt.Length);
reqStream.Flush();
}
try
{
using (WebResponse res = req.GetResponse())
{
Stream resStream = res.GetResponseStream();
StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);
string resLine;
System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();
while ((resLine = resStreamReader.ReadLine()) != null)
{
resStringBuilder.Append(resLine + System.Environment.NewLine);
}
resStream.Close();
resStreamReader.Close();
return resStringBuilder.ToString();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
根据code获取openid
/// <summary> /// 根据code获取用户openid /// </summary> /// <param name="Code"></param> /// <param name="access_token"></param> /// <returns></returns> public string GetOpenidByCode(string Code, out string access_token) { string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppId, WeixinAppSecret, Code); string ReText = WebRequestPostOrGet(url, "");//post/get方法获取信息 Newtonsoft.Json.Linq.JObject DicText = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(ReText); access_token = ""; if (DicText.ContainsKey("access_token")) access_token = DicText["access_token"].ToString(); if (!DicText.ContainsKey("openid")) return ""; return DicText["openid"].ToString(); }
九、根据openid获取用户信息
WXModel:
参数 | 描述 |
---|---|
openid | 用户的唯一标识 |
nickname | 用户昵称 |
sex | 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 |
province | 用户个人资料填写的省份 |
city | 普通用户个人资料填写的城市 |
country | 国家,如中国为CN |
headimgurl | 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。 |
privilege | 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom) |
unionid | 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。 |
public class WXModel
{
public string openid { get; set; }
public string nickname { get; set; }
public int sex { get; set; }
public string province { get; set; }
public string city { get; set; }
public string country { get; set; }
public string headimgurl { get; set; }
}
获取用户信息
public WXModel GetUserInfoByCode(string code)
{
string access_token = "";
string openid = GetOpenidByCode(code, out access_token);
string userinfo = WebRequestPostOrGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN", "");
WXModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<WXModel>(userinfo);
return model;
}
十、微网站公用获取用户信息方法
public WXModel GetUser(string urlpath) { WXModel model = null; var code = Request.Params["code"]; urlpath = urlpath.UrlEncode(); if (code == null || code == "") { GetWeixinCode(urlpath); } else { model = GetUserInfoByCode(code); } return model; }
十一、需要获取用户的地方
string urlpath = Request.Url.AbsoluteUri;
tb_user user = GetUser(urlpath);
注:以上代码属个人整理,用于交流学习,非原创。如涉及侵权,请联系我,我立即处理。(QQ/微信:742010299 昵称:同心同德)