微信开放平台---网站应用开发---微信登录功能 简介

news/2024/5/9 8:58:09/文章来源:https://blog.csdn.net/weixin_30268921/article/details/94892176

1 微信开放平台:https://open.weixin.qq.com/

2 开通流程:

3 微信官方教程:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN

4 效果展示:

点击微信图标跳转到https://open.weixin.qq.com/connect/.....页面

使用个人微信扫描后,点击“确认登录”

这时候,pc页面上就会有变化:

然后页面就直接跳转到1好店的首页,并且将微信用户的信息传过去了。

 

5 通过官方提供的文档,我们可以看出一共分4个步骤

第一步:请求CODE
第二步:通过code获取access_token
第三步:通过access_token调用接口
第4步:获取用户个人信息(UnionID机制)

我们写一个api代码:  

public class weixin_helper{public weixin_helper(){}/// <summary>/// 根据AppID和AppSecret获得access token(默认过期时间为2小时)/// </summary>/// <returns>Dictionary</returns>public static Dictionary<string, object> get_access_token(){//获得配置信息oauth_config config = oauth_helper.get_config(2);string send_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +config.oauth_app_id + "&secret=" + config.oauth_app_key + "";//发送并接受返回值string result = Utils.HttpGet(send_url);if (result.Contains("errmsg")){return null;}try{Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);return dic;}catch{return null;}} /// <summary>/// 取得临时的Access Token(默认过期时间为2小时)/// </summary>/// <param name="code">临时Authorization Code</param>/// <param name="state">防止CSRF攻击,成功授权后回调时会原样带回</param>/// <returns>Dictionary</returns>public static Dictionary<string, object> get_access_token(string code, string state){//获得配置信息oauth_config config = oauth_helper.get_config(2);string send_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +config.oauth_app_id + "&secret=" + config.oauth_app_key + "&code="+code+"&grant_type=authorization_code";//发送并接受返回值string result = Utils.HttpGet(send_url);if (result.Contains("errmsg")){return null;}try{Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);return dic;}catch{return null;}}/// <summary>/// 根据access_token判断access_token是否过期/// </summary>/// <param name="access_token"></param>/// <returns>true表示未失效</returns>public static bool check_access_token(string access_token){//获得配置信息oauth_config config = oauth_helper.get_config(2);string send_url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + config.oauth_app_id;//发送并接受返回值string result = Utils.HttpGet(send_url);try{Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);if (dic.ContainsKey("errmsg")){if (dic["errmsg"].ToString()=="ok"){return true;}else{return false;}}return false;}catch{return false;}}/// <summary>/// 若fresh_token已过期则根据refresh_token取得新的refresh_token/// </summary>/// <param name="refresh_token">refresh_token</param>/// <returns>Dictionary</returns>public static Dictionary<string, object> get_refresh_token(string refresh_token){//获得配置信息oauth_config config = oauth_helper.get_config(2);string send_url ="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" +config.oauth_app_id + "&grant_type=refresh_token&refresh_token=" + refresh_token;//发送并接受返回值string result = Utils.HttpGet(send_url);if (result.Contains("errmsg")){return null;}try{Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);return dic;}catch{return null;}}/// <summary>/// 获取登录用户自己的基本资料/// </summary>/// <param name="access_token">临时的Access Token</param>/// <param name="open_id">用户openid</param>/// <returns>Dictionary</returns>public static Dictionary<string, object> get_user_info(string access_token, string open_id){//获得配置信息oauth_config config = oauth_helper.get_config(2);//发送并接受返回值   string send_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+open_id;//发送并接受返回值string result = Utils.HttpGet(send_url);if (result.Contains("errmsg")){return null;}//反序列化JSONDictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);return dic;}}

 

控制器的核心代码:

#region 微信登录/// <summary>/// 微信登录/// </summary>public ActionResult WeChat(){//获得配置信息oauth_config config = oauth_helper.get_config(2); //主键idif (config == null){return Content("出错了,您尚未配置微信相关的API信息!");}string state = Guid.NewGuid().ToString().Replace("-", "");Session["oauth_state"] = state;string send_url ="https://open.weixin.qq.com/connect/qrconnect?appid=" + config.oauth_app_id +"&redirect_uri=" + Utils.UrlEncode(config.return_uri.ToLower()) +"&response_type=code&scope=snsapi_login&state=" + state +"#wechat_redirect";//开始发送return Redirect(send_url); //跳转到微信自己 指定的关联登陆页面
        }/// <summary>/// 微信登录返回action/// </summary>public ActionResult WeChatReturnUrl(string state, string code){//取得返回参数string access_token = string.Empty;string expires_in = string.Empty;string client_id = string.Empty;string openid = string.Empty;string refresh_token = string.Empty;if (Session["oauth_state"] == null || Session["oauth_state"].ToString() == "" ||state != Session["oauth_state"].ToString() || string.IsNullOrEmpty(code))//若返回参数中未包含code或者state没有通过验证则提示出错
            {return Content("出错啦,state未初始化!");}//第一步:通过code来获取Access Token以及openidDictionary<string, object> dic1 = weixin_helper.get_access_token(code, state);if (dic1 == null || !dic1.ContainsKey("access_token")){return Content("错误代码:,无法获取Access Token,请检查App Key是否正确!");}if (dic1 == null || !dic1.ContainsKey("openid")){if (dic1.ContainsKey("errmsg")){return Content("errcode:" + dic1["errcode"] + ",errmsg:" + dic1["errmsg"]);}else{return Content("出错啦,无法获取用户授权Openid!");}}access_token = dic1["access_token"].ToString();//获取access_tokenexpires_in = dic1["expires_in"].ToString();//获取过期时间refresh_token = dic1["refresh_token"].ToString();//获取用于重新刷新access_token的凭证openid = dic1["openid"].ToString();//用户唯一标示openid//储存获取数据用到的信息Session["oauth_name"] = "webchat";Session["oauth_access_token"] = access_token;Session["oauth_openid"] = openid;Session["oauth_refresh_token"] = refresh_token;#region todo 将获取到的用户信息保存到数据库中#endregion//第二步:通过Access Token以及openid来获取用户的基本信息//Dictionary<string, object> dic2 = weixin_helper.get_user_info(access_token,openid);//第三步:跳转到指定页面return Content(WeChatResultJson());}/// <summary>/// 微信登录返回action, 处理用户信息/// </summary>public string WeChatResultJson(){string oauth_access_token = string.Empty;string oauth_openid = string.Empty;string oauth_name = string.Empty;string oauth_refresh_token = string.Empty;if (Session["oauth_name"] == null || Session["oauth_access_token"] == null ||Session["oauth_openid"] == null){return "{\"ret\":\"1\", \"msg\":\"出错啦,Access Token已过期或不存在!\"}";}oauth_name = Session["oauth_name"].ToString();oauth_access_token = Session["oauth_access_token"].ToString();oauth_openid = Session["oauth_openid"].ToString();oauth_refresh_token = Session["oauth_refresh_token"].ToString();if (!weixin_helper.check_access_token(oauth_access_token)) //调用access_token前需判断是否过期
            {Dictionary<string, object> dic1 = weixin_helper.get_refresh_token(oauth_refresh_token);//如果已过期则重新换取新的access_tokenif (dic1 == null || !dic1.ContainsKey("access_token")){return "{\"openid\":\"0\", \"msg\":\"出错啦,无法获取access_token!\"}";}oauth_access_token = dic1["access_token"].ToString();}Dictionary<string, object> dic = weixin_helper.get_user_info(oauth_access_token, oauth_openid);if (dic == null){return "{\"openid\":\"0\", \"msg\":\"出错啦,无法获取授权用户信息!\"}";}try{StringBuilder str = new StringBuilder();str.Append("{");str.Append("\"openid\": \"" + dic["openid"].ToString() + "\", ");str.Append("\"nickname\": \"" + dic["nickname"].ToString() + "\", ");str.Append("\"sex\": \"" + dic["sex"].ToString() + "\", ");str.Append("\"province\": \"" + dic["province"].ToString() + "\", ");str.Append("\"city\": \"" + dic["city"].ToString() + "\", ");str.Append("\"country\": \"" + dic["country"].ToString() + "\", ");str.Append("\"headimgurl\": \"" + dic["headimgurl"].ToString() + "\", ");str.Append("\"privilege\": \"" + dic["privilege"].ToString() + "\", ");str.Append("\"unionid\": \"" + dic["unionid"].ToString() + "\"");str.Append("\"oauth_name\": \"" + oauth_name + "\"");str.Append("\"oauth_access_token\": \"" + oauth_access_token + "\"");str.Append("\"oauth_openid\": \"" + oauth_openid + "\"");str.Append("}");return str.ToString();}catch{return "{\"ret\":\"0\", \"msg\":\"出错啦,无法获取授权用户信息!\"}";}}#endregion

 

核心代码已经写好了。

这里要感谢小亚同学辛苦写的代码。我直接拿过来使用了。

面对新的知识和技能,我们首先要仔细看官方的说明,再理清楚思路,一步一步跟着开发就行了。

小亚同学是去年刚毕业,也能把这些代码写的很好,难能可贵。

 

转载于:https://www.cnblogs.com/puzi0315/p/4571790.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_851026.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

抓取某一个网站整站的记录 【记录】

经常由于某些原因我们需要爬取某一个网站或者直接复制某一个站点&#xff0c;到网上找了很多工具进行测试&#xff0c;试了很多各有各的问题&#xff0c;最终选择了Teleport Ultra&#xff0c;用起来效果很好&#xff1b;具体的操作手册等东西就不在这里说了&#xff0c;网上搜…

谈谈个人网站的建立(三)—— 定时任务

欢迎访问我的网站http://www.wenzhihuai.com/ 。谢谢啊&#xff0c;如果可以&#xff0c;希望能在GitHub上给个star&#xff0c;GitHub地址https://github.com/Zephery/newblog 。 Quartz 先看一下Quartz的架构图&#xff1a;一.特点&#xff1a; 强大的调度功能&#xff0c;例…

同步、异步方式对SEO搜索引擎优化的影响

本人昨天去面试了&#xff0c;面试官问了这样一个问题“你知道SEO不&#xff1f;同步、异步对SEO有什么影响&#xff1f;”&#xff0c;我当时就懵了&#xff0c;这几个名词SEO、同步、异步我都知道&#xff0c;但是。SEO和同步异步有什么关系呢&#xff1f;面试官人很nice&…

记录使用scrapy爬取新闻网站最新新闻存入MySQL数据库,每天定时爬取自动更新

爬取每天更新的新闻&#xff0c;使用scrapy框架&#xff0c;Python2.7&#xff0c;存入MySQL数据库&#xff0c;将每次的爬虫日志和爬取过程中的bug信息存为log文件下。定义bat批处理文件&#xff0c;添加到计划任务程序中&#xff0c;自动爬取。 额… 1.在items文件中&#x…

6个线上视频音频转换网站

1.Zamzar Zamzar是一项免费的线上转换格式网站&#xff0c;把歌曲、图档、影像和文件转变成不同的格式。其服务特点是高品质的文件格式转换。基本的免费服务&#xff0c;可以让您转换的文件大小为100MB 。如果想拥有更多功能的服务&#xff0c;你可以注册成为基础会员&#xff…

四年大学下那些让我欲罢不能的网站

在本科学习期间&#xff0c;通过Google/百度搜索接触了各种各样的学习网站&#xff0c;收益匪浅&#xff0c;现在来分享一下吧 分为三种类型&#xff0c;“课程网站”&#xff0c;“编程网站”&#xff0c;“社区网站”&#xff0c;贵精不贵多&#xff0c;每种分享几个 课程网站…

Github Pages + jekyll 全面介绍极简搭建个人网站和博客

本文将会全面介绍一下如何使用Github Pages jekyll搭建个人站点&#xff0c;所谓极简的意思就是不用使用git和本地构建jekll服务&#xff0c;直接在Github网站上编辑设置即可&#xff0c;但会涉及到jekll的一些配置和编程控制。可以参看我的网站模板&#xff1a;https://scott…

css可以对网页干什么,css对网页的优势-专业SEO技术教程(33)

css对网页的优势-专业SEO技术教程(33)采用css布局相对于传统的table网页布局的显著优势1.表现和内容相分离将设计部分剥离出来的放在一个独立样式文件中&#xff0c;HTML文件中只存放文本信息。这样的页面对搜索引擎更加友好。2.提高页面浏览速度对于同一个页面视觉效果&#x…

【转载】IIS网站如何同时解析带www和不带www的域名

针对公网上线的网站系统&#xff0c;很多网站的域名会同时含有带www和不带www的域名解析记录&#xff0c;如果需要同时解析带www和不带www的域名信息&#xff0c;则需要在相应的域名解析平台(如阿里云域名解析平台、腾讯云域名解析平台)设置不带www的主域名以及带www的域名解析…

搜索引擎优化:常用的SEO六个指标

在做网站推广过程中&#xff0c;搜索引擎优化是一个重要点&#xff0c;绝大部分行业来自自然搜索的流量都是非常大的&#xff0c;正因为如此&#xff0c;一般企业隔一段时间就对网站自然搜索的情况作一个KPI考核&#xff0c;而这些重点指标不外乎&#xff1a;网页的收录数量、网…

阿里云上发布自己的网站的方法

在阿里云上发布自己的网站的方法&#xff1a; 一、在阿里云上发布自己的网站的方法&#xff1a; 进入我的电脑&#xff0c;在头部输入ftp&#xff1a;//60.205.48.122&#xff08;IP地址为自己注册的阿里云账号上的IP地址&#xff09; 进入以后登录自己的账号 用户名&#x…

java使用HttpURLConnection检索网站时403错误处理方式

java使用HttpURLConnection检索网站时403错误处理方式: 我们通过代码方式访问网站时会报错&#xff1a; 此种情况分2中类型&#xff0c; 1.需要登录才可以访问&#xff1b; 2.需要设置User-Agent来欺骗服务器。 connection.setRequestProperty("User-Agent", &qu…

解决某些网站,图片不能下载

如下图&#xff0c;右键图片&#xff0c;没有保存图片的选项 按下F12 拷贝src中的地址&#xff0c;输入到浏览器&#xff0c;这时候就可以保存图片了

给duckling网站加上cnzz网站统计信息

第一&#xff0c;注册cnzz帐号&#xff0c;网址http://www.cnzz.com/ 第二&#xff0c;登录帐号&#xff0c;获取代码&#xff1b; 第三&#xff0c;根据自己的需要&#xff0c;将代码加入网站的公共页面&#xff0c;比如说head、foot、version页面都可以。 第四&#xff0c…

网站压力测试工具Jmeter安装与使用

系统是Windows XP 配置此工具前&#xff0c;需要先在机器上安装jdk 如下是在jdk1.7的基础上配置的&#xff1b; 安装步骤如下&#xff1a; 第一步&#xff1a;解压apache-jmeter-2.8.zip文件至c盘&#xff0c;本文解压至C:\jmeter2.8目录下。 第二步&#xff1a;桌面上选择“我…

十大抢手的网站压力测试工具

原文链接&#xff1a;http://blog.163.com/weiwenjuan_bj/blog/static/1403503362010621111052355/ 两天&#xff0c;jnj在本站发布了《如何在低速率网络中测试 Web 应用》&#xff0c;那是测试网络不好的情况。而下面是十个免费的可以用来进行Web的负载/压力测试的工具&#x…

使用WinSCP 上传 jeecms 到linux centos中 显示乱码问题,网站无法使用的解决方法

第一、设置WinSCP上传时的编码为utf-8如下&#xff1a; 第二、将linux的默认字符集设置为zh_CN.UTF-8 vi /etc/sysconfig/i18n 内容如下&#xff1a; LANG"zh_CN.UTF-8" SUPPORTED"zh_CN.UTF-8:zh_CN:zh" SYSFONT"latarcyrheb-sun16" [rootcan…

如何使用firefox浏览器查看记住的网站密码

工具——》选项——》安全 如下图&#xff1a; 点击就出现浏览器记住的登录网站、帐号、密码了&#xff0c;密码是明码。

如何使用遨游浏览器查看记住的网站密码

点击“显示密码”即可&#xff0c;密码是明码&#xff01;

tomcat部署多个项目,通过不同域名解析访问不同的网站

win7、tomcat8、jdk1.7 第一&#xff1a;通过配置hosts文件模拟&#xff0c;hosts文件所在路径&#xff1a;C:\Windows\System32\drivers\etc 修改如下&#xff1a; #测试tomcat配置多个项目&#xff0c;用二级域名访问 127.0.0.1 www.ibelieve.com 127.0.0.1 bbs.ib…