參考文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432json
1、安裝Senparc.Weixin NuGet包。小程序
2、添加引用api
using Senparc.CO2NET.Extensions; using Senparc.Weixin.MP.Entities.Request;
3、微信公衆號-開發-基本配置 數組
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一致。"); } }
4、獲取公衆號相關信息微信
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"];
5、獲取tokenapp
public string GetAccessToken() { return Senparc.Weixin.MP.Containers.AccessTokenContainer.GetAccessToken(AppId); }
6、自定義建立菜單post
利用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)); }
7、調用受權頁面獲取用戶微信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); }
8、根據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(); }
9、根據openid獲取用戶信息
WXModel:
參數 | 描述 |
---|---|
openid | 用戶的惟一標識 |
nickname | 用戶暱稱 |
sex | 用戶的性別,值爲1時是男性,值爲2時是女性,值爲0時是未知 |
province | 用戶我的資料填寫的省份 |
city | 普通用戶我的資料填寫的城市 |
country | 國家,如中國爲CN |
headimgurl | 用戶頭像,最後一個數值表明正方形頭像大小(有0、4六、6四、9六、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; }
10、微網站公用獲取用戶信息方法
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; }
11、須要獲取用戶的地方
string urlpath = Request.Url.AbsoluteUri; tb_user user = GetUser(urlpath);
注:以上代碼屬我的整理,用於交流學習,非原創。如涉及侵權,請聯繫我,我當即處理。(QQ/微信:742010299 暱稱:同心同德)