Exemple #1
0
        public PayStateDto ProcessPayment(PayRequestDto payReq)
        {
            PayStateDto pys = new PayStateDto();
            Random      rd  = new Random();
            int         res = rd.Next(0, 10);

            int [] array = new int[5] {
                2, 4, 6, 8, 10
            };
            if (array.Contains(res))
            {
                pys = new PayStateDto()
                {
                    PayState = PayStateEnum.Processed, PaymentStateDate = DateTime.Now
                };
            }
            else
            {
                pys = new PayStateDto()
                {
                    PayState = PayStateEnum.Failed, PaymentStateDate = DateTime.Now
                };
            }
            return(pys);
        }
Exemple #2
0
        public async Task <Result <PayResponseDto> > SendToPortal(PayRequestDto payRequestDto,
                                                                  CancellationToken cancellationToken)
        {
            var client = new RestClient(SendToPortalUrl);

            var request = new RestRequest {
                Method = Method.POST
            };

            request.AddParameter("application/json", JsonSerializer.Serialize(payRequestDto),
                                 ParameterType.RequestBody);

            var result = await client.ExecuteAsync(request, cancellationToken);

            var response = JsonSerializer.Deserialize <PayResponseDto>(result.Content);

            if (result.IsSuccessful == false)
            {
                return(Result <PayResponseDto> .Failed(response.errorMessage));
            }

            response.Url = $"{PortalUrl}/{response.token}";

            return(Result <PayResponseDto> .SuccessFul(response));
        }
Exemple #3
0
        public ActionResult Index(PayRequestDto payObj)
        {
            var respp = payProcess(payObj);

            TempData["msgDATA"] = respp.Result.StatusCode.ToString();
            return(RedirectToAction("index", "Home"));
        }
Exemple #4
0
 public HttpResponseMessage Post(PayRequestDto PayReq)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var payState    = ipay.ProcessPayment(PayReq);
             var payResponse = new PayResponseDto()
             {
                 IsProcessed = payState.PayState == PayStateEnum.Processed,
                 paystate    = payState
             };
             if (payResponse.IsProcessed)
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, payResponse));
             }
             else
             {
                 return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Payment could not be processed" }));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadGateway, ModelState));
         }
     }
     catch (Exception)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError));
     }
 }
        private PayStateDto ProcessPaymentStateDto(IPaymentGateway payGateway, PayRequestDto payReqDto, Payment payEntity)
        {
            var paymentSateDto = payGateway.ProcessPayment(payReqDto);
            var payStEntity    = new PaymentState()
            {
                Payment = payEntity, PayId = payEntity.PayId, CreatedDate = paymentSateDto.PaymentStateDate, State = paymentSateDto.PayState.ToString()
            };

            payStEntity = payStateRepo.Create(payStEntity);
            return(paymentSateDto);
        }
Exemple #6
0
        public static async Task <HttpResponseMessage> payProcess(PayRequestDto pay)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://localhost:3884/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = (HttpResponseMessage)client.PostAsJsonAsync("/api/values", pay).Result;

            return(response);
        }
        public void TestpayReqService(PayRequestDto payReqDto, PayStateDto cheapGateResDto, int cheapGateCount, PayStateDto expGateResponseDto, int ExpGateCount, PayStateEnum expPayStateEnum)
        {
            cheapPayGateway.Setup(c => c.ProcessPayment(payReqDto)).Returns(cheapGateResDto);
            expensivePayGateway.Setup(c => c.ProcessPayment(payReqDto)).Returns(expGateResponseDto);
            var payStateDto = PayReqService.ProcessPayment(payReqDto);

            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(payStateDto);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(payStateDto.PayState, expPayStateEnum);
            cheapPayGateway.Verify(c => c.ProcessPayment(payReqDto), Times.Exactly(cheapGateCount));
            expensivePayGateway.Verify(c => c.ProcessPayment(payReqDto), Times.Exactly(ExpGateCount));
        }
        /// <summary>
        /// 通联支付支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <AllinpayResponse> Pay(PayRequestDto request)
        {
            var req = new RequestPublic(_options.CusId, _options.AppId, request.Trxamt, request.Reqsn, request.PayType, _options.SignType);

            req.ValidTime = request.ValidTime;
            req.Body      = request.Body;
            req.Remark    = request.Remark;
            req.Acct      = request.Acct;
            if (!string.IsNullOrWhiteSpace(_options.AppKey))
            {
                req.AppKey = _options.AppKey;
            }
            if (!string.IsNullOrWhiteSpace(_options.NotifyUrl))
            {
                req.NotifyUrl = _options.NotifyUrl;
            }
            if (!string.IsNullOrWhiteSpace(_options.SubAppid))
            {
                req.SubAppid = _options.SubAppid;
            }
            if (!string.IsNullOrWhiteSpace(_options.Version))
            {
                req.Version = _options.Version;
            }
            var param = req.GetPublicParams();
            var res   = await _http.PostResponse <AllinpayResponse>(_options.ApiGateWay + payUrl, param);

            if (!string.IsNullOrWhiteSpace(res.Sign))
            {
                if (PayHelper.ValidSign(param, _options.AppKey, _options.SignType))
                {
                    return(await Task.FromResult <AllinpayResponse>(res));
                }
                else
                {
                    return(await Task.FromException <AllinpayResponse>(new Exception("验证签名失败")));
                }
            }
            else
            {
                return(await Task.FromResult <AllinpayResponse>(res));
            }
        }
        public async Task <IActionResult> PaySend(PayRequestDto payRequestDto)
        {
            var model = new GateApiReturn <PayResponseDto>
            {
                Status = true,
                Result = new PayResponseDto()
            };
            //Error
            var gateFromRepo = (await _db._GateRepository.GetAllAsync(p => p.Id == payRequestDto.Api, null, "Wallet")).SingleOrDefault();

            if (gateFromRepo == null)
            {
                errorModel.Messages.Clear();
                errorModel.Messages = new string[] { "Api درگاه معتبر نمیباشد" };
                return(BadRequest(errorModel));
            }
            //var userDocuments = await _db.DocumentRepository
            //    .GetManyAsync(p => p.Approve == 1 && p.UserId == gateFromRepo.Wallet.UserId, null, "");
            //if (!userDocuments.Any())
            //{
            //    errorModel.Messages.Clear();
            //    errorModel.Messages = new string[] { "مدارک کاربر صاحب درگاه تکمیل نمیباشد" };
            //    return BadRequest(errorModel);
            //}
            if (!gateFromRepo.IsActive)
            {
                errorModel.Messages.Clear();
                errorModel.Messages = new string[] { "این درگاه غیر فعال میباشد . درصورت نیاز با پشتیبانی در تماس باید" };
                return(BadRequest(errorModel));
            }
            if (gateFromRepo.IsIp)
            {
                var currentIp     = HttpContext.Connection.RemoteIpAddress.ToString(); //::1
                var gateWebsiteIp = await _utilities.GetDomainIpAsync(gateFromRepo.WebsiteUrl);

                if (currentIp != gateWebsiteIp)
                {
                    errorModel.Messages.Clear();
                    errorModel.Messages = new string[] { "آی پی وبسایت درخواست دهنده پرداخت معبتر نمیباشد" };
                    return(BadRequest(errorModel));
                }
            }
            //Success

            var factorToCreate = new Factor()
            {
                UserId             = gateFromRepo.Wallet.UserId,
                GateId             = gateFromRepo.Id,
                EnterMoneyWalletId = gateFromRepo.WalletId,

                UserName          = payRequestDto.UserName,
                Mobile            = payRequestDto.Mobile,
                Email             = payRequestDto.Email,
                FactorNumber      = payRequestDto.FactorNumber,
                Description       = payRequestDto.Description,
                ValidCardNumber   = payRequestDto.ValidCardNumber,
                RedirectUrl       = payRequestDto.RedirectUrl,
                Status            = false,
                Kind              = (int)FactorTypeEnums.Factor,
                Bank              = (int)BankEnums.ZarinPal,
                GiftCode          = "",
                IsGifted          = false,
                Price             = payRequestDto.Amount,
                EndPrice          = payRequestDto.Amount,
                RefBank           = "پرداختی انجام نشده است",
                IsAlreadyVerified = false,
                GatewayName       = "non",
                Message           = "خطای نامشخص"
            };

            await _dbFinancial.FactorRepository.InsertAsync(factorToCreate);

            if (await _dbFinancial.SaveAcync() > 0)
            {
                model.Messages.Clear();
                model.Messages           = new string[] { "بدون خطا" };
                model.Result.Token       = factorToCreate.Id;
                model.Result.RedirectUrl = $"{Request.Scheme ?? ""}://{Request.Host.Value.Replace("api.", "pay.") ?? ""}{Request.PathBase.Value ?? ""}" +
                                           "/bank/pay/" + factorToCreate.Id;
                return(Ok(model));
            }
            else
            {
                errorModel.Messages.Clear();
                errorModel.Messages = new string[] { "خطا در ثبت فاکتور" };
                return(BadRequest(errorModel));
            }
        }
        public PayStateDto ProcessPayment(PayRequestDto PayReqDto)
        {
            var payEntity = Mapper.Map <PayRequestDto, Payment>(PayReqDto);
            // payEntity = payRepo.Create(payEntity);
            var payStateEntity = new PaymentState()
            {
                Payment = payEntity, PayId = payEntity.PayId, CreatedDate = DateTime.Now, State = PayStateEnum.Pending.ToString()
            };

            payStateEntity = payStateRepo.Create(payStateEntity);
            if (PayReqDto.Amount <= 20)
            {
                var Paystdto = ProcessPaymentStateDto(cheapPayGateway, PayReqDto, payEntity);
                return(Paystdto);
            }
            else if (PayReqDto.Amount > 20 && PayReqDto.Amount <= 500)
            {
                PayStateDto PayStDto = new PayStateDto()
                {
                    PayState = PayStateEnum.Failed, PaymentStateDate = DateTime.Now
                };
                int counter = 1;
                try {
                    PayStDto = ProcessPaymentStateDto(expensivePayGateway, PayReqDto, payEntity);
                    if (PayStDto != null && PayStDto.PayState == PayStateEnum.Processed)
                    {
                        return(PayStDto);
                    }
                    else
                    {
                        counter++;
                        PayStDto = ProcessPaymentStateDto(cheapPayGateway, PayReqDto, payEntity);
                        return(PayStDto);
                    }
                }
                catch (Exception)
                {
                    if (counter == 0)
                    {
                        PayStDto = ProcessPaymentStateDto(cheapPayGateway, PayReqDto, payEntity);
                        return(PayStDto);
                    }
                }
                return(PayStDto);
            }
            else
            {
                int         counter  = 0;
                PayStateDto payStDto = new PayStateDto()
                {
                    PayState = PayStateEnum.Failed, PaymentStateDate = DateTime.Now
                };
                while (counter < 3)
                {
                    try
                    {
                        payStDto = ProcessPaymentStateDto(expensivePayGateway, PayReqDto, payEntity);
                        if (payStDto != null && payStDto.PayState == PayStateEnum.Processed)
                        {
                            return(payStDto);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    finally {
                        counter++;
                    }
                }
                return(payStDto);
            }
            throw new Exception("Payment could not be processed");
        }