微信授權(Net Mvc)
專案結構
WeiXinController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using System.Xml;
using System.Net;
using Newtonsoft.Json;
using WeChat2.Models;
namespace WeChat2.Controllers
{
using Senparc.Weixin.MP;
public class WeiXinController : Controller
{
string token = "garfieldzf8";
string appID = "wx3475193134aa161e";
string appsecret = "10c0994def4d52442a2edde4ce1843cf";
[HttpGet]
[ActionName("Index")]
public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
{
if (CheckSignature.Check(signature, timestamp, nonce, token))
{
return Content(echostr);
}
else
{
return Content("err");
}
}
[HttpPost]
[ActionName("Index")]
public ActionResult Get(string signature, string timestamp, string nonce)
{
StreamReader sr = new StreamReader(Request.InputStream, Encoding.UTF8);
XmlDocument doc = new XmlDocument();
doc.Load(sr);
sr.Close();
sr.Dispose();
WxMessage wxMessage = new WxMessage();
wxMessage.ToUserName = doc.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
wxMessage.FromUserName = doc.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
wxMessage.MsgType = doc.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
wxMessage.CreateTime = int.Parse(doc.SelectSingleNode("xml").SelectSingleNode("CreateTime").InnerText);
Log(wxMessage.ToUserName + "," + wxMessage.FromUserName + "," + wxMessage.MsgType);
if (wxMessage.MsgType == "event")
{
wxMessage.EventName = doc.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
Log(wxMessage.EventName);
if (!string.IsNullOrEmpty(wxMessage.EventName) && wxMessage.EventName == "subscribe")
{
string content = "您好,歡迎訪問garfieldzf8測試公眾平臺\n";
content += "<a href='" + Request.Url.Host + Url.Action("OAuthSnsApiBase") + "'>SnsApiBase</a>\n";
content += "<a href='" + Request.Url.Host + Url.Action("OAuthSnsApiUserInfo") + "'>SnsApiUserInfo</a>";
content = SendTextMessage(wxMessage, content);
Log(content);
return Content(content);
}
}
return Content("");
}
private string SendTextMessage(WxMessage wxmessage, string content)
{
string result = string.Format(Message, wxmessage.FromUserName, wxmessage.ToUserName, DateTime.Now.Ticks, content);
return result;
}
/**
* snsapi_base
* **/
public ActionResult OAuthSnsApiBase()
{
string code = Request.QueryString["code"];
try
{
if (!string.IsNullOrEmpty(code))
{
OAuthToken oauthToken = HttpUtility.Get<OAuthToken>(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appID, appsecret, code));
string accesstoken = string.Empty;
AccessToken token = HttpUtility.Get<AccessToken>(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appID, appsecret));
if (token != null && !string.IsNullOrEmpty(token.access_token))
{
accesstoken = token.access_token;
}
if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid))
{
OAuthUserInfo userInfo = HttpUtility.Get<OAuthUserInfo>(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, oauthToken.openid));
if (userInfo != null)
{
Log("獲取到使用者資訊nickName:" + userInfo.nickname);
ViewData["headImage"] = userInfo.headimgurl;
ViewData["openid"] = userInfo.openid;
ViewData["nickName"] = userInfo.nickname;
if (userInfo.sex == 0)
{
ViewData["sex"] = "未知";
}
else if (userInfo.sex == 1)
{
ViewData["sex"] = "男";
}
else
{
ViewData["sex"] = "女";
}
ViewData["province"] = userInfo.province;
ViewData["city"] = userInfo.city;
}
else
{
Log("未獲取到使用者資訊");
}
}
else
{
Log("access_token:" + oauthToken.access_token + ",openid:" + oauthToken.openid);
}
}
else
{
return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123456#wechat_redirect", appID, "http://" + Request.Url.Host + Url.Action("OAuthSnsApiBase")));
}
}
catch (Exception ex)
{
Log(ex.Message);
ViewData["errmsg"] = ex.Message;
}
return View();
}
/**
* snsapi_userinfo
* **/
public ActionResult OAuthSnsApiUserInfo()
{
string code = Request.QueryString["code"];
try
{
if (!string.IsNullOrEmpty(code))
{
OAuthToken oauthToken = HttpUtility.Get<OAuthToken>(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appID, appsecret, code));
if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid) && !string.IsNullOrEmpty(oauthToken.access_token))
{
OAuthUserInfo userInfo = Get<OAuthUserInfo>(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", oauthToken.access_token, oauthToken.openid));
if (userInfo != null)
{
Log("獲取到使用者資訊nickName:" + userInfo.nickname);
ViewData["headImage"] = userInfo.headimgurl;
ViewData["openid"] = userInfo.openid;
ViewData["nickName"] = userInfo.nickname;
if (userInfo.sex == 0)
{
ViewData["sex"] = "未知";
}
else if (userInfo.sex == 1)
{
ViewData["sex"] = "男";
}
else
{
ViewData["sex"] = "女";
}
ViewData["province"] = userInfo.province;
ViewData["city"] = userInfo.city;
}
else
{
Log("未獲取到使用者資訊");
}
}
else
{
Log("access_token:" + oauthToken.access_token + ",openid:" + oauthToken.openid);
}
}
else
{
return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=123456#wechat_redirect", appID, Server.UrlEncode("http://" + Request.Url.Host + Url.Action("OAuthSnsApiUserInfo"))));
}
}
catch (Exception ex)
{
Log(ex.Message);
ViewData["errmsg"] = ex.Message;
}
return View();
}
//被動回覆使用者訊息
public string Message
{
get
{
return @"<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{3}]]></Content>
</xml>";
}
}
private void Log(string text)
{
string str = Server.MapPath("~/Log/") + "log.txt";
FileStream fs = new FileStream(str, FileMode.Append, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(DateTime.Now + " : " + text);
sr.Close();
fs.Close();
}
public T Get<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "get";
request.Timeout = 2000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
Log("result:" + result);
return JsonConvert.DeserializeObject<T>(result);
}
}
public class HttpUtility
{
public static T Get<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "get";
request.Timeout = 2000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
return JsonConvert.DeserializeObject<T>(result);
}
}
}
實體類
OAuthToken.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WeChat2.Models
{
public class OAuthToken
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string refresh_token { get; set; }
public string openid { get; set; }
public string scope { get; set; }
}
public class AccessToken
{
public string access_token { get; set; }
public int expires_in { get; set; }
}
public class OAuthUserInfo
{
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 string privilege { get; set; }
public string unionid { get; set; }
}
}
WxMessage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WeChat2.Models
{
public class WxMessage
{
public string ToUserName { get; set; }
public string FromUserName { get; set; }
public long CreateTime { get; set; }
public string Content { get; set; }
public string MsgType { get; set; }
public string EventName { get; set; }
public string EventKey { get; set; }
}
}
檢視
OAuthSnsApiBase.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>OAuthSnsApiBase</title>
</head>
<body>
<h1>OAuthSnsApiBase</h1>
@if (ViewData["errmsg"] != null)
{
<h1>@ViewData["errmsg"]</h1>
}
else
{
<h2>@ViewData["nickName"]</h2>
<h2>@ViewData["sex"]</h2>
<h2>@ViewData["province"]</h2>
<h2>@ViewData["city"]</h2>
<h2>@ViewData["headImage"]</h2>
}
</body>
</html>
OAuthSnsApiUserInfo.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>OAuthSnsApiUserInfo</title>
</head>
<body>
<h1>OAuthSnsApiUserInfo</h1>
@if (ViewData["errmsg"] != null)
{
<h1>@ViewData["errmsg"]</h1>
}
else
{
<h2>@ViewData["nickName"]</h2>
<h2>@ViewData["sex"]</h2>
<h2>@ViewData["province"]</h2>
<h2>@ViewData["city"]</h2>
<h2>@ViewData["headImage"]</h2>
}
</body>
</html>
相關文章
- C#微信網頁授權登入(NET MVC)C#網頁MVC
- 前端微信授權前端
- 微信網頁授權網頁
- 微信小程式——授權微信小程式
- 微信授權管理功能
- 微信裡的”授權“
- 微信授權登入
- .NET Core企業微信網頁授權登入網頁
- Asp.Net Core 企業微信靜默授權ASP.NET
- ASP.NET Core策略授權和 ABP 授權ASP.NET
- 微信授權註冊或微信登陸 微信授權登陸 基於若依vue 實現Vue
- 微信網頁靜默授權網頁
- vue 微信授權解決方案Vue
- java 微信授權登入配置Java
- 微信授權學習記錄
- 微信小程式授權過程微信小程式
- .Net Core之JWT授權JWT
- 微信網頁授權視訊教程網頁
- 微信 OAuth 授權域名支援兩個OAuth
- 微信小程式的授權登入微信小程式
- [微信開發] 微信網頁授權Java實現網頁Java
- Laravel 微信 Token 配置 與微信網頁授權操作Laravel網頁
- 微信授權和sdk加密演算法加密演算法
- Java微信授權登入小程式介面Java
- 微信公眾號開發 —— 微信網頁授權小記網頁
- 微信開發-微信網頁開發-授權多次回撥網頁
- .NET Core中的鑑權授權正確方式(.NET5)
- 理解ASP.NET Core - 授權(Authorization)ASP.NET
- 微信掃碼支付(Asp.Net MVC)ASP.NETMVC
- ajax 實現微信網頁授權登入網頁
- uni-app 微信小程式授權登入APP微信小程式
- 微信網頁授權登入(c# Webform)網頁C#WebORM
- 微信小程式授權登入最佳實踐微信小程式
- 關於微信公眾號靜默授權和非靜默授權的區別
- #聊聊微信小程式使用者授權登入,無感知登入,強制授權~~~微信小程式
- 微信小程式踩坑日記1——呼叫微信授權視窗微信小程式
- 關於微信小程式使用者拒絕授權後不再彈出授權視窗微信小程式
- 第三方微信登入 | 靜默授權與網頁授權的實現網頁