C#-公众号H5页面授权获取用户code、openid、unionid
一:配置信息公众号设置:
1:设置 IP白名单(所在的服务器ip)、记录公众号APPID和APPsecret;
2:设置 网页授权域名;
二:页面授权----【html中获取code】
1:页面引入js
2: js 跳转授权
(snsapi_userinfo指跳转页面授权!123处可随意替换随机数!)
var AppID="公众号APPID";
const { origin } = window.location //获取域名
const currentUrl = encodeURIComponent(`${origin}/HTML/Index.html?z=`)//对URL进行转码<br>//跳转授权
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID+ '&redirect_uri=' + currentUrl + '&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';<br>//跳转授权后>会返回【currentUrl】指定页面并追加参数code! 此时仅需--获取地址参数【code】<br>//注意:注意:注意:<strong>currentUrl 中域名不能带端口号</strong>!!!不能带端口号!!!不能带端口号!!!【me遇到了这个问题找半天!】<br>//获取地址参数code<br>const code = GetQueryString('code')<em id="__mceDel">//获取地址参数值<br>function GetQueryString(name) {</em> var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r); return null;
}
三:C#--后台获取--openid、unionid (创建wx.ashx.cs)
using Common;
using HealthApp.Common.wx;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace HealthApp.Ashx
{
/// <summary>
/// wx 的摘要说明
/// </summary>
public class wx : IHttpHandler
{
public static string AppID = "";//公众号APPID
public static string AppSecret = "";//公众号AppSecret
public static string GetOpenid(string code)
{
//微信认证部分:第二步 获得openid
string url = 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 result = HttpClientHelper.GetResponse(url);
JObject outputObj = JObject.Parse(result);
return outputObj["openid"].ToString();
}
public static string GetUser(string access_token, string openID)
{
//微信认证部分:第三步 获得unionid
string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openID);
string result = HttpClientHelper.GetResponse(url);
JavaScriptSerializer js = new JavaScriptSerializer();
Access_Token amodel = js.Deserialize<Access_Token>(result);//此处为定义的类,用以将json转成model
//JObject outputObj = JObject.Parse(result);
//return outputObj["unionid"].ToString();
return amodel.unionid;
}
/// <summary>
/// 通过code获得access_token
/// </summary>
/// <param name="appid"></param>
/// <param name="appsecret"></param>
/// <returns></returns>
public static Access_Token Get_Access_token(string code)
{
string a_token = string.Empty;
WebClient webclient = new WebClient();
string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppID, AppSecret, code);
byte[] bytes = webclient.DownloadData(url);//在指定的path上下载
string result = Encoding.GetEncoding("utf-8").GetString(bytes);//转string
//WriteTextLogHelper.WriteTextLog("获取token", result, DateTime.Now);
JavaScriptSerializer js = new JavaScriptSerializer();
Access_Token amodel = js.Deserialize<Access_Token>(result);//此处为定义的类,用以将json转成model
return amodel;
}
public class Access_Token
{
public string access_token { get; set; }
public string expires_in { get; set; }
public string openid { get; set; }
public string unionid { get; set; }
public string errcode { get; set; }
}
}
} c#后台调用示例
//传参-页面授权的code
string code = context.Request["code"].ToString();
if (string.IsNullOrEmpty(code))
{
//未授权!需要授权
//wx.OpenAccess(tj);
context.Response.Write("未授权");
}
//第二部获取access_token
var access_token = wx.Get_Access_token(code);
//第三部拉取用户信息
var unionid = wx.GetUser(access_token.access_token, access_token.openid);
var openID = access_token.openid;
检验 网页授权域名 是否通过:
(公众平台测试账号----登录公众号管理账号》输入域名进行检验)网址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
微信官方文档---授权网址 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
来源:https://www.cnblogs.com/BMxxx/p/18567538/baimao
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]