当前位置 主页 > 网站技术 > 代码类 >

    .Net微信网页开发解决用户在不同公众号或在公众号、移动应用之间(2)

    栏目:代码类 时间:2019-09-11 14:30

    通过通过code获取网页授权access_token和用户唯一标识Openid,最后拉取用户信息(需要scope为snsapi_userinfo)

    /// <summary>/// 微信登录注册(通过unionid来判断之前是否已经存在同一个工作平台注册过的账号,假如存在的话则关联起来,不存在注册一个新的账号)/// </summary>/// <param name="code">获取用户凭证换取用户网页授权</param>/// <param name="ReturnUrl">跳转地址</param>/// <returns></returns>public async Task<ActionResult> WxRegisterAndLogin(string code, string ReturnUrl = ""){try{//登录成功后跳转的地址string url=ReturnUrl;//通过Code以及微信appscrect和wxappid换取网页授权access_token和用户oppenidHttpClient webClient = new HttpClient();var jsonString = await (await webClient.GetAsync("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +公众号appid+ "&secret=" + 公众号AppSecret + "&code=" + code + "&grant_type=authorization_code")).Content.ReadAsStringAsync();//异步获取的用户oppenid和access_tokenvar jsonOAuthorObj = JsonConvert.DeserializeObject(jsonString, new { access_token = "", openid = "" }.GetType());if (jsonOAuthorObj.openid == null){return Content(jsonString + "出现错误请重试");}var myuser = new user { WxOpenId = jsonOAuthorObj.openid }.SelectObject();//注册成功后直接登录,授权会判断是否有账户if (myuser == null){//拉取用户信息(需scope为 snsapi_userinfo),和unionid(只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段)jsonString = await (await webClient.GetAsync("https://api.weixin.qq.com/sns/userinfo?access_token=" + jsonOAuthorObj.access_token + "&openid=" + jsonOAuthorObj.openid + "&lang=zh_CN")).Content.ReadAsStringAsync();dynamic jsonObj = JsonConvert.DeserializeObject(jsonString, new { nickname = "", headimgurl = "", sex = "", openid = "", country = "", province = "", city = "",unionid=""}.GetType());//查询系统中是否存在unionid用户信息,若存在则更新当前用户openid,并直接登录,如果不存在的话则需要创建一个新的用户信息var isExistUserInfo=new user(){unionid=unionid }.SelectObject();if(isExistUserInfo!=null)//存在该用户记录{//更新公众号openid isExistUserInfo.WxOpenId=jsonObj.openid; isExistUserInfo.Update();//存在用户信息直接登录return Redirect(url);}else//不存在该用户记录{//创建用户int cUserId = new user { Wximage= jsonObj.headimgurl, WxNickName = jsonObj.nickname, WxOpenId = jsonObj.openid, Sex = Convert.ToInt32(jsonObj.sex), Country = jsonObj.country, Province = jsonObj.province, City = jsonObj.city,unionid=unionid }.Create();return RedirectToAction("WxRegister", "Login", new { ReturnUrl = url });}}else{//存在用户信息直接登录return Redirect(url);}}catch (Exception e){return View("MessageInfo", "", e.ToString());}}

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持IIS7站长之家。