Example #1
0
        public async Task <IActionResult> WxLoginAsync(WxLoginParam loginParam)
        {
            // 使用IHttpClientFactory创建的HttpClient
            OpenIdParam openIdParam = await WxUtils.GetOpenIdAsync(loginParam, clientFactory.CreateClient());

            if (openIdParam == null || string.IsNullOrEmpty(openIdParam.session_key))
            {
                return(ValidationProblem("验证错误,Secret可能失效"));
            }
            WxPhoneModel wxPhoneModel = WxAppEncryptUtil.GetEncryptedDataStr(loginParam.EncryptedData, openIdParam.session_key, loginParam.Iv);

            if (wxPhoneModel == null)
            {
                return(ValidationProblem("用户信息解析错误"));
            }
            string phone = wxPhoneModel.PurePhoneNumber ?? wxPhoneModel.PhoneNumber;

            if (string.IsNullOrEmpty(phone))
            {
                return(ValidationProblem("可能未绑定手机号"));
            }
            TbUser user = await rep.GetEntityAsync(s => s.Phone.Equals(phone), s => new TbUser {
                State = s.State
            });

            if (user == null)
            {
                return(ValidationProblem("用户未注册"));
            }
            string token = AuthorizationUtil.GetToken(30, user.Id, user.Name, "user", user.CarNum);

            return(Ok(new { access_token = token }));
        }
Example #2
0
        /// <summary>
        /// 获取OpenId(建议通过IHttpClientFactory注入HttpClient)
        /// </summary>
        /// <param name="loginParam"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        public static async Task <OpenIdParam> GetOpenIdAsync(WxLoginParam loginParam, HttpClient client = null)
        {
            // 获取openid连接
            string      address     = string.Format(wxLoginLink, loginParam.AppId, loginParam.Secret, loginParam.Code);
            string      jsonStr     = null;
            OpenIdParam openIdParam = null;

            // 自定义HttpClient
            bool selfClient = false;

            if (client == null)
            {
                client     = new HttpClient();
                selfClient = true;
            }
            using (HttpResponseMessage message = await client.GetAsync(address))
            {
                if (message.IsSuccessStatusCode && message.StatusCode == HttpStatusCode.OK)
                {
                    jsonStr = await message.Content.ReadAsStringAsync();
                }
            }
            if (selfClient)
            {
                client.Dispose();
            }
            if (!string.IsNullOrEmpty(jsonStr))
            {
                openIdParam = JsonConvert.DeserializeObject <OpenIdParam>(jsonStr);
                if (openIdParam == null || string.IsNullOrEmpty(openIdParam.session_key))
                {
                    throw new System.Exception(jsonStr);
                }
            }
            return(openIdParam);
        }