時間:2022-08-10 15:57:01 | 來源:網(wǎng)站運營
時間:2022-08-10 15:57:01 來源:網(wǎng)站運營
開發(fā)者可通過OpenID來獲取用戶基本信息。特別需要注意的是,如果開發(fā)者擁有多個移動應用、網(wǎng)站應用和公眾帳號,可通過獲取用戶基本信息中的unionid來區(qū)分用戶的唯一性,因為只要是同一個微信開放平臺帳號下的移動應用、網(wǎng)站應用和公眾帳號,用戶的unionid是唯一的。換句話說,同一用戶,對同一個微信開放平臺下的不同應用,unionid是相同的。
獲取用戶基本信息(包括UnionID機制)開發(fā)者可通過OpenID來獲取用戶基本信息。請使用https協(xié)議。
第三方使用網(wǎng)站應用授權登錄前請注意已獲取相應網(wǎng)頁授權作用域(scope=snsapi_login),則可以通過在PC端打開以下鏈接:https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect若提示“該鏈接無法訪問”,請檢查參數(shù)是否填寫錯誤,如redirect_uri的域名與審核時填寫的授權域名不一致或scope不為snsapi_login。
/// <summary>/// 微信登錄注冊(通過unionid來判斷之前是否已經(jīng)存在同一個工作平臺注冊過的賬號,假如存在的話則關聯(lián)起來,不存在注冊一個新的賬號)/// </summary>/// <param name="code">獲取用戶憑證換取用戶網(wǎng)頁授權</param>/// <param name="ReturnUrl">跳轉地址</param>/// <returns></returns>public async Task<ActionResult> WxRegisterAndLogin(string code, string ReturnUrl = ""){try{//登錄成功后跳轉的地址string url=ReturnUrl;//通過Code以及微信appscrect和wxappid換取網(wǎng)頁授權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 + "出現(xiàn)錯誤請重試");}var myuser = new user { WxOpenId = jsonOAuthorObj.openid }.SelectObject();//注冊成功后直接登錄,授權會判斷是否有賬戶if (myuser == null){//拉取用戶信息(需scope為 snsapi_userinfo),和unionid(只有在用戶將公眾號綁定到微信開放平臺帳號后,才會出現(xiàn)該字段)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());//查詢系統(tǒng)中是否存在unionid用戶信息,若存在則更新當前用戶openid,并直接登錄,如果不存在的話則需要創(chuàng)建一個新的用戶信息var isExistUserInfo=new user(){unionid=unionid }.SelectObject();if(isExistUserInfo!=null)//存在該用戶記錄{//更新公眾號openid isExistUserInfo.WxOpenId=jsonObj.openid; isExistUserInfo.Update();//存在用戶信息直接登錄return Redirect(url);}else//不存在該用戶記錄{//創(chuàng)建用戶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());}}
技術群:添加小編微信并備注進群
小編微信:mm1552923
公眾號:dotNet編程大全
關鍵詞:公眾,用戶,解決,移動,機制,通過
微信公眾號
版權所有? 億企邦 1997-2025 保留一切法律許可權利。