微信授权(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);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
实体类
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; }
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
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; }
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
视图
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>
微信授权(Net Mvc)的更多相关文章
- 【第二十一篇】手C# MVC 微信授权登录 OAuth2.0授权登录
首先一定要熟读,最起码过一遍微信开发者文档 微信开发者文档 文档写的很清楚 授权登录四步走 在正文开始前,我得讲清楚一个事情 敲黑板,划重点:微信一共有两个 access_token 一个是7200就 ...
- 解决微信授权回调页面域名只能设置一个的问题 [php]
最终的解决方案是:https://github.com/liuyunzhuge/php_weixin_proxy,详细的介绍请往下阅读. 在做项目集成微信登录以及微信支付的时候,都需要进行用户授权.这 ...
- url带#号,微信授权,微信分享那些坑
微信授权的方法是,在项目里面配置拦截器(此处可以参考各个框架的拦截器)没有拦截器也可以,反正意思就是跳转到项目里的时候判断微信环境 如果是微信环境, 判断微信环境的方法是 var ua = windo ...
- 微信公众平台开发——微信授权登录(OAuth2.0)
1.OAuth2.0简介 OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用. 允许用户 ...
- 微信授权步骤与详解 -- c#篇
微信授权步骤与详解 -- c#篇 注:这里不涉及界面操作,只介绍代码操作. 1.基本原理如下: 从图上所知,第一步用户访问我们的网页,第二步我们后台跳转到微信授权页面,第三步用户点击授权,第四步微信重 ...
- [转] Android:微信授权登录与微信分享全解析
https://wohugb.gitbooks.io/wechat/content/qrconnent/refresh_token.html http://blog.csdn.net/xiong_it ...
- html 微信开发——微信授权
微信JS-SDK说明文档 链接地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html 微信web开发:http: ...
- 微信授权登陆接入第三方App(步骤总结)Android
微信授权登陆接入第三方App(步骤总结)Android Android App实现第三方微信登录
- 微信授权登录(PHP)
微信授权登录(PHP) 微信授权 OAuth2.0授权 微信网页授权 主要是在项目中遇到网页授权登录这个需求,就对此做些总结记录. OAuth2.0授权 OAuth是一个开放协议,允许用户让第三方应用 ...
随机推荐
- 获取 ip ( 第三方接口 )
搜狐IP地址查询接口(默认GBK):http://pv.sohu.com/cityjson 搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/cityjson?ie=utf-8 ...
- windows版 Java调用人脸识别离线sdk
最近因工作需求在java-web服务中调用人脸识别离线sdk,主要通过JNA及JNI技术,但均未调试通过,JNA调用时出现以下异常,一直未解决,求大佬指点,导常信息如下: in BaiduFaceAp ...
- Bagging和Boosting的区别(面试准备)
Baggging 和Boosting都是模型融合的方法,可以将弱分类器融合之后形成一个强分类器,而且融合之后的效果会比最好的弱分类器更好. Bagging: 先介绍Bagging方法: Bagging ...
- python 自动化测试Jenkins 持续集成
一直在做 python 自动化测试,但是脚本的执行之前是运维来维护的,通过 saltstack, 自己并未做过多的研究,后续可以研究一下 saltstack. 今天先研究一下使用 github 管理项 ...
- 第 3 章 镜像 - 021 - Docker 镜像小结
镜像小结 镜像的常用操作子命令: images 显示镜像列表 history 显示镜像构建历史 commit 从容器创建新镜像 build 从 Dockerfile 构建镜像 ...
- spring集成JMS访问ActiveMQ
首先我们搭建一个spring-mvc项目,项目可以参考:spring-mvc 学习笔记 步骤: 在pom.xml中加上需要的包 修改web.xml,增加IOC容器 spring配置文件applicat ...
- boke练习: spring boot: security post数据时,要么关闭crst,要么添加隐藏域
spring boot: security post数据时,要么关闭crst,要么添加隐藏域 http.csrf().disable(); 或者: <input name="${_cs ...
- Django中CBV及其源码解释
FBV(function base views) 就是在视图里使用函数处理请求. CBV(class base views) 就是在视图里使用类处理请求. Python是一个面向对象的编程语言,如果只 ...
- 2015-2016 ACM-ICPC Northeastern European Regional Contest (NEERC 15)C - Cactus Jubilee
题意:给一颗仙人掌,要求移动一条边,不能放在原处,移动之后还是一颗仙人掌的方案数(仙人掌:无向图,每条边只在一个环中),等价于先删除一条边,然后加一条边 题解:对于一颗仙人掌,分成两种边,1:环边:环 ...
- 【PowerDesigner】【10】绘制类图
前言:我感觉我也是一知半解,参考博客的内容会比我的文章更有帮助 用途:描述项目中类与类的关系(即描述java文件) 正文: 1,新建oomFile→New Model→Model types→Obje ...