当前位置: 首页 > 编程日记 > 正文

微信是个坑货4-网页授权

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

--公众号后台配置

》此次设置的是网页授权域名,设置成你调试的域名或者正式备案的域名(不带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

相关文章:

root 123 mysql_MySQL常用命令

1、查看数据库状态 及启动停止/etc/init.d/mysqld status/etc/init.d/mysqld start/etc/init.d/mysqld stop2、给用户配置初始密码123456&#xff1a;mysqladmin -u root -password 1234563、修改root用户密码为 abc123mysqladmin -u root -p123456 password abc1234、如果想去…

想挖矿?不如先学习一下以太坊

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 许多使用点对点协议且基于区块链的项目在性能和吞吐量上夸大其辞。在研发阶段&#xff0c;这些项目已经出现了一些创新&#xff0c;但是一旦这些协…

Kubernetes入门

简介  它是一个全新的基于容器技术的分布式解决方案&#xff0c;基于强大的自动化机制解决传统系统架构中负载均衡和实施部署的问题&#xff0c;从而节省了30%开发成本&#xff0c;其次具有完备的集群能力&#xff0c; 包括服务注册、服务发现、故障的发现和修复、服务滚动升…

ubuntu 14.04安装postgresql最新版本

官网&#xff1a; https://www.postgresql.org/download/linux/ubuntu/ -------------------------------------------------------------------------------------------------------------------- 另一篇文章&#xff0c;讲的差不多也是这个&#xff1a; http://tecadmin.net…

c++ mysql ctime_C++操作mysql数据库范例代码

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。编程之家小编现在分享给大家&#xff0c;也给大家做个参考。#include #include void TestMySQL(){TRACE("MySQL client version: %s\n",mysql_get_client_info());MYSQL *conn mysql_init(NULL);if (conn NULL…

链客区块链技术问答社区

链客是中国领先的区块链垂直领域技术问答社区&#xff08;www.liankexing.com&#xff09;&#xff0c;旨在为大家提供一个直接、高效的技术交流平台&#xff0c;区块链技术爱好者遇到的每一个问题&#xff0c;链客做到有问必答&#xff01; 在这里&#xff1a; ①海量的真实…

oracle imp dmp

imp helpy导入自己的表&#xff1a;exp scott/tigerorcl tables(student, address) fileD:\scott_stu_add.dmp logD:\scott_stu_add.logimp scott/tigerorcl fileD:\scott_stu_add.dmp logD:log.logimp scott/tigerorcl fileD:\scott_stu_add.dmp tablesstudent 导入别人的表&a…

STM32普通定时器(TIM2-7)的时钟源

STM32普通定时器(TIM2-7)的时钟源 转载于:https://www.cnblogs.com/LittleTiger/p/6218048.html

operate函数_跟着 redux 学 compose组合函数

▲ 点击上方蓝字关注我 ▲把你的心 我的心串一串 串一株幸运草 串一个同心圆文 / 景朝霞来源公号 / 朝霞的光影笔记ID / zhaoxiajingjing目录0 / 热热身1 / redux 中的compose函数2 / 逐步分析(1)compose()函数调用① reduce第一轮遍历② reduce第一轮遍历③ reduce第三轮遍历(…

感恩有你,链客一周年!

感恩有你&#xff0c;链客一周年&#xff01; 2018年6月16日&#xff0c;天气&#xff1a;晴&#xff0c;在这一天&#xff0c;诞生了一个崭新的技术社区&#xff1a;链客区块链技术问答社区&#xff08;www.liankexing.com) 她的诞生让我们赋予了’利他‘的概念&#xff0c;…

【Python3_基础系列_006】Python3-set-集合

一、set集合的方法 set不是特别常用&#xff0c;但是set的一些特性可以方便处理一些特殊情况。 集合&#xff08;set&#xff09;是一个无序不重复元素的序列。 可以使用大括号 { } 或者 set() 函数创建集合&#xff0c;注意&#xff1a;创建一个空集合必须用 set() 而不是 { }…

springmvc xml 空模板

<?xml version"1.0" encoding"UTF-8"?><!-- Bean头部 --><beans xmlns"http://www.springframework.org/schema/beans" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xmlns:p"http://www.springframe…

mysql ltree_mysq基础知识总结l

一、Mysql架构二、Mysql查询过程例如执行select * from tablea where id4;三、Mysql中的事务及隔离级别事务&#xff1a;InnoDB存储引擎支持事务。事务是mysql的执行最小单元&#xff0c;也就是原子性。要么执行成功&#xff0c;要么执行失败。>start transaction>commit…

如何让自己时刻冷静的方法_4个方法,教你如何真正爱自己

很多人说&#xff0c;我想爱自己&#xff0c;看了很多文章&#xff0c;依然不知道如何爱自己。那你可以问一问自己&#xff0c;你对自己拥有的一切感到开心、快乐和满足吗&#xff1f;“爱自己”对你是知识还是习惯呢&#xff1f;实际上&#xff0c;当你的内在固有的思维模式转…

记录一个比较完整的python项目分析架构

世界杯&#xff1a;用Python分析热门夺冠球队 https://www.cnblogs.com/lemonbit/p/9174965.html 转载于:https://www.cnblogs.com/testerhome-yizhou2018/p/9287115.html

list,set,map,数组间的相互转换

1.list转set Java代码 Set set new HashSet( new ArrayList()); 2.set转list Java代码 List list new ArrayList( new HashSet()); 3.数组转为list Java代码 List stooges Arrays.asList( "Larry" , "Moe" , "Curly" ); 此时st…

void函数返回值_(*void(*)()0)() 是什么

(*void(*)()0)()代码分析这是啥这行代码&#xff0c;是我今天在看《C陷阱与缺陷》时看到的&#xff0c;一开始很不能理解。慢慢上网摸索一些后&#xff0c;大致理解了&#xff0c;现在来分享一下我所理解的这行代码。1.首先&#xff0c;得明白什么是函数指针。顾明思义&#xf…

老年手机英文改中文_这些手游大作你都玩了吗?手机游戏推荐

全 世 界 只 有 1 % 的 人 关 注 郭 叔 说你 真 是 个 特 别 的 人目前100000人 已关注 郭叔说郭叔说做一个有趣的人&#xff0c;从认识我开始。关注攻略交流群请添加微信&#xff1a;GLT962464 备注老规矩&#xff1a;游戏名(无备注不通过&#xff01;&#xff01;&#xf…

MySQL数据库(五)使用pymysql对数据库进行增删改查

折腾好半天的数据库连接&#xff0c;由于之前未安装 pip &#xff0c;而且自己用的python 版本为3.6. 只能用 pymysql 来连接数据库&#xff0c;&#xff08;如果有和我一样未安装 pip 的朋友请 点这里http://blog.csdn.net/qq_37176126/article/details/72824404 &#xff09…

vue调试工具如何使用_教你使用Vue.js的DevTools来调试vue项目

Vue DevTools项目的官方主页位于GitHub上&#xff1a;https&#xff1a;//http://github.com/vuejs/vue-devtools。你可以找到安装说明&#xff0c;帮助解决一些问题等等。目前该扩展在Chrome和Firefox中得到支持&#xff0c;同样Safari也得到了支持。如果你想从安装扩展开始&a…

Python开发【第十篇】:CSS (二)

Python开发【前端】&#xff1a;CSS Kylin Zhang 发表于 2016-11-10 13:13:57css样式选择器 标签上设置style属性&#xff1a; <body><div style"height: 48px;">第一层</div><div style"height: 48px;">第二层</div><di…

java设计一个bank类实现银行_SAP银企直连之平安银行(ECC版)

关于讲解SAP中国本地化银企直连系统功能&#xff0c;它通过ECC和S4 HANA 1909两个不同版本的演示来讲解银企直连付款相关功能实施和应用&#xff0c;有兴趣的可以联系微信号&#xff1a;timijia进行付费获取。以下资料仅供大家参考&#xff1a;说明&#xff1a;因为平安银行较S…

spark ml中一个比较通用的transformer

spark ml中有许多好用的transformer&#xff0c;很方便用来做特征的处理&#xff0c;比如Tokenizer, StopWordsRemover等,具体可参看文档:http://spark.apache.org/docs/2.1.0/ml-features.html . 但是呢&#xff0c;这些都是一些特定的操作&#xff0c;组内的同事提了一个需求…

mysql 常用函数循环_近30个MySQL常用函数,看到就是学到,纯干货收藏!

概念&#xff1a;相当于java中的方法&#xff0c;将一组逻辑语句封装在方法体中&#xff0c;对外暴露方法名隐藏了实现细节提高代码的可重用性使用&#xff1a;select 函数名(实参列表)【from 表】 【】中内容可省略正文&#xff1a;字符函数&#xff1a;length&#xff1a;…

连接Oracle错误:800a0e7a未找到提供程序的解决

一、现象&#xff1a; C#程序中需要以ProviderOraOLEDB.Oracle.1方式访问ORACLE数据库。但程序执行时报异常&#xff1a;未在本地计算机注册“OraOLEDB.Oracle.1”提供程序 二、解决方案&#xff1a; 1、在Oracle安装目录找到Oracle的主程序目录&#xff0c;点击鼠标右键->属…

定义一个属性_Python property属性

1. 什么是property属性一种用起来像是使用的实例属性一样的特殊属性&#xff0c;可以对应于某个方法# ############### 定义 ###############class Foo: def func(self): pass # 定义property属性 property def prop(self): pass# ############### 调用 ###############foo_obj…

MySQL 字段类型知识

tinyint(m)  值的范围&#xff1a;-128 ~ 127&#xff1b;unsigned 时&#xff0c;0 ~ 255。存储占用1字节 m 默认为4&#xff0c;和存储空间、数字位数没有关系&#xff0c;表示左侧补空格&#xff08;默认&#xff0c;声明 zerofill 则补0&#xff0c;如0001&#xff09;到…

mysql 单实例部署_Mysql 数据库单机多实例部署手记

最近的研发机器需要部署多个环境&#xff0c;包括数据库。为了管理方便考虑将mysql数据库进行隔离&#xff0c;即采用单机多实例部署的方式。找了会资料发现用的人也不是太多&#xff0c;一般的生产环境为了充分发挥机器性能都是单机单实例运行&#xff0c;再进行一系列的配置调…

用python做一个图片验证码

看一下做出来的验证码长啥样 验证码分析 1. 有很多点 2. 有很多线条 3. 有字母&#xff0c;有数字 需要用到的模块&#xff1a; 1. random 2. Pillow (python3中使用pillow) 安装pillow : pip install pillow pillow的用法&#xff1a; 创建一张图片&#xff1a; from PIL im…

地图测量面积工具app_全站仪的使用面积测量

测量与地图制作见习全站仪使用11 / 20#2020 #全站仪是全站型电子速测仪的简称&#xff0c;是电子经纬仪、光学测距仪及微处理器相结合的光电仪器。其可直接测量距离、角度、坐标&#xff0c;根据三角函数原理&#xff0c;已知两点坐标信息推算出无数个第三点的坐标信息。下面让…