服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 微信开放平台之网站授权微信登录功能

微信开放平台之网站授权微信登录功能

2021-10-27 11:36小 鹏 C#

本文通过.net实现的微信开放平台之网站授权微信登录功能,需要的小伙伴一起看看吧

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

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

微信开放平台之网站授权微信登录功能

3.pc页面显示

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

第一步:请求code

第二步:通过code获取access_token

第三步:通过access_token调用接口

第4步:获取用户个人信息(unionid机制)

api:核心代码

?
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
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;
   }
   //反序列化json
   dictionary<string, object> dic = jsonhelper.datarowfromjson(result);
   return dic;
  }
 }

控制器的核心代码:

?
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
#region 微信登录
  /// <summary>
  /// 微信登录
  /// </summary>
  public actionresult wechat()
  {
   //获得配置信息
   oauth_config config = oauth_helper.get_config(2); //主键id
   if (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以及openid
   dictionary<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_token
   expires_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_token
    if (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

 

延伸 · 阅读

精彩推荐
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11