获取openid流程为首先根据微信开发参数构造AuthorizeUrl认证链接,用户跳转到该链接进行授权,授权完成将跳转到回调页(首次认证需要授权,后面将直接再跳转至回调页),此时回调页中带上一个GET参数code,使用该code请求微信接口得到用户的openid。话不多说,直接上代码。

1.编写认证类OAuth

public class OAuth
{
public static HttpClient httpClient = new HttpClient();
public static string GetAuthorizeUrl(string appId, string redirectUrl, string state= "state", string scope = "snsapi_base", string responseType = "code")
{
if (!string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = HttpUtility.UrlEncode(redirectUrl, System.Text.Encoding.UTF8);
}
else
{
redirectUrl = null;
}
object[] args = new object[] { appId, redirectUrl, responseType, scope, state };
return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect", args);
} public static string GetOpenIdUrl(string appId, string secret, string code, string grantType = "authorization_code")
{
object[] args = new object[] { appId, secret, code, grantType };
string requestUri = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type={3}", args);
return requestUri;
} /// <summary>
/// 获取openid
/// </summary>
/// <param name="appId"></param>
/// <param name="secret"></param>
/// <param name="code"></param>
/// <param name="grantType"></param>
/// <returns></returns>
public static string GetOpenid(string appId, string secret, string code, string grantType = "authorization_code")
{
string requestUri = GetOpenIdUrl(appId, secret, code, grantType);
var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
string openid = string.Empty;
if (!obj.TryGetValue("openid", out openid))
{
Log.Info($"获取openid失败appId={appId},secret={secret},code={code}");
}
return openid;
}
}

  2.在控制器中使用认证类获取用户openid,注意:访问该控制器地址确保微信回调时候也能访问到该地址

/// <summary>
/// 获取微信openid
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
[HttpGet]
public IActionResult GetWxOpenid(string code)
{
WxPayConfig wxPayConfig = new WxPayConfig();
//首先构造微信请求授权url,重定向到该url中,其中redirectUrl是回调地址,必须保证该地址在公网上能访问,本例子构造的是返回到本控制器的方法。
//若是从微信授权返回进入该方法,则会带上一个参数,code就不为空,若code为空则跳转微信授权
if (string.IsNullOrEmpty(code))
{
var redirectUrl = OAuth.GetAuthorizeUrl(wxPayConfig.appid, "回调地址到公网本Action");
return Redirect(redirectUrl);
}
else
{
//根据code和微信参数得到openid
var openId = OAuth.GetOpenid(wxPayConfig.appid, wxPayConfig.appSecret, code);
//业务处理 }
return View();
}

  通过使用OAuth类轻松的就能获取用户的Openid

附上写日志的一个老师傅写类库Sky.Logger,在项目中添加引用即可使用日志:链接: https://pan.baidu.com/s/1eHdNGZN0pmNHsO_yHzgE_g 密码: ta2x

最新文章

  1. springAOP实现基于注解的数据源动态切换
  2. js中的offsetWidth岁的BUG
  3. 真实世界:使用WCF扩展在方法调用前初始化环境
  4. Apex Design Patterns
  5. FFrpc python客户端lib
  6. node.js使用util实现简单继承
  7. 学习Slim Framework for PHP v3 (三)
  8. public,protected,friendly,private的访问权限
  9. SQLite设置主键自动增长及插入语法
  10. phpcms v9 表单向导里添加图片字段,提示会话过期,请重新登陆
  11. 设定PCB电路板形状和物理边界
  12. Java宝典(一)
  13. 最长回文 hdu3068(神代码)
  14. 用Nodejs+Express搭建web,nodejs路由和Ajax传数据并返回状态,nodejs+mysql通过ajax获取数据并写入数据库
  15. linux --&gt; 动态库和静态库
  16. pandas学习笔记(一)
  17. centos7/RHEL7最小化系统安装gnome图形界面
  18. appium定位h5
  19. 为 git设置代理
  20. 反序列化失败Failed to deserialize --- local class incompatible: stream classdesc serialVersionUID

热门文章

  1. (cx_Oracle.DatabaseError) DPI-1047: 64-bit Oracle Client library cannot be loaded: &quot;libclntsh.so: cannot open shared object file: No such file or directory&quot;
  2. Oracle语句优先级
  3. Lucene Query In Kibana
  4. Winfrom多文档界面实现
  5. CF949D Curfew
  6. mysql timestamp时区有影响
  7. python3爬虫二
  8. Jetson tk1 hash sum mismatch
  9. 基于Python的机器学习实战:Apriori
  10. Dubbo监控中心