Exemplo n.º 1
0
        /// <inheritdoc />
        public override async Task <IPaymentRefundResult> RefundAsync(VerifyContext context, Money amount, CancellationToken cancellationToken = default)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (amount == null)
            {
                throw new ArgumentNullException(nameof(amount));
            }

            var account = await GetAccountAsync(context.Payment).ConfigureAwaitFalse();

            var data = PasargadHelper.CreateRefundData(context, amount, account);

            var responseMessage = await _httpClient.PostFormAsync(
                PasargadHelper.RefundPaymentPageUrl,
                data,
                cancellationToken)
                                  .ConfigureAwaitFalse();

            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwaitFalse();

            return(PasargadHelper.CreateRefundResult(response, _messageOptions.Value));
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        public override async Task <IPaymentVerifyResult> VerifyAsync(VerifyContext context, CancellationToken cancellationToken = default)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var callbackResult = ParsianHelper.CreateCallbackResult(context, _httpContextAccessor.HttpContext.Request, _messageOptions.Value);

            if (!callbackResult.IsSucceed)
            {
                return(callbackResult.Result);
            }

            var account = await GetAccountAsync(context.Payment).ConfigureAwaitFalse();

            var data = ParsianHelper.CreateVerifyData(account, callbackResult);

            var responseMessage = await _httpClient
                                  .PostXmlAsync(ParsianHelper.VerifyServiceUrl, data, cancellationToken)
                                  .ConfigureAwaitFalse();

            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwaitFalse();

            return(ParsianHelper.CreateVerifyResult(response, callbackResult, _messageOptions.Value));
        }
Exemplo n.º 3
0
        public static string CreateRefundData(ParsianGatewayAccount account, VerifyContext context, Money amount)
        {
            var transaction = context.Transactions.SingleOrDefault(item => item.Type == TransactionType.Verify);

            if (transaction == null)
            {
                throw new InvalidOperationException($"No transaction record found in database for payment with tracking number {context.Payment.TrackingNumber}.");
            }

            if (!AdditionalDataConverter.ToDictionary(transaction).TryGetValue("token", out var token))
            {
                throw new InvalidOperationException($"No token found in database for payment with tracking number {context.Payment.TrackingNumber}.");
            }

            return
                ("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:rev=\"https://pec.Shaparak.ir/NewIPGServices/Reversal/ReversalService\">" +
                 "<soap:Header/>" +
                 "<soap:Body>" +
                 "<rev:ReversalRequest>" +
                 "<!--Optional:-->" +
                 "<rev:requestData>" +
                 "<!--Optional:-->" +
                 $"<rev:LoginAccount>{account.LoginAccount}</rev:LoginAccount>" +
                 $"<rev:Token>{token}</rev:Token>" +
                 "</rev:requestData>" +
                 "</rev:ReversalRequest>" +
                 "</soap:Body>" +
                 "</soap:Envelope>");
        }
Exemplo n.º 4
0
        public static IEnumerable <KeyValuePair <string, string> > CreateVerifyData(VerifyContext context, PasargadGatewayAccount account, PasargadCallbackResult callbackResult)
        {
            var timeStamp = GetTimeStamp(DateTime.Now);

            var dataToSign = string.Format("#{0}#{1}#{2}#{3}#{4}#{5}#",
                                           account.MerchantCode,
                                           account.TerminalCode,
                                           context.Payment.TrackingNumber,
                                           callbackResult.InvoiceDate,
                                           (long)context.Payment.Amount,
                                           timeStamp);

            var signData = SignData(account.PrivateKey, dataToSign);

            return(new[]
            {
                new KeyValuePair <string, string>("InvoiceNumber", context.Payment.TrackingNumber.ToString()),
                new KeyValuePair <string, string>("InvoiceDate", callbackResult.InvoiceDate),
                new KeyValuePair <string, string>("MerchantCode", account.MerchantCode),
                new KeyValuePair <string, string>("TerminalCode", account.TerminalCode),
                new KeyValuePair <string, string>("Amount", ((long)context.Payment.Amount).ToString()),
                new KeyValuePair <string, string>("TimeStamp", timeStamp),
                new KeyValuePair <string, string>("Sign", signData)
            });
        }
Exemplo n.º 5
0
        public static PaymentVerifyResult CreateVerifyResult(
            string webServiceResponse,
            VerifyContext context,
            IranKishCallbackResult callbackResult,
            MessagesOptions messagesOptions)
        {
            var result = XmlHelper.GetNodeValueFromXml(webServiceResponse, "KicccPaymentsVerificationResult");

            // The result object is actually the amount of invoice . It must equal to invoice's amount.
            if (!long.TryParse(result, out var numericResult))
            {
                return(new PaymentVerifyResult
                {
                    TrackingNumber = callbackResult.InvoiceNumber,
                    TransactionCode = callbackResult.ReferenceId,
                    IsSucceed = false,
                    Message = messagesOptions.InvalidDataReceivedFromGateway
                });
            }

            var isSuccess = numericResult != (long)context.Payment.Amount;

            var translatedMessage = isSuccess
                ? messagesOptions.PaymentSucceed
                : IranKishGatewayResultTranslator.Translate(result, messagesOptions);

            return(new PaymentVerifyResult
            {
                TrackingNumber = callbackResult.InvoiceNumber,
                TransactionCode = callbackResult.ReferenceId,
                IsSucceed = true,
                Message = translatedMessage
            });
        }
Exemplo n.º 6
0
 public static VerifyContext <bool> Assert(this VerifyContext <bool> context, string message)
 {
     if (!context.Value)
     {
         throw new ArgumentException(context.Format(message));
     }
     return(context);
 }
Exemplo n.º 7
0
 public static VerifyContext <T> Assert <T, TException>(this VerifyContext <T> context, Func <T, bool> assertOpr, string message)
 {
     if (!assertOpr(context.Value))
     {
         throw (Exception)Activator.CreateInstance(typeof(TException), context.Format(message));
     }
     return(context);
 }
Exemplo n.º 8
0
 public static VerifyContext <string> IsNotEmpty(this VerifyContext <string> context, string?message = null)
 {
     if (string.IsNullOrWhiteSpace(context.Value))
     {
         throw new ArgumentNullException(context.Format(message));
     }
     return(context);
 }
Exemplo n.º 9
0
 public static VerifyContext <T> Assert <T>(this VerifyContext <T> context, Func <T, bool> assertOpr, string message)
 {
     if (!assertOpr(context.Value))
     {
         throw new ArgumentException(context.Format(message));
     }
     return(context);
 }
Exemplo n.º 10
0
        public static IranKishCallbackResult CreateCallbackResult(
            VerifyContext context,
            IranKishGatewayAccount account,
            HttpRequest httpRequest,
            MessagesOptions messagesOptions)
        {
            httpRequest.TryGetParam("ResultCode", out var resultCode);
            httpRequest.Form.TryGetValue("Token", out var token);
            httpRequest.TryGetParam("MerchantId", out var merchantId);

            // Equals to TrackingNumber in Parbad system.
            httpRequest.TryGetParamAs <long>("InvoiceNumber", out var invoiceNumber);

            // Equals to TransactionCode in Parbad system.
            httpRequest.TryGetParam("ReferenceId", out var referenceId);

            var isSucceed = false;
            PaymentVerifyResult verifyResult = null;

            if (merchantId != account.MerchantId ||
                invoiceNumber != context.Payment.TrackingNumber ||
                token.IsNullOrEmpty())
            {
                verifyResult = new PaymentVerifyResult
                {
                    TrackingNumber  = invoiceNumber,
                    TransactionCode = referenceId,
                    IsSucceed       = false,
                    Message         = messagesOptions.InvalidDataReceivedFromGateway
                };
            }
            else
            {
                var translatedMessage = IranKishGatewayResultTranslator.Translate(resultCode, messagesOptions);

                isSucceed = resultCode == OkResult;

                if (!isSucceed)
                {
                    verifyResult = new PaymentVerifyResult
                    {
                        TrackingNumber  = invoiceNumber,
                        TransactionCode = referenceId,
                        IsSucceed       = false,
                        Message         = translatedMessage
                    };
                }
            }

            return(new IranKishCallbackResult
            {
                IsSucceed = isSucceed,
                Token = token,
                InvoiceNumber = invoiceNumber,
                ReferenceId = referenceId,
                Result = verifyResult
            });
        }
Exemplo n.º 11
0
        public void GivenVerifyOnIntNullable_WhenNull_ShouldReturnVerifyContext()
        {
            int?intRoot = null;

            VerifyContext <int?> context = intRoot.Verify(nameof(intRoot));

            context.Should().NotBeNull();
            context.Name.Should().Be(nameof(intRoot));
            context.Value.Should().Be(intRoot);
        }
Exemplo n.º 12
0
        public void GivenVerifyOnInt_WhenBinded_ShouldReturnVerifyContext()
        {
            int intRoot = 10;

            VerifyContext <int> context = intRoot.Verify(nameof(intRoot));

            context.Should().NotBeNull();
            context.Name.Should().Be(nameof(intRoot));
            context.Value.Should().Be(intRoot);
        }
Exemplo n.º 13
0
        public void GivenVerifyOnNullString_WhenBinded_ShouldReturnVerifyContext()
        {
            string?root = null;

            VerifyContext <string?> context = root.Verify(nameof(root));

            context.Should().NotBeNull();
            context.Name.Should().Be(nameof(root));
            context.Value.Should().BeNull();
        }
Exemplo n.º 14
0
        public void GivenVerifyOnString_WhenBinded_ShouldReturnVerifyContext()
        {
            string root = "This is a test";

            VerifyContext <string> context = root.Verify(nameof(root));

            context.Should().NotBeNull();
            context.Name.Should().Be(nameof(root));
            context.Value.Should().Be(root);
        }
Exemplo n.º 15
0
        public static VerifyContext <T> IsNotNull <T>(this VerifyContext <T> context, string?message = null)
        {
#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter.
            if (EqualityComparer <T> .Default.Equals(context.Value, default))
            {
                throw new ArgumentNullException(context.Format(message));
            }
#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter.

            return(context);
        }
Exemplo n.º 16
0
 public static string CreateRefundData(VerifyContext context, Money amount, SamanGatewayAccount account)
 {
     return
         ("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:Foo\">" +
          "<soapenv:Header/>" +
          "<soapenv:Body>" +
          "<urn:reverseTransaction soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
          $"<String_1 xsi:type=\"xsd:string\">{context.Payment.TransactionCode}</String_1>" +
          $"<String_2 xsi:type=\"xsd:string\">{(long)amount}</String_2>" +
          $"<Username xsi:type=\"xsd:string\">{account.MerchantId}</Username>" +
          $"<Password xsi:type=\"xsd:string\">{account.Password}</Password>" +
          "</urn:reverseTransaction>" +
          "</soapenv:Body>" +
          "</soapenv:Envelope>");
 }
Exemplo n.º 17
0
        public static ParsianCallbackResult CreateCallbackResult(VerifyContext context, HttpRequest httpRequest, MessagesOptions messagesOptions)
        {
            httpRequest.Form.TryGetValue("token", out var token);
            httpRequest.Form.TryGetValue("status", out var status);
            httpRequest.Form.TryGetValue("orderId", out var orderId);
            httpRequest.Form.TryGetValue("amount", out var amount);
            httpRequest.Form.TryGetValue("RRN", out var rrn);

            var isSucceed = !status.IsNullOrEmpty() &&
                            status == "0" &&
                            !token.IsNullOrEmpty();

            string message = null;

            if (isSucceed)
            {
                if (rrn.IsNullOrEmpty() ||
                    amount.IsNullOrEmpty() ||
                    orderId.IsNullOrEmpty() ||
                    !long.TryParse(orderId, out var numberOrderNumber) ||
                    !long.TryParse(amount, out var numberAmount) ||
                    numberOrderNumber != context.Payment.TrackingNumber ||
                    numberAmount != (long)context.Payment.Amount)
                {
                    isSucceed = false;
                    message   = messagesOptions.InvalidDataReceivedFromGateway;
                }
            }
            else
            {
                message = $"Error {status}";
            }

            PaymentVerifyResult verifyResult = null;

            if (!isSucceed)
            {
                verifyResult = PaymentVerifyResult.Failed(message);
            }

            return(new ParsianCallbackResult
            {
                IsSucceed = isSucceed,
                RRN = rrn,
                Result = verifyResult
            });
        }
Exemplo n.º 18
0
 public static string CreateRefundData(VerifyContext context, MellatGatewayAccount account)
 {
     return
         ("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:int=\"http://interfaces.core.sw.bps.com/\">" +
          "<soapenv:Header/>" +
          "<soapenv:Body>" +
          "<int:bpReversalRequest>" +
          $"<terminalId>{account.TerminalId}</terminalId>" +
          "<!--Optional:-->" +
          $"<userName>{account.UserName}</userName>" +
          "<!--Optional:-->" +
          $"<userPassword>{account.UserPassword}</userPassword>" +
          $"<orderId>{context.Payment.TrackingNumber}</orderId>" +
          $"<saleOrderId>{context.Payment.TrackingNumber}</saleOrderId>" +
          $"<saleReferenceId>{context.Payment.TransactionCode}</saleReferenceId>" +
          "</int:bpReversalRequest>" +
          "</soapenv:Body>" +
          "</soapenv:Envelope>");
 }
Exemplo n.º 19
0
        /// <inheritdoc />
        public override Task <IPaymentVerifyResult> VerifyAsync(VerifyContext context, CancellationToken cancellationToken = default)
        {
            if (!_httpContextAccessor.HttpContext.Request.TryGetParam("Result", out var result))
            {
                return(PaymentVerifyResult.Failed(_messageOptions.Value.InvalidDataReceivedFromGateway).ToInterfaceAsync());
            }

            _httpContextAccessor.HttpContext.Request.TryGetParam("TransactionCode", out var transactionCode);

            var isSucceed = result.Equals("true", StringComparison.OrdinalIgnoreCase);

            var message = isSucceed ? _messageOptions.Value.PaymentSucceed : _messageOptions.Value.PaymentFailed;

            return(new PaymentVerifyResult
            {
                IsSucceed = isSucceed,
                TransactionCode = transactionCode,
                Message = message
            }.ToInterfaceAsync());
        }
Exemplo n.º 20
0
        /// <inheritdoc />
        public override async Task <IPaymentVerifyResult> VerifyAsync(VerifyContext context, CancellationToken cancellationToken = default)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var callbackResult = MellatHelper.CrateCallbackResult(_httpContextAccessor.HttpContext.Request, _messagesOptions.Value);

            if (!callbackResult.IsSucceed)
            {
                return(callbackResult.Result);
            }

            var account = await GetAccountAsync(context.Payment).ConfigureAwaitFalse();

            var data = MellatHelper.CreateVerifyData(context, account, callbackResult);

            var responseMessage = await _httpClient
                                  .PostXmlAsync(MellatHelper.GetWebServiceUrl(account.IsTestTerminal, context.Payment.Amount), data, cancellationToken)
                                  .ConfigureAwaitFalse();

            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwaitFalse();

            var verifyResult = MellatHelper.CheckVerifyResult(response, callbackResult, _messagesOptions.Value);

            if (!verifyResult.IsSucceed)
            {
                return(verifyResult.Result);
            }

            data = MellatHelper.CreateSettleData(context, callbackResult, account);

            responseMessage = await _httpClient
                              .PostXmlAsync(MellatHelper.GetWebServiceUrl(account.IsTestTerminal, context.Payment.Amount), data, cancellationToken)
                              .ConfigureAwaitFalse();

            response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwaitFalse();

            return(MellatHelper.CreateSettleResult(response, callbackResult, _messagesOptions.Value));
        }
Exemplo n.º 21
0
        public static IEnumerable <KeyValuePair <string, string> > CreateRefundData(VerifyContext context, Money amount, PasargadGatewayAccount account)
        {
            var transactionRecord = context.Transactions.FirstOrDefault(transaction => transaction.Type == TransactionType.Request);

            if (transactionRecord == null)
            {
                throw new Exception($"Cannot find transaction record for Payment-{context.Payment.TrackingNumber}");
            }

            if (!AdditionalDataConverter.ToDictionary(transactionRecord).TryGetValue("invoiceDate", out var invoiceDate))
            {
                throw new Exception("Cannot get the invoiceDate from database.");
            }

            var timeStamp = GetTimeStamp(DateTime.Now);

            var dataToSign = string.Format("#{0}#{1}#{2}#{3}#{4}#{5}#{6}#",
                                           account.MerchantCode,
                                           account.TerminalCode,
                                           context.Payment.TrackingNumber,
                                           invoiceDate,
                                           (long)amount,
                                           RefundNumber,
                                           timeStamp);

            var signedData = SignData(account.PrivateKey, dataToSign);

            return(new[]
            {
                new KeyValuePair <string, string>("InvoiceNumber", context.Payment.TrackingNumber.ToString()),
                new KeyValuePair <string, string>("InvoiceDate", invoiceDate),
                new KeyValuePair <string, string>("MerchantCode", account.MerchantCode),
                new KeyValuePair <string, string>("TerminalCode", account.TerminalCode),
                new KeyValuePair <string, string>("Amount", amount.ToLongString()),
                new KeyValuePair <string, string>("action", RefundNumber),
                new KeyValuePair <string, string>("TimeStamp", timeStamp),
                new KeyValuePair <string, string>("Sign", signedData)
            });
        }
Exemplo n.º 22
0
        /// <inheritdoc />
        public override async Task <IPaymentRefundResult> RefundAsync(VerifyContext context, Money amount, CancellationToken cancellationToken = default)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (amount == null)
            {
                throw new ArgumentNullException(nameof(amount));
            }

            var account = await GetAccountAsync(context.Payment).ConfigureAwaitFalse();

            var data = MellatHelper.CreateRefundData(context, account);

            var responseMessage = await _httpClient
                                  .PostXmlAsync(MellatHelper.GetWebServiceUrl(account.IsTestTerminal, context.Payment.Amount), data, cancellationToken)
                                  .ConfigureAwaitFalse();

            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwaitFalse();

            return(MellatHelper.CreateRefundResult(response, _messagesOptions.Value));
        }
Exemplo n.º 23
0
        public static MelliCallbackResult CreateCallbackResult(VerifyContext context, HttpRequest httpRequest, MelliGatewayAccount account, MessagesOptions messagesOptions)
        {
            httpRequest.TryGetParamAs <int>("ResCode", out var apiResponseCode);

            if (apiResponseCode != SuccessCode)
            {
                return(new MelliCallbackResult
                {
                    IsSucceed = false,
                    Result = PaymentVerifyResult.Failed(messagesOptions.PaymentFailed)
                });
            }

            httpRequest.TryGetParam("Token", out var apiToken);
            httpRequest.TryGetParamAs <long>("OrderId", out var apiOrderId);

            if (apiOrderId != context.Payment.TrackingNumber)
            {
                return(new MelliCallbackResult
                {
                    IsSucceed = false,
                    Token = apiToken,
                    Result = PaymentVerifyResult.Failed(messagesOptions.InvalidDataReceivedFromGateway)
                });
            }

            var signedData = SignVerifyData(account.TerminalKey, apiToken);

            var dataToVerify = CreateVerifyObject(apiToken, signedData);

            return(new MelliCallbackResult
            {
                IsSucceed = true,
                Token = apiToken,
                JsonDataToVerify = dataToVerify
            });
        }
Exemplo n.º 24
0
        /// <inheritdoc />
        public override async Task <IPaymentVerifyResult> VerifyAsync(VerifyContext context, CancellationToken cancellationToken = default)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var account = await GetAccountAsync(context.Payment).ConfigureAwaitFalse();

            var data = MelliHelper.CreateCallbackResult(
                context,
                _httpContextAccessor.HttpContext.Request,
                account,
                _messageOptions.Value);

            if (!data.IsSucceed)
            {
                return(data.Result);
            }

            var result = await PostJsonAsync <MelliApiVerifyResult>(MelliHelper.ServiceVerifyUrl, data.JsonDataToVerify, cancellationToken).ConfigureAwaitFalse();

            return(MelliHelper.CreateVerifyResult(data.Token, result, _messageOptions.Value));
        }
Exemplo n.º 25
0
 public ProjectController(IOptionsMonitor <ApiConf> cfg, ProjectManagerContext context, VerifyContext verify)
 {
     this.cfg     = cfg.CurrentValue;
     this.context = context;
     this.verify  = verify;
 }
Exemplo n.º 26
0
 public VerifyController(VerifyContext context)
 {
     this.context = context;
 }
Exemplo n.º 27
0
 /// <inheritdoc />
 public override Task <IPaymentRefundResult> RefundAsync(VerifyContext context, Money amount, CancellationToken cancellationToken = default)
 {
     return(PaymentRefundResult.Failed(Resources.RefundNotSupports).ToInterfaceAsync());
 }
 /// <summary>
 /// Constructor. Our DbContext subclass is injected via the DI controller at runtime.
 /// </summary>
 /// <param name="verifyContext"></param>
 public PersonService(VerifyContext verifyContext)
 {
     _verifyContext = verifyContext;
 }
Exemplo n.º 29
0
        public static PaymentVerifyResult CreateVerifyResult(string webServiceResponse, VerifyContext context, SamanCallbackResult callbackResult, MessagesOptions messagesOptions)
        {
            var result = XmlHelper.GetNodeValueFromXml(webServiceResponse, "result");

            //  This result is actually: TotalAmount
            //  it must be equals to TotalAmount in database.
            var numericResult = Convert.ToInt64(result);

            var isSuccess = numericResult > 0 && numericResult == (long)context.Payment.Amount;

            var message = isSuccess
                ? messagesOptions.PaymentSucceed
                : SamanResultTranslator.Translate(numericResult, messagesOptions);

            return(new PaymentVerifyResult
            {
                IsSucceed = isSuccess,
                TransactionCode = callbackResult.TransactionId,
                Message = message
            });
        }
Exemplo n.º 30
0
 /// <inheritdoc />
 public abstract Task <IPaymentRefundResult> RefundAsync(VerifyContext context, Money amount, CancellationToken cancellationToken = default);