功能:认证服务号通过网页授权获取用户信息

--公众号后台配置

》此次设置的是网页授权域名,设置成你调试的域名或者正式备案的域名(不带http或https)。

--自定义菜单设置

设置参数:

appid:微信公众号的appid

uri:微信网页授权后跳转的网页(该uri需经过UrlEncode编码)

scope:此处使用 snsapi_userinfo方式

关于网页授权的两种scope的区别说明

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)

2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。

--授权步骤

1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

--后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;namespace wxweb.Areas.wechatPage.Controllers
{public class service_PersonalController : Controller{// GET: wechatPage/service_Personalpublic ActionResult Index(){//--------------微信oauth授权---------------wxPlatForm.OAuth.wechatOAuth oauth = new wxPlatForm.OAuth.wechatOAuth();oauth.appid = appid;//微信公众号的appidoauth.secret = secret;//微信公众号的AppSecretoauth.get_code();//获取token及userinfo信息if (oauth.o_user != null){//获取用户信息成功,继续逻辑业务操作
            }else{return RedirectToAction("Error", "service_Personal");}//--------------end微信oauth授权---------------return View();}}
}

网页授权接入页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;namespace wxPlatForm.OAuth
{public class wechatOAuth{/// <summary>  /// 公众号的唯一标识  /// </summary>  public string appid;/// <summary>  /// 公众号的appsecret  /// </summary>  public string secret;public OAuthAccess_Token o_token;public OAuthUser o_user;private string code;/// <summary>/// 获取code/// </summary>public void get_code() {try{code = HttpContext.Current.Request.QueryString["Code"];if (code != ""&&code!=null) {get_access_token();}}catch (Exception ex){common.CommonMethod.WriteTxt(ex.Message);}}/// <summary>/// 通过code换取网页授权access_token/// </summary>public void get_access_token() {Dictionary<string, string> obj = new Dictionary<string, string>();var client = new System.Net.WebClient();var serializer = new JavaScriptSerializer();string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);client.Encoding = System.Text.Encoding.UTF8;string dataaccess = "";try{dataaccess = client.DownloadString(url);//获取字典obj = serializer.Deserialize<Dictionary<string, string>>(dataaccess);string accessToken = "";if (obj.TryGetValue("access_token", out accessToken))  //判断access_Token是否存在
                {o_token =new OAuthAccess_Token {access_token=obj["access_token"],expires_in =Convert.ToInt32( obj["expires_in"]),refresh_token = obj["refresh_token"],openid = obj["openid"],scope = obj["scope"]};if (o_token.scope == "snsapi_userinfo") {get_userinfo(o_token.access_token, o_token.openid);}}else  //access_Token 失效时重新发送。
                {//存log方法common.CommonMethod.WriteTxt("access_token 获取失败,time:"+DateTime.Now.ToLongTimeString());}}catch (Exception e){//存log方法
                common.CommonMethod.WriteTxt(e.Message);}}/// <summary>/// 拉取用户信息(需scope为 snsapi_userinfo)/// </summary>/// <param name="access_token">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>/// <param name="access_token">    用户的唯一标识</param>public void get_userinfo(string access_token,string openid) {Dictionary<string, object> obj = new Dictionary<string, object>();var client = new System.Net.WebClient();JavaScriptSerializer serializer = new JavaScriptSerializer();string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);client.Encoding = System.Text.Encoding.UTF8;string dataaccess = "";try{dataaccess = client.DownloadString(url);obj = serializer.Deserialize<Dictionary<string, object>>(dataaccess);object user_openid = "";if (obj.TryGetValue("openid", out user_openid))  //判断access_Token是否存在
                {o_user = new OAuthUser{openid = obj["openid"].ToString(),nickname = obj["nickname"].ToString(),sex =Convert.ToInt32( obj["sex"]),province = obj["province"].ToString(),city = obj["city"].ToString(),country = obj["country"].ToString(),headimgurl = obj["headimgurl"].ToString(),privilege =obj["privilege"].ToString(),unionid =""};}else  //access_Token 失效时重新发送。
                {//存log方法common.CommonMethod.WriteTxt("用户信息 获取失败,time:" + DateTime.Now.ToLongTimeString());}}catch (Exception e){//存log方法
                common.CommonMethod.WriteTxt(e.Message);}}/// <summary>/// 检验授权凭证(access_token)是否有效/// </summary>/// <param name="appid">公众号的唯一标识</param>  /// <param name="refresh_token">填写通过access_token获取到的refresh_token参数</param>public void refresh_access_token(string refresh_token) {Dictionary<string, string> obj = new Dictionary<string, string>();var client = new System.Net.WebClient();var serializer = new JavaScriptSerializer();string url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", this.appid, refresh_token);client.Encoding = System.Text.Encoding.UTF8;string dataaccess = "";try{dataaccess = client.DownloadString(url);//获取字典obj = serializer.Deserialize<Dictionary<string, string>>(dataaccess);string accessToken = "";if (obj.TryGetValue("access_token", out accessToken))  //判断access_Token是否存在
                {OAuthAccess_Token o_token = new OAuthAccess_Token{access_token = obj["access_token"],expires_in = Convert.ToInt32(obj["expires_in"]),refresh_token = obj["refresh_token"],openid = obj["openid"],scope = obj["scope"]};if (o_token.scope == "snsapi_userinfo"){get_userinfo(o_token.access_token, o_token.openid);}}else  //access_Token 失效时重新发送。
                {//存log方法common.CommonMethod.WriteTxt("access_token 获取失败,time:" + DateTime.Now.ToLongTimeString());}}catch (Exception e){//存log方法
                common.CommonMethod.WriteTxt(e.Message);}}/// <summary>/// 刷新access_token(如果需要)/// </summary>public void check_access_token(){}}
}

网页授权接入-调用wechatOAuth

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace wxPlatForm.OAuth
{public class OAuthAccess_Token{public string access_token { get; set; }public int expires_in { get; set; }public string refresh_token { get; set; }/// <summary>  /// 用户针对当前公众号的唯一标识  /// 关注后会产生,返回公众号下页面也会产生  /// </summary>  public string openid { get; set; }public string scope { get; set; }/// <summary>  /// 当前用户的unionid,只有在用户将公众号绑定到微信开放平台帐号后  /// </summary>  public string unionid { get; set; }}
}

网页授权接入-调用OAuthAccess_Token

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace wxPlatForm.OAuth
{/// <summary>  /// 授权之后获取用户基本信息  /// </summary>  public class OAuthUser{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; }/// <summary>  /// 用户特权信息,json 数组  /// </summary>  //public JArray privilege { get; set; }public string privilege { get; set; }public string unionid { get; set; }}
}

网页授权接入-调用OAuthUser

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;namespace common
{/// <summary>/// 通用方法类/// </summary>public class CommonMethod{#region 记录bug,以便调试/// <summary>/// 记录bug,以便调试/// </summary>public static bool WriteTxt(string str){try{string LogPath = HttpContext.Current.Server.MapPath("/err_log/");if (!Directory.Exists(LogPath)){Directory.CreateDirectory(LogPath);}FileStream FileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/err_log//xiejun_" + DateTime.Now.ToLongDateString() + "_.txt"), FileMode.Append);StreamWriter StreamWriter = new StreamWriter(FileStream);//开始写入
                StreamWriter.WriteLine(str);//清空缓冲区
                StreamWriter.Flush();//关闭流
                StreamWriter.Close();FileStream.Close();}catch (Exception){return false;}return true;}#endregion}
}

写日志

转载于:https://www.cnblogs.com/eye-like/p/9276529.html

微信是个坑货4-网页授权相关推荐

  1. 微信开发学习 问题1: 网页授权问题 “该连接无法访问” 解决方法

    微信开发学习 问题1: 网页授权问题 "该连接无法访问" 解决方法 参考文章: (1)微信开发学习 问题1: 网页授权问题 "该连接无法访问" 解决方法 (2) ...

  2. 微信公众平台-服务号:网页授权域名 设置

    微信公众平台-服务号的网页授权域名 设置 设置与开发->公众号设置->功能设置->网页授权域名 一:下载认证文件,放置服务器中 二:设置服务器中的 Https中的nginx服务 ng ...

  3. 微信公共平台接入之:网页授权(微信授权,微信access_token获取,获取微信用户信息),微信开发者工具使用,微信公众平台测试号申请接入

    1.微信公众平台文档入口 微信公众平台入口地址:https://mp.weixin.qq.com/,截图: 进入之后的文档地址: https://mp.weixin.qq.com/wiki?t=res ...

  4. 微信公众平台开发OAuth2.0网页授权(转)

    微信公众平台开发 OAuth2.0网页授权认证 网页授权获取用户基本信息  作者:方倍工作室 微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友在 ...

  5. 微信公众平台开发 OAuth2.0网页授权认证

    一.什么是OAuth2.0 官方网站:http://oauth.NET/   http://oauth.Net/2/ 权威定义:OAuth is An open protocol to allow s ...

  6. 微信开发之获取OAuth2.0网页授权认证和获取用户信息进行关联(转:http://playxinz.iteye.com/blog/2249634)

    最近有做了关于微信公众号和自己网站用户进行用户关联授权登录的一个功能,主要是用户关注该公众号,点击会员中心,则会弹出需要关联授权的网页授权:OAuth2.0网页授权,然后用户同意获取用户信息,进行用户 ...

  7. 微信公众号开发002-微信网页授权

    1.首先在开发前阅读微信提供的API文档(https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842) 阅读完的我们就知 ...

  8. PHP实现微信公众平台开发---提升篇(网页授权接口)

    网页授权接口(类似于浏览器通过cookie|session标识客户 微信端通过openid标识) 接口类型(通过网页授权 获取openid) snsapi_base:基本类型 静默授权并自动跳转到回调 ...

  9. 如何获取微信浏览器访问需要OAuth2.0网页授权的页面资源

    目标:需要获取一些微信网页的前端资源,嘿嘿,你懂的. 方法: 方法一:用chrome模拟微信浏览器,这个需要OAuth2.0授权的网页就获取不了啦... 方法二:百度了说可以用PHP的代码模拟访问,测 ...

最新文章

  1. [转]oracle 存储过程的基本语法 及注意事项
  2. 用开源工具OCSNG管理资产信息
  3. Spring常问的面试
  4. Boost:序列化之text_iarchive和text_oarchive
  5. [BUUCTF-pwn]——picoctf_2018_can_you_gets_me
  6. 保25ms争10ms——Zenlayer如何保持出海业务的超低延时
  7. 硬件知识:U盘缩水是怎么回事,如何恢复U盘真实容量?
  8. Git初学札记(三)————创建Git版本库
  9. [iOS]如何把App打包成ipa文件,然后App上架流程[利用Application Loader]
  10. execution 排除_使用SQL Server 2016 Live Execution统计信息对SQL查询性能进行故障排除
  11. 灵格斯 Lingoes 2.8 去广告 禁止新词锐词弹窗
  12. 网页设计1-1李清照人物简介
  13. Openssl 命令之cer证书转成pem. 利用ptf私钥文件生成公钥
  14. lt18i android 2.3.4典藏版,索尼LT18i一键ROOT教程工具 2.3.4已亲测成功
  15. AWash: Handwashing Assistance for the Elderly with Dementia via Wearables
  16. Java身份证、手机号码用*隐藏中间几位
  17. DBeaver设置Maven镜像仓库
  18. C/C++动态申请空间方式
  19. pip install lap出现问题
  20. Mysql数据库表结构导出工具介绍

热门文章

  1. 关于OGNL表达式中的%,$,#
  2. cannot access a closed file
  3. element ui 图片控件 排序_JAVA全栈面试前端基础之四 Vue+Element框架快速开发
  4. Mysql提示缺少表的别名报错_mysql对sql中别名引起的Column not found问题
  5. mysql锁表_MYSQL锁表问题的解决方法
  6. c语言翻译成php,C语言如何把它翻译成中文
  7. 量子计算机真随机数,量子真随机数发生器研究取得进展
  8. jsp调试java_调试从Tomcat(JSP)运行的Java程序
  9. android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能
  10. matlab奈馈斯图,matlab关于控制的设计单位负反馈的校正