白猫儿

导航

C#-公众号H5页面授权获取用户code、openid、unionid

一:配置信息

公众号设置:

  1:设置 IP白名单(所在的服务器ip)、记录公众号APPID和APPsecret;

  2:设置 网页授权域名;

 二:页面授权----【html中获取code】

  1:页面引入js  <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

  2: js 跳转授权

    scope   

      (1)静默授权:snsapi_base,没有弹窗,只能获取用户的openId。

      (2)非静默授权:snsapi_userinfo,有弹框弹出需要用户手动点击确认授权。可以获取openId,用户的头像、昵称等

    (snsapi_userinfo指跳转页面授权!123处可随意替换随机数!)

var AppID="公众号APPID";
const { origin } = window.location //获取域名
const currentUrl = encodeURIComponent(`${origin}/HTML/Index.html?z=`)//对URL进行转码
//跳转授权 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';
//跳转授权后>会返回【currentUrl】指定页面并追加参数code!(刷新了一次页面)  此时仅需--获取地址参数【code】
//注意:注意:注意:currentUrl 中域名不能带端口号!!!不能带端口号!!!不能带端口号!!!【me遇到了这个问题找半天!】
//获取地址参数code
const code = GetQueryString('code')
//获取地址参数值
function GetQueryString(name) {

  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return decodeURI(r[2]); return null;
}

 

三:C#--后台获取--openid、unionid  (创建wx.ashx.cs)

  openid:指用户在单一公众号下的唯一标识!

  unionid:指用户在‘单一公司\商家’下多个公众号的唯一标识!

    【一个公司\商家可以有多个公众号(多个公众号对应多个不同openid,仅unionid唯一)】

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

 

posted on 2024-11-25 15:50  白猫儿  阅读(134)  评论(0编辑  收藏  举报