Example #1
0
        public ActionResult OnLogin(string code)
        {
            JsCode2JsonResult jsonResult = SnsApi.JsCode2Json(Comman.Appid, Comman.AppSecret, code);

            if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功)
            {
                SessionBag sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key);
                Session[sessionBag.Key] = jsonResult;
                Session.Timeout         = 60;
                StatusReport sr = EmployeeDal.CheckOpenIdExist(jsonResult.openid);
                return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, userInfo = sr }));
            }
            else
            {
                return(Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult }));
            }
        }
        public async Task <IActionResult> login([FromBody] JObject jObject)
        {
            var code       = jObject["code"].ToString();
            var activityNo = this.GetActivityNo();

            #region 校验参数

            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrWhiteSpace(code))
            {
                sb.AppendLine("code无效!");
            }

            if (string.IsNullOrWhiteSpace(appId))
            {
                sb.AppendLine("appid无效!");
            }

            if (!string.IsNullOrEmpty(sb.ToString()))
            {
                return(BadRequest(sb.ToString()));
            }

            #endregion 校验参数

            #region 获取微信openId

            var jsonResult = new JsCode2JsonResult();
            try
            {
                jsonResult = SnsApi.JsCode2Json(appId, appSecret, code);
                //Console.WriteLine("jsonResult:" + Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult));
                if (jsonResult.errcode == ReturnCode.请求成功)
                {
                    if (string.IsNullOrEmpty(jsonResult.openid))
                    {
                        return(BadRequest("获取OpenId失败"));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("登录失败:" + ex.Message);
                return(BadRequest("登录失败"));
            }

            #endregion 获取微信openId

            //开放平台下存在同一主体小程序+公众号且用户已关注返回unionId,否则不返回
            //同主体公众号小程序 用户是否关注 1:关注 0:否
            var subscsribe = !string.IsNullOrEmpty(jsonResult.unionid) ? 1 : 0;
            //获取会员信息,每次都会更新sessionKey
            var data = await _activityApplication.GetMemberByOpenIdAsync(activityNo, jsonResult.openid, jsonResult.session_key);

            //获取活动信息
            var activityInfo = await _activityApplication.GetActivityResponseAsync(this.GetActivityNo());

            // 愿望状态
            var wish = await _activityApplication.MemberWishStatusAsync(activityNo, data.memberId);

            return(this.MyOK(
                       new
            {
                subscsribe,
                data.memberId,
                data.gender,
                data.isBind,
                data.nickName,
                data.avatarUrl,
                activity = new
                {
                    activityInfo?.status,
                    activityInfo?.startTime,
                    activityInfo?.endTime,
                    activityInfo?.serverTime
                },
                myWish = new { wishId = wish.Item1, status = wish.Item2, mchNo = wish.Item3 }
            }));
        }
        public async Task <IActionResult> BindPhone([FromBody] BindTelRequestParam request)
        {
            if (request == null)
            {
                return(BadRequest("参数错误"));
            }
            if (string.IsNullOrEmpty(request.encryptedData) || string.IsNullOrEmpty(request.iv))
            {
                return(BadRequest("参数错误"));
            }
            var memberId = this.GetMemberId();

            if (memberId == 0)
            {
                return(BadRequest("未获取会员id"));
            }
            #region 更新session_key
            if (!string.IsNullOrEmpty(request.code))
            {
                var jsonResult = new JsCode2JsonResult();
                try
                {
                    jsonResult = SnsApi.JsCode2Json(appId, appSecret, request.code);
                    await _activityApplication.UpdateSessionKeyAsync(memberId, jsonResult.session_key);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("更新session_key失败:" + ex.Message);
                }
            }
            #endregion 更新session_key


            string sessionKey = await _activityApplication.GetSessionKeyAsync(memberId);

            string tel = "";

            #region 解析手机号

            try
            {
                var jsonStr     = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(sessionKey, request.encryptedData, request.iv);
                var phoneNumber = Newtonsoft.Json.JsonConvert.DeserializeObject <Senparc.Weixin.WxOpen.Entities.DecodedPhoneNumber>(jsonStr);
                tel = phoneNumber.purePhoneNumber;
            }
            catch (Exception ex)
            {
                var logger = _loggerFactory.CreateLogger($"Error-BindPhoneNumber:{DateTime.Now}");
                logger.LogError(ex.Message);

                return(BadRequest("手机号解析失败"));
            }

            #endregion 解析手机号

            if (string.IsNullOrEmpty(tel))
            {
                return(BadRequest("手机号解析失败"));
            }
            var(resCode, res) = await _activityApplication.BindTelAsync(memberId, tel);

            if (resCode == 0)
            {
                return(BadRequest(res));
            }
            return(this.MyOK(new { resCode = 1 }));
        }
        public async Task <Result> LiteAppLogin([FromBody] WeChatLiteAppLoginRequest request)
        {
            string errorMsg = string.Empty;

            try
            {
                JsCode2JsonResult jsonResult = SnsApi.JsCode2Json(WechatService.WxOpenAppId, WechatService.WxOpenAppSecret, request.Code);
                if (jsonResult != null && jsonResult.errcode == ReturnCode.请求成功)
                {
                    var customer = await _customerRepository.Query()
                                   .FirstOrDefaultAsync(e => e.OpenId == jsonResult.openid);

                    if (customer == null)
                    {
                        int?parentId  = null;
                        var anyParent = await _customerRepository.Query().AnyAsync(e => e.Id == request.ParentId);

                        if (anyParent)
                        {
                            parentId = request.ParentId;
                        }

                        var userInfo = request.UserInfo;
                        customer = new Customer
                        {
                            NickName   = userInfo.NickName,
                            OpenId     = jsonResult.openid,
                            SessionKey = jsonResult.session_key,
                            UnionId    = jsonResult.unionid,
                            Gender     = userInfo.Gender,
                            Country    = userInfo.Country,
                            Province   = userInfo.Province,
                            City       = userInfo.City,
                            AvatarUrl  = userInfo.AvatarUrl,
                            Language   = userInfo.Language,
                            ParentId   = parentId,
                            Createat   = DateTime.Now,
                            Assets     = new Assets()
                            {
                                TotalAssets     = 0,
                                AvailableAmount = 0,
                                TotalCommission = 0,
                                UpdateTime      = DateTime.Now,
                                Createat        = DateTime.Now
                            }
                        };
                        await _customerRepository.InsertAsync(customer);

                        if (parentId.HasValue)
                        {
                            await _mediator.Publish(new CustomerRelationEvent
                            {
                                ParentId   = request.ParentId,
                                ChildrenId = customer.Id
                            });
                        }
                    }
                    else
                    {
                        if (!customer.ParentId.HasValue && request.ParentId > 0)
                        {
                            var anyParent = await _customerRepository.Query().AnyAsync(e => e.Id == request.ParentId);

                            if (anyParent)
                            {
                                customer.ParentId = request.ParentId;
                                await _mediator.Publish(new CustomerRelationEvent
                                {
                                    ParentId   = request.ParentId,
                                    ChildrenId = customer.Id
                                });
                            }
                        }
                        if (customer.SessionKey != jsonResult.session_key)
                        {
                            customer.SessionKey = jsonResult.session_key;
                            await _customerRepository.UpdateProperyAsync(customer, nameof(customer.SessionKey), nameof(customer.ParentId));
                        }
                    }

                    List <Claim> claims = new List <Claim>();
                    claims.Add(new Claim("id", customer.Id.ToString()));
                    // claims.Add(new Claim("openId", customer.OpenId));

                    var token       = _tokenService.JwtToken(claims);
                    var customerRes = _mapper.Map <CustomerResponse>(customer);

                    return(Result.Ok(new WeChatLiteAppLoginResponse(token, customerRes)));
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }
            return(Result.Fail(ResultCodes.RequestParamError, errorMsg));
        }