Example #1
0
        /// <summary>
        /// Start the paypal payment process. This should return a redirect url in the IPaymentResponse.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private IPaymentResponse BeginExpressCheckout(IPaymentRequest request)
        {
            var response = new PaymentResponse();
            try
            {
                SetExpressCheckoutRequestDetailsType reqDetails = new SetExpressCheckoutRequestDetailsType();

                reqDetails.ReturnURL = request.PaymentSuccessReturnUrl.ToString();
                reqDetails.CancelURL = request.PaymentCancelReturnUrl.ToString();
                reqDetails.NoShipping = "1";

                reqDetails.PaymentAction = PaymentActionCodeType.Sale;
                reqDetails.PaymentActionSpecified = true;
                reqDetails.AllowNote = "0";

                BillingAgreementDetailsType bADT = new BillingAgreementDetailsType()
                {
                    BillingAgreementDescription = string.Empty,
                    BillingType = BillingCodeType.RecurringPayments
                };

                reqDetails.BillingAgreementDetails = new BillingAgreementDetailsType[1];
                reqDetails.BillingAgreementDetails.SetValue(bADT, 0);

                reqDetails.OrderTotal = new BasicAmountType()
                {
                    currencyID = CurrencyCodeType.USD,
                    Value = request.Amount.ToString()
                };
                bADT.BillingAgreementDescription = request.Description;
                reqDetails.OrderDescription = bADT.BillingAgreementDescription;

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        Version = this._paymentGateway.APIVersion,
                        SetExpressCheckoutRequestDetails = reqDetails
                    }
                };

                SetExpressCheckoutResponseType paypalResp = BuildPayPalWebservice().SetExpressCheckout(req);

                if (paypalResp.Errors != null && paypalResp.Errors.Length > 0)
                {
                    response.IsSuccess = false;
                    response.Message = paypalResp.Errors[0].LongMessage;
                    return response;
                }

                response.RedirectUrl = string.Format("{0}?cmd=_express-checkout&useraction=commit&token={1}", response.RedirectUrl, paypalResp.Token);
                response.RedirectRequested = true;
            }
            catch (Exception ex)
            {
                response.Message = ex.ToString();
                response.IsSuccess = false;
            }
            return response;
        }
        public static void GetTransaction()
        {
            Console.WriteLine("Getting Transaction... ");

            Gateway beanstream = new Gateway()
            {
                MerchantId      = 300200578,
                PaymentsApiKey  = "4BaD82D9197b4cc4b70a221911eE9f70",
                ReportingApiKey = "4e6Ff318bee64EA391609de89aD4CF5d",
                ApiVersion      = "1"
            };

            PaymentResponse response = beanstream.Payments.MakePayment(
                new CardPaymentRequest {
                Amount      = 100.00M,
                OrderNumber = getRandomOrderId("test"),
                Card        = new Card {
                    Name        = "John Doe",
                    Number      = "5100000010001004",
                    ExpiryMonth = "12",
                    ExpiryYear  = "18",
                    Cvd         = "123"
                }
            }
                );

            beanstream.Payments.Void(response.TransactionId, 100);
            Transaction trans = beanstream.Reporting.GetTransaction(response.TransactionId);

            Console.WriteLine("Payment id: " + response.TransactionId + ", " + response.Message + "\n");

            Assert.IsNotEmpty(response.TransactionId);
            Assert.AreEqual("Approved", response.Message);
            Assert.AreEqual("P", response.TransType);
            Assert.NotNull(trans.Adjustments);
            Assert.AreEqual(1, trans.Adjustments.Count);

            // look for the void payment, there should only be one adjustment
            foreach (Adjustment adj in trans.Adjustments)
            {
                Assert.AreEqual("VP", adj.Type);
            }
        }
Example #3
0
        public void ItShouldHaveATransactionIdForASuccessfulCompletion()
        {
            // Arrange
            var webresult = new WebCommandResult <string> {
                Response = @"{""id"":""10000000""}"
            };

            _executer.Setup(e => e.ExecuteCommand(It.IsAny <ExecuteWebRequest>())).Returns(webresult);


            _bambora.WebCommandExecuter = _executer.Object;

            // Act
            PaymentResponse response = _bambora.Payments.PreAuthCompletion("0001", 100);


            // Assert
            Assert.AreEqual(response.TransactionId, "10000000");
        }
Example #4
0
        //private void SavePayment(int requestId)
        //{
        //      //Request.QueryString["referanceNo"];
        //        Payment paymentObj = new Payment();
        //        paymentObj.OrderId = Convert.ToInt32(Request.QueryString["orderId"]);
        //        paymentObj.Amount = 200;
        //        paymentObj.CardNumber = "123";

        //        paymentObj.Mode = 1;
        //        paymentObj.NameOnCard = "Rekha";
        //        paymentObj.TransactionNo = Request.QueryString["referanceNo"];
        //        paymentObj.IsActive = 1;
        //        paymentObj.PaymentDate = DateTime.Now;

        //        //Saving Payment
        //        //.DBAccess.KitchenOnMyPlate.Classes.OrderManagement.SavePayemt(paymentObj, requestId,);
        //}
        void OfflineOnly(PaymentResponse paymentResponse)
        {
            if (paymentResponse.PaymentDone == "0" && (paymentResponse.PaymentMethod == "11" || paymentResponse.PaymentMethod == "12" || paymentResponse.PaymentMethod == "13" || paymentResponse.PaymentMethod == "14"))//Off line only
            {
                if (CommanAction.GetSession() != null)
                {
                    var objtblUser = CommanAction.GetSession();
                    OrderManagement.SavePayemt(Convert.ToInt32(Request.QueryString["requestId"]), 0, Convert.ToInt32(paymentResponse.PaymentMethod), "", "", objtblUser.FirstName);
                }
                Session.Remove("OrderList");
                //Deleting cookies
                if (Request.Cookies["ORDERLIST"] != null)
                {
                    HttpCookie myCookie = new HttpCookie("ORDERLIST");
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                    Response.Cookies.Add(myCookie);
                }
            }
        }
        /// <summary>
        /// Maps the invoice pay response.
        /// </summary>
        /// <param name="paymentResponse">The payment response.</param>
        /// <returns></returns>
        public InvoicePayResponseModel MapInvoicePayResponse(PaymentResponse paymentResponse)
        {
            try
            {
                //     var payfortResponse = JsonConvert.DeserializeObject<PayfortCheckStatus>(pfResponse);
                var InvoicePayResponseModel = new InvoicePayResponseModel();

                InvoicePayResponseModel.IsValid       = paymentResponse.IsValid;
                InvoicePayResponseModel.ResponseCode  = paymentResponse.ResponseCode;
                InvoicePayResponseModel.PaymentLink   = paymentResponse.PaymentLink;
                InvoicePayResponseModel.PaymentLinkId = paymentResponse.PaymentLinkId;
                InvoicePayResponseModel.ResponseCode  = paymentResponse.ResponseCode;
                return(InvoicePayResponseModel);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Create_DataWithUnknownKey_ReturnsEmptyResponse()
        {
            var result = PaymentResponse.Create("foo=bar");

            Assert.IsNotNull(result);
            Assert.AreEqual(0m, result.Amount);
            Assert.AreEqual(null, result.AuthorisationId);
            Assert.AreEqual(null, result.CaptureDay);
            Assert.AreEqual(null, result.CaptureMode);
            Assert.AreEqual(CurrencyCode.Unknown, result.CurrencyCode);
            Assert.AreEqual(0, result.KeyVersion);
            Assert.AreEqual(null, result.MaskedPan);
            Assert.AreEqual(null, result.MerchantId);
            Assert.AreEqual(null, result.OrderId);
            Assert.AreEqual(PaymentBrand.Unknown, result.PaymentBrand);
            Assert.AreEqual((ResponseCode)0, result.Code);
            Assert.AreEqual(null, result.TransactionDateTime);
            Assert.AreEqual(null, result.TransactionReference);
        }
Example #7
0
        public void CanRetrieveSingleRefund()
        {
            // If: We create a payment
            PaymentResponse payment = this.CreatePayment();

            // We can only test this if you make the payment using the payment.Links.PaymentUrl property.
            // If you don't do this, this test will fail because we can only refund payments that have been paid
            Debugger.Break();
            RefundResponse refundResponse = this._refundClient.CreateRefundAsync(payment.Id).Result;

            // When: We attempt to retrieve this refund
            RefundResponse result = this._refundClient.GetRefundAsync(payment.Id, refundResponse.Id).Result;

            // Then
            Assert.IsNotNull(result);
            Assert.AreEqual(refundResponse.Id, result.Id);
            Assert.AreEqual(refundResponse.Payment.AmountRefunded, result.Payment.AmountRefunded);
            Assert.AreEqual(refundResponse.Payment.AmountRemaining, result.Payment.AmountRemaining);
        }
Example #8
0
        /// <summary>
        /// Process Cash and Cheque payments. This is a useful way to record a payment that
        /// you physically took.
        /// NOTE: You will need to have these payment options ACTIVATED by calling Beanstream
        /// support at 1-888-472-0811
        ///
        /// </summary>
        static void ProcessPhysicalPayments()
        {
            Console.WriteLine("Processing Cash Payment... ");

            Gateway beanstream = new Gateway()
            {
                MerchantId     = 300200578,
                PaymentsApiKey = "4BaD82D9197b4cc4b70a221911eE9f70",
                ApiVersion     = "1"
            };


            // process cash payment
            PaymentResponse response = beanstream.Payments.MakePayment(
                new CashPaymentRequest()
            {
                Amount      = 50.00,
                OrderNumber = getRandomOrderId("test")
            }
                );

            Console.WriteLine("Cash Payment id: " + response.TransactionId + ", " + response.Message + "\n");

            Assert.IsNotEmpty(response.TransactionId);
            Assert.AreEqual("Approved", response.Message);
            Assert.AreEqual("P", response.TransType);


            Console.WriteLine("Processing Cheque Payment... ");
            // process cheque payment
            response = beanstream.Payments.MakePayment(
                new ChequePaymentRequest()
            {
                Amount      = 30.00,
                OrderNumber = getRandomOrderId("test")
            }
                );
            Console.WriteLine("Cheque Payment id: " + response.TransactionId + ", " + response.Message + "\n");

            Assert.IsNotEmpty(response.TransactionId);
            Assert.AreEqual("Approved", response.Message);
            Assert.AreEqual("P", response.TransType);
        }
Example #9
0
        public async Task CanCreatePartialRefund()
        {
            // If: We create a payment of 250 euro
            PaymentResponse payment = await this.CreatePayment("250.00");

            // We can only test this if you make the payment using the payment.Links.PaymentUrl property.
            // If you don't do this, this test will fail because we can only refund payments that have been paid
            Debugger.Break();

            // When: We attempt to refund 50 euro
            RefundRequest refundRequest = new RefundRequest()
            {
                Amount = new Amount(Currency.EUR, "50.00")
            };
            RefundResponse refundResponse = await this._refundClient.CreateRefundAsync(payment.Id, refundRequest);

            // Then
            Assert.AreEqual("50.00", refundResponse.Amount.Value);
        }
        public void Should_process_GPWP_response_from_response_no_mock_with_certificate()
        {
            // Arrange
            const string merchantNumber             = "62346346";
            const string privateCertificateFile     = "certs/server.pfx";
            const string privateCertificatePassword = "******";
            const string publicCertificateFile      = "certs/server_pub.pem";
            const string publicCertificatePassword  = null;
            var          privateCert = new X509Certificate2(privateCertificateFile, privateCertificatePassword,
                                                            Encoding.DefaultKeyStorageFlags);
            var publicCert = new X509Certificate2(publicCertificateFile, publicCertificatePassword,
                                                  Encoding.DefaultKeyStorageFlags);

            var response = new PaymentResponse
            {
                Operation      = "Operation",
                OrderNumber    = 12332,
                MerOrderNumber = 0,
                PRCode         = 0,
                SRCode         = 0,
                ResultText     = "ResultText",
                UserParam1     = "UserParam1",
                AddInfo        = null
            };

            var encodingServiceMock = this.GetLoggerMock <EncodingService>();
            var encodingService     = new EncodingService(encodingServiceMock.Object);
            var prt = new PaymentResponseTransformer();

            var parameterString = prt.GetParameterString(response);

            response.Digest  = encodingService.SignData(parameterString, privateCert);
            response.Digest1 = encodingService.SignData($"{parameterString}|{merchantNumber}", privateCert);

            var clientServiceLoggerMock = this.GetLoggerMock <ClientService>();
            var testee = new ClientService(encodingService,
                                           new PaymentRequestTransformer(), new PaymentResponseTransformer(), clientServiceLoggerMock.Object);

            // Act
            // Assert
            testee.ProcessGPWebPayResponse(response, merchantNumber, publicCert);
        }
Example #11
0
        public override async Task <PaymentResponse> CreatePayment(PaymentRequest request, ServerCallContext context)
        {
            var response = new PaymentResponse()
            {
                Message        = "Ok",
                ResponseStatus = ResponseStatus.Successful,
                ReceivingTime  = Timestamp.FromDateTime(DateTime.UtcNow)
            };

            try
            {
                ValidateRequest(request);

                var transaction = new Transaction()
                {
                    TransactionType = (PublicEnums.TransactionType)request.TransactionType,
                    Amount          = request.Amount,
                    CurrencyType    = (PublicEnums.CurrencyType)request.CurrencyType,
                    Source          = request.Source
                };

                await _repository.AddTransactionAsync(transaction);

                await _repository.SaveAllAsync();

                _logger.LogInformation($"Transaction saved to db, transactionId: {transaction.TransactionId}");

                response.TransactionId = transaction.TransactionId;
            }
            catch (RpcException)
            {
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError($"Exception thrown during creation of payment transaction: {ex}");
                response.Message        = "Exception thrown during process";
                response.ResponseStatus = ResponseStatus.Failed;
            }

            return(response);
        }
Example #12
0
        public override string ProcessPaymentReturn(HttpContext context)
        {
            var orderid = Utils.RequestQueryStringParam(context, "orderid");

            var            objEventLog    = new EventLogController();
            PortalSettings portalsettings = new PortalSettings();

            var orderData = new OrderData(Convert.ToInt32(orderid));

            if (Utils.IsNumeric(orderid))
            {
                PaymentResponse paymentClientResult = ProviderUtils.GetOrderPaymentResponse(orderData, "OS_MolliePaymentProvider.ProcessPaymentReturn");

                objEventLog.AddLog("Mollie ProcessPaymentReturn", "Status: " + paymentClientResult.Status + " OrderId:" + orderid + " Mollie Id: " + orderData.PaymentPassKey, portalsettings, -1, EventLogController.EventLogType.ADMIN_ALERT);

                switch (paymentClientResult.Status.ToString().ToLower())
                {
                case "open":
                    //waiting for bank?
                    return(GetReturnTemplate(orderData, false, "Mollie Open"));

                case "paid":
                    return(GetReturnTemplate(orderData, true, ""));

                case "failed":
                    return(GetReturnTemplate(orderData, false, "Mollie failed"));

                case "canceled":
                    return(GetReturnTemplate(orderData, false, "Mollie canceled"));

                case "expired":
                    return(GetReturnTemplate(orderData, false, "Mollie expired"));

                default:
                    return(GetReturnTemplate(orderData, false, "Mollie failed"));
                }
            }
            else
            {
                return(GetReturnTemplate(orderData, false, "Mollie failed"));
            }
        }
Example #13
0
        public IPaymentResponse Parse(byte[] responseData)
        {
            PaymentResponse paymentResponse = new PaymentResponse();
            string responseString = Encoding.ASCII.GetString(responseData);

            if (string.IsNullOrEmpty(responseString))
            {
                paymentResponse.IsSuccess = false;
                paymentResponse.Message = "Transaction Response is empty";
                return paymentResponse;
            }

            Debug.WriteLine("Response String:\r\n" + responseString);

            string[] responseValues = responseString.Split(new char[] {'|'});

            //HACK: I am sometimes getting 69 fields back even though there should only be 68. For the time being I am just making sure I have ENOUGH fields.
            if (responseValues.Length < numberOfFieldsInVersionThreeOneResponse)
            {
                paymentResponse.IsSuccess = false;
                paymentResponse.Message = String.Format("Transaction Response is not in version 3.1 format it has {0}. It must have {1} fields.", responseValues.Length.ToString(), numberOfFieldsInVersionThreeOneResponse.ToString());
                //Return null instead of exceptioning. The issue is that it is possible the transaction happened fine, and if that is the case we will not log that transaction in the history table.
               // Diagnostic.FatalFormat("Transaction Response is not in version 3.1 format it has {0}. It must have {1} fields.", responseValues.Length.ToString(), numberOfFieldsInVersionThreeOneResponse.ToString());
                return null;
            }

            char encapsulatingCharacter = '\0';

            var responseInfo = new PaymentResponse
            {

                ResponseCode = GetResponseCode(responseValues[responseCodePosition].Trim(encapsulatingCharacter)),
                SubCode = GetResponseSubCode(responseValues[responseSubCodePosition].Trim(encapsulatingCharacter)),
                AuthorizationCode = responseValues[authorizationCodePosition].Trim(encapsulatingCharacter),
                TransactionId = responseValues[transactionIdPosition].Trim(encapsulatingCharacter),
                Message = responseValues[responseReasonTextPosition].Trim(encapsulatingCharacter)
            };

            // Process Return Values

            return (IPaymentResponse)responseInfo;
        }
Example #14
0
        static void ProcessVoids()
        {
            Console.WriteLine("Processing Voids... ");

            Gateway beanstream = new Gateway()
            {
                MerchantId     = 300200578,
                PaymentsApiKey = "4BaD82D9197b4cc4b70a221911eE9f70",
                ApiVersion     = "1"
            };

            // we make a payment first so we can void it
            PaymentResponse response = beanstream.Payments.MakePayment(
                new CardPaymentRequest {
                Amount      = 30.00,
                OrderNumber = getRandomOrderId("test"),
                Card        = new Card {
                    Name        = "John Doe",
                    Number      = "5100000010001004",
                    ExpiryMonth = "12",
                    ExpiryYear  = "18",
                    Cvd         = "123"
                }
            }
                );

            Console.WriteLine("Void Payment id: " + response.TransactionId);

            Assert.IsNotEmpty(response.TransactionId);
            Assert.AreEqual("Approved", response.Message);
            Assert.AreEqual("P", response.TransType);


            // void the purchase
            response = beanstream.Payments.Void(response.TransactionId, 30);              // void the $30 amount

            Console.WriteLine("Void result: " + response.TransactionId + ", " + response.Message + "\n");

            Assert.IsNotEmpty(response.TransactionId);
            Assert.AreEqual("Approved", response.Message);
            Assert.AreEqual("VP", response.TransType);
        }
Example #15
0
        public void ShouldReturnProcessedFailPaymentFromCache()
        {
            Guid           merchantPaymentRequestId = Guid.NewGuid();
            PaymentRequest request = GetValidPaymentRequest();

            request.MerchantPaymentRequestId = merchantPaymentRequestId;
            string message = "Insufficient Funds";

            var response = new TransactionResponse
            {
                Status  = false,
                Message = message
            };

            _bankClient.ProcessTransaction(Arg.Is <TransactionRequest>(x => x.CardNumber == request.CardNumber && x.Amount == request.Amount)).Returns(response);
            PaymentResponse        txResponse = _service.ProcessPayment(request);
            PaymentDetailsResponse details    = _service.GetPaymentDetails(_merchantId, txResponse.PaymentGatewayTxId);

            AssetProcessDetails(details, request, txResponse, merchantPaymentRequestId, Guid.Empty, false, message);
        }
        /// <summary>
        /// Retrieves the order details maintained for the payment gateway.
        /// </summary>
        /// <returns>return order data.</returns>
        private async Task <OrderViewModel> GetOrderDetails()
        {
            OrderViewModel orderFromPayment = null;

            try
            {
                PaymentResponse paymentResponse = await ApiCalls.GetPaymentDetails(paymentId).ConfigureAwait(false);

                if (paymentResponse != null && paymentResponse.Result.Count > 0)
                {
                    orderFromPayment = await GetOrderDetails(paymentResponse.Result[0].PostBackParam.Udf1, paymentResponse.Result[0].PostBackParam.ProductInformation, paymentResponse.Result[0].PostBackParam.Udf2).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                ParsePayUException(ex);
            }

            return(await Task.FromResult(orderFromPayment).ConfigureAwait(false));
        }
        public void Test02()
        {
            var objectToMap = new PaymentResponse
            {
                PaymentId          = new Guid("24b542a8-4825-4089-ace6-6c0ef8bd56a8"),
                IsRequestSucceeded = true
            };

            var expectedObject = new PaymentResponseDto
            {
                PaymentId          = new Guid("24b542a8-4825-4089-ace6-6c0ef8bd56a8"),
                IsRequestSucceeded = true
            };

            var mapper       = new PaymentResponseMapper();
            var mappedObject = mapper.Map(objectToMap);

            mappedObject.Should().NotBeNull();
            mappedObject.Should().BeEquivalentTo(expectedObject);
        }
Example #18
0
        public void PaymentResponseInits()
        {
            var methodName      = "credit";
            var details         = new { };
            var shippingAddress = GetShippingAddress();
            var shippingOption  = "ground";
            var payerEmail      = "*****@*****.**";
            var payerPhone      = "555-555-5555";

            var paymentResponse = new PaymentResponse(methodName, details, shippingAddress, shippingOption, payerEmail, payerPhone);

            Assert.NotNull(paymentResponse);
            Assert.IsType <PaymentResponse>(paymentResponse);
            Assert.Equal(methodName, paymentResponse.MethodName);
            Assert.Equal(details, paymentResponse.Details);
            Assert.Equal(shippingAddress, paymentResponse.ShippingAddress);
            Assert.Equal(shippingOption, paymentResponse.ShippingOption);
            Assert.Equal(payerEmail, paymentResponse.PayerEmail);
            Assert.Equal(payerPhone, paymentResponse.PayerPhone);
        }
Example #19
0
        public void CanCreateRecurringPaymentAndRetrieveIt()
        {
            // If: we create a new recurring payment
            string         customerId     = this.GetFirstValidMandate().CustomerId;
            PaymentRequest paymentRequest = new PaymentRequest()
            {
                Amount        = 100,
                Description   = "Description",
                RedirectUrl   = this.DefaultRedirectUrl,
                RecurringType = RecurringType.First,
                CustomerId    = customerId
            };

            // When: We send the payment request to Mollie and attempt to retrieve it
            PaymentResponse paymentResponse = this._paymentClient.CreatePaymentAsync(paymentRequest).Result;
            PaymentResponse result          = this._paymentClient.GetPaymentAsync(paymentResponse.Id).Result;

            // Then: Make sure the recurringtype parameter is entered
            Assert.AreEqual(RecurringType.First, result.RecurringType);
        }
Example #20
0
        public async Task CanCreateSpecificPaymentType(Type paymentType, PaymentMethods?paymentMethod, Type expectedResponseType)
        {
            // If: we create a specific payment type with some bank transfer specific values
            PaymentRequest paymentRequest = (PaymentRequest)Activator.CreateInstance(paymentType);

            paymentRequest.Amount      = 100;
            paymentRequest.Description = "Description";
            paymentRequest.RedirectUrl = fixture.DefaultRedirectUrl;
            paymentRequest.Method      = paymentMethod;

            // When: We send the payment request to Mollie
            PaymentResponse result = await fixture.PaymentClient.CreatePaymentAsync(paymentRequest);

            // Then: Make sure all requested parameters match the response parameter values
            Assert.NotNull(result);
            Assert.Equal(expectedResponseType, result.GetType());
            Assert.Equal(paymentRequest.Amount, result.Amount);
            Assert.Equal(paymentRequest.Description, result.Description);
            Assert.Equal(paymentRequest.RedirectUrl, result.Links.RedirectUrl);
        }
Example #21
0
        //Payment
        public PaymentResponse ExecutePayment(PaymentRequest request)
        {
            var response = new PaymentResponse();

            Type type = request.GetType();

            if (type.FullName == "BOA.Types.Banking.PaymentRequest")
            {
                var pr = new BOA.Process.Banking.Payment();
                if (request.MethodName == "AddPayment")
                {
                    response = pr.AddPayment((PaymentRequest)request);
                }
                else if (request.MethodName == "GetPayment")
                {
                    response = pr.GetPayment((PaymentRequest)request);
                }
            }
            return(response);
        }
Example #22
0
        public async Task CanCreateRefund()
        {
            // If: We create a payment
            string          amount  = "100.00";
            PaymentResponse payment = await this.CreatePayment(amount);

            // We can only test this if you make the payment using the payment.Links.Checkout property.
            // If you don't do this, this test will fail because we can only refund payments that have been paid
            Debugger.Break();

            // When: We attempt to refund this payment
            RefundRequest refundRequest = new RefundRequest()
            {
                Amount = new Amount(Currency.EUR, amount)
            };
            RefundResponse refundResponse = await this._refundClient.CreateRefundAsync(payment.Id, refundRequest);

            // Then
            Assert.IsNotNull(refundResponse);
        }
        public async Task CanGetPaymentActionMetadata()
        {
            PaymentRequest <CardSource> paymentRequest = TestHelper.CreateCardPaymentRequest();
            var metadata = new KeyValuePair <string, object>("test", "1234");

            paymentRequest.Metadata.Add(metadata.Key, metadata.Value);
            PaymentResponse paymentResponse = await _api.Payments.RequestAsync(paymentRequest);

            IEnumerable <PaymentAction> actionsResponse = await _api.Payments.GetActionsAsync(paymentResponse.Payment.Id);

            actionsResponse.ShouldNotBeNull();

            PaymentAction paymentAction = actionsResponse.FirstOrDefault();

            paymentAction.ShouldNotBeNull();
            paymentAction.Metadata.ShouldNotBeNull();
            paymentAction.Metadata.ShouldNotBeEmpty();
            paymentAction.Metadata.ShouldHaveSingleItem();
            paymentAction.Metadata.ShouldContain(d => d.Key == metadata.Key && d.Value.Equals(metadata.Value));
        }
Example #24
0
        /// <summary>
        /// Validates the response.
        /// </summary>
        /// <typeparam name="V"></typeparam>
        /// <typeparam name="E"></typeparam>
        /// <param name="restResponse">The rest response.</param>
        public static void ValidateResponse <V, E>(this IRestResponse <V, E> restResponse)
        {
            if (restResponse.Error != null)
            {
                if (restResponse.Error is SdkError)
                {
                    SdkError sdkError = restResponse.Error as SdkError;
                    RestResponseExtensionsUtils.FormatSdkError(sdkError);
                }
                if (restResponse.Error is PaymentResponse)
                {
                    PaymentResponse paymentResponse = restResponse.Error as PaymentResponse;

                    throw new PayUException(ErrorCode.INVALID_PARAMETERS,
                                            string.Format("{0} {1} {2}", paymentResponse.ResponseCode, paymentResponse.Error, paymentResponse.MessageError));
                }
            }

            RestResponseExtensionsUtils.ValidateResponseCommon(restResponse);
        }
Example #25
0
        public async Task CanCreateDefaultPaymentWithOnlyRequiredFields()
        {
            // When: we create a payment request with only the required parameters
            PaymentRequest paymentRequest = new PaymentRequest()
            {
                Amount      = new Amount(Currency.EUR, "100.00"),
                Description = "Description",
                RedirectUrl = this.DefaultRedirectUrl
            };

            // When: We send the payment request to Mollie
            PaymentResponse result = await this._paymentClient.CreatePaymentAsync(paymentRequest);

            // Then: Make sure we get a valid response
            Assert.IsNotNull(result);
            Assert.AreEqual(paymentRequest.Amount.Currency, result.Amount.Currency);
            Assert.AreEqual(paymentRequest.Amount.Value, result.Amount.Value);
            Assert.AreEqual(paymentRequest.Description, result.Description);
            Assert.AreEqual(paymentRequest.RedirectUrl, result.RedirectUrl);
        }
Example #26
0
        public async Task CanCreatePartialRefund()
        {
            // If: We create a payment of 250 euro
            PaymentResponse payment = await this.CreatePayment(250);

            // We can only test this if you make the payment using the payment.Links.PaymentUrl property.
            // If you don't do this, this test will fail because we can only refund payments that have been paid
            Debugger.Break();

            // When: We attempt to refund 50 euro
            RefundRequest refundRequest = new RefundRequest()
            {
                Amount = 50
            };
            RefundResponse refundResponse = await fixture.RefundClient.CreateRefundAsync(payment.Id, refundRequest);

            // Then
            Assert.Equal(50, refundResponse.Payment.AmountRefunded);
            Assert.Equal(200, refundResponse.Payment.AmountRemaining);
        }
Example #27
0
        public void CanCreatePaymentWithMandate()
        {
            // If: We create a payment with a mandate id
            MandateResponse validMandate   = this.GetFirstValidMandate();
            PaymentRequest  paymentRequest = new PaymentRequest()
            {
                Amount        = 100,
                Description   = "Description",
                RedirectUrl   = this.DefaultRedirectUrl,
                RecurringType = RecurringType.Recurring,
                CustomerId    = validMandate.CustomerId,
                MandateId     = validMandate.Id
            };

            // When: We send the payment request to Mollie
            PaymentResponse result = this._paymentClient.CreatePaymentAsync(paymentRequest).Result;

            // Then: Make sure we get the mandate id back in the details
            Assert.AreEqual(validMandate.Id, result.MandateId);
        }
Example #28
0
        public void SendWithErrorResponseInvalidCodeTest()
        {
            //get sample response XML
            PaymentResponse fromXmlResponse = new PaymentResponse().FromXml(Resources.payment_response_basic_error_sample);

            fromXmlResponse.Result = "invalid";

            //mock HttpResponse
            _handler.AddFakeResponse(HttpConfiguration.DEFAULT_ENDPOINT, new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(fromXmlResponse.ToXml())
            });

            //create empty request
            PaymentRequest request = new PaymentRequest();

            //create configuration
            HttpConfiguration httpConfiguration = new HttpConfiguration();

            //mock HttpCLient instance
            HttpClient httpClientMock = new HttpClient(_handler);


            //execute send on client
            RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpConfiguration, httpClientMock);

            bool correctExceptionThrown = false;

            try {
                realexClient.Send(request);
                Assert.Fail("RealexException should have been thrown before this point.");
            }
            catch (RealexServerException) {
                Assert.Fail("Incorrect exception thrown. Expected RealexException as result code is invalid.");
            }
            catch (RealexException) {
                correctExceptionThrown = true;
            }

            Assert.IsTrue(correctExceptionThrown, "Incorrect exception thrown.");
        }
Example #29
0
        public async Task <PaymentResponseDTO> GetPaymentByAcquirerRefrenceIdAsync(Guid acuirer_reference_id)
        {
            PaymentResponse paymentResponse = await _paymentResponseRepository.GetByAcquirerRefrenceIdAsync(acuirer_reference_id);

            PaymentResponseDTO paymentResponseDTO = _mapper.Map <PaymentResponseDTO>(paymentResponse);

            if (paymentResponse.Card_id != Guid.Empty)
            {
                Card card = await _cardService.RetrieveCardByIdAsync(paymentResponse.Card_id);

                if (card != null)
                {
                    CardResponseDTO cardResponseDTO = new CardResponseDTO(card.Number);
                    cardResponseDTO.Id           = card.Id;
                    cardResponseDTO.Expiry_Month = card.Expiry_Month;
                    cardResponseDTO.Expiry_Year  = card.Expiry_Year;
                    paymentResponseDTO.Card_Info = cardResponseDTO;
                }
            }
            return(paymentResponseDTO);
        }
Example #30
0
        private void SaveResponse(PaymentResponse resPonse, string aturianResponse, int reqId)
        {
            DbProvider _db = new DbProvider();

            try
            {
                _db.AddParameter("@requestId", reqId);
                _db.AddParameter("@transId", resPonse.transId);
                _db.AddParameter("@transResponse", JsonConvert.SerializeObject(resPonse));
                _db.AddParameter("@transStatus", resPonse.statusCode);
                _db.AddParameter("@message", resPonse.message);
                _db.AddParameter("@aturianResponse", aturianResponse);
                _db.ExecuteDataReader("SavePaymentResponse", CommandType.StoredProcedure);
            }
            catch
            {
            }
            finally
            {
            }
        }
Example #31
0
        public async Task CanCreateSpecificPaymentType(Type paymentType, PaymentMethod?paymentMethod, Type expectedResponseType)
        {
            // If: we create a specific payment type with some bank transfer specific values
            PaymentRequest paymentRequest = (PaymentRequest)Activator.CreateInstance(paymentType);

            paymentRequest.Amount      = new Amount(Currency.EUR, "100.00");
            paymentRequest.Description = "Description";
            paymentRequest.RedirectUrl = this.DefaultRedirectUrl;
            paymentRequest.Method      = paymentMethod;

            // When: We send the payment request to Mollie
            PaymentResponse result = await this._paymentClient.CreatePaymentAsync(paymentRequest);

            // Then: Make sure all requested parameters match the response parameter values
            Assert.IsNotNull(result);
            Assert.AreEqual(expectedResponseType, result.GetType());
            Assert.AreEqual(paymentRequest.Amount.Currency, result.Amount.Currency);
            Assert.AreEqual(paymentRequest.Amount.Value, result.Amount.Value);
            Assert.AreEqual(paymentRequest.Description, result.Description);
            Assert.AreEqual(paymentRequest.RedirectUrl, result.RedirectUrl);
        }
            public void SetUp()
            {
                _mockAcquirerClient = new Mock <IPaymentAcquirerClient>();

                _card = new Card("6923847329847", "0220", "123", "J Bloggs");

                _amount   = 101.12m;
                _currency = "GBP";

                _sut = new AcquirerService(_mockAcquirerClient.Object, new AcquirerStatusFactory());

                //setup for success by default
                _paymentResponse = new PaymentResponse
                {
                    Id      = Guid.NewGuid().ToString(),
                    Success = true
                };
                _mockAcquirerClient.Setup(x => x.SendAsync(It.IsAny <PaymentRequest>()))
                .Callback <PaymentRequest>(pr => _sentRequest = pr)
                .ReturnsAsync(_paymentResponse);
            }
Example #33
0
 public void UpdateTransaction(PaymentResponse response, string extra)
 {
     _customApplicationRepository.UpdateTransaction(response, extra);
 }
Example #34
0
        private IPaymentResponse EndExpressCheckout(IPaymentRequest request)
        {
            PaymentResponse response = new PaymentResponse ();

            GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq()
            {
                GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType()
                {
                    Version = this._paymentGateway.APIVersion,
                    Token = request.Token,
                }
            };

            // query PayPal for transaction details
            GetExpressCheckoutDetailsResponseType paypalResp = BuildPayPalWebservice().GetExpressCheckoutDetails(req);

            //handle error
            if (paypalResp.Errors != null && paypalResp.Errors.Length > 0)
            {
                response.IsSuccess = false;
                response.Message = paypalResp.Errors[0].LongMessage;
                return response;
            }

            GetExpressCheckoutDetailsResponseDetailsType respDetails = paypalResp.GetExpressCheckoutDetailsResponseDetails;

            PaymentDetailsType[] sPaymentDetails = new PaymentDetailsType[1];
            sPaymentDetails[0] = new PaymentDetailsType()
            {
                OrderTotal = new BasicAmountType()
                {
                    currencyID = respDetails.PaymentDetails.FirstOrDefault().OrderTotal.currencyID,
                    Value = respDetails.PaymentDetails.FirstOrDefault().OrderTotal.Value
                },
                /*must specify PaymentAction and PaymentActionSpecific, or it'll fail with PaymentAction : Required parameter missing (error code: 81115)*/
                PaymentAction = PaymentActionCodeType.Sale,
                // Recurring = RecurringFlagType.Y,
                PaymentActionSpecified = true

            };
            // prepare for commiting transaction
            DoExpressCheckoutPaymentReq payReq = new DoExpressCheckoutPaymentReq()
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType()
                {
                    Version = this._paymentGateway.APIVersion,
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType()
                    {
                        Token = paypalResp.GetExpressCheckoutDetailsResponseDetails.Token,
                        /*must specify PaymentAction and PaymentActionSpecific, or it'll fail with PaymentAction : Required parameter missing (error code: 81115)*/
                        PaymentAction = PaymentActionCodeType.Sale,
                        PaymentActionSpecified = true,
                        PayerID = paypalResp.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID,
                        PaymentDetails = sPaymentDetails
                    }
                }

            };

            // commit transaction and display results to user
            DoExpressCheckoutPaymentResponseType doResponse = BuildPayPalWebservice().DoExpressCheckoutPayment(payReq);
            try
            {
                //handle error
                if (paypalResp.Errors != null && paypalResp.Errors.Length > 0)
                {
                    response.IsSuccess = false;
                    response.Message = paypalResp.Errors[0].LongMessage;
                    return response;
                }
            }
            catch (Exception ex)
            {

            }

            if (!string.IsNullOrEmpty(doResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID) && doResponse.Ack == AckCodeType.Success)
            {

                response.TransactionId = doResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
            }
            else
            {
                response.IsSuccess = false;
                response.Message = "No Transaction id returned";
                return response;
            }

            // Create Recurring profile.

            var pp_response = CreateRecurringPaymentsProfile(paypalResp.GetExpressCheckoutDetailsResponseDetails.Token,
                                            respDetails.PaymentDetails.FirstOrDefault().OrderTotal,
                                            respDetails.PaymentDetails[0], request);

            string profileId = pp_response.CreateRecurringPaymentsProfileResponseDetails.ProfileID;

            return null;
        }
 private PaymentResponse PopulateResponse(XDocument xmlResponse)
 {
     var status = this.ExtractStatus(xmlResponse);
     var response = new PaymentResponse() {
         Status = status,
         Reason = xmlResponse.ToString()
     };
     response.PaymentId = ExtractPaymentId(xmlResponse);
     return(response);
 }
 private void PopulateResponseProperty(PaymentResponse response, string[] pair)
 {
     if (pair.Length != 2) throw (new ArgumentException("Token " + string.Join(",", pair) + " was not an array with exactly two elements", "pair"));
     switch (pair[0]) {
         case "Status":
             response.Status = ExtractStatus(pair);
             return;
         case "VPSTxId":
             response.PaymentId = pair[1];
             return;
     }
 }
 private PaymentResponse ParseResponse(string postResponse)
 {
     var response = new PaymentResponse {
         Reason = postResponse
     };
     foreach (var pair in Tokenize(postResponse)) {
         this.PopulateResponseProperty(response, pair);
     }
     return (response);
 }
        public void HandleActivityResult(int requestCode, Result resultCode, Intent data)
        {
            // TODO: What is this for?
            if(data == null)
            {
                return;
            }

            try
            {
                if (resultCode == Result.Ok)
                {
                    var paymentResponse = new PaymentResponse(data);

                    switch (paymentResponse.BillingStatus)
                    {
                        case MpUtils.MessageStatusBilled:
                            {
                                // Record what we purchased
                                this.UpdatePayment(paymentResponse);

                                // Let anyone know who is interested that purchase has completed
                                this.FireOnPurchaseProduct(paymentResponse.BillingStatus, null, string.Empty, string.Empty);

                                break;
                            }
                        case MpUtils.MessageStatusNotSent:
                        case MpUtils.MessageStatusFailed:
                            {
                                FortumoInAppService.SharedInstance.FireOnPurchaseProductError(paymentResponse.BillingStatus, string.Empty);
                                break;
                            }
                        case MpUtils.MessageStatusPending:
                            {
                                break;
                            }
                    }
                }
                else
                {
                    // Cancel
                    this.FireOnUserCanceled();
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception in HandleActivityResult: " + ex);
                this.FireOnPurchaseProductError(-1, string.Empty);
            }
        }
 public void UpdatePayment(PaymentResponse paymentResponse)
 {
     var simsipProductId = this.FortumoToSimsipProductId(paymentResponse.ServiceId);
     var newPurchase = new InAppPurchase
     {
         OrderId = paymentResponse.PaymentCode,
         ProductId = simsipProductId,
         PurchaseTime = DateTime.Now
     };
     App.ViewModel.Purchases.Add(newPurchase);
 }
        public override void OnReceive(Context context, Intent data)
        {
            // TODO: What is this for?
            if(data == null)
            {
                return;
            }

            // To be safe we create a local instance of InappSevice as we are not sure
            // what is avialable when this is called. For instance, app might not be running
            // when this is called.
            var inAppService = new FortumoInAppService();

            try
            {
                // TODO: can we use PaymentResponse(Intent)?
                var paymentResponse = new PaymentResponse(data);

                /*
                Bundle extras = intent.Extras;

                int billingStatus = extras.GetInt("billing_status");
                var creditAmount = extras.GetString("credit_amount");
                var creditName = extras.GetString("credit_name");
                var messageId = extras.GetString("message_id");
                var paymentCode = extras.GetString("payment_code");
                var priceAmount = extras.GetString("price_amount");
                var priceCurrency = extras.GetString("price_currency");
                var productName = extras.GetString("product_name");
                var serviceId = extras.GetString("service_id");
                var userId = extras.GetString("user_id");

                 var simsipProductId = InappService.SharedInstance.FortumoToSimsipProductId(serviceId);
                 */

                switch (paymentResponse.BillingStatus)
                {
                    case MpUtils.MessageStatusBilled:
                        {
                            // Record what we purchased
                            inAppService.UpdatePayment(paymentResponse);

                            /*
                            var inAppPurchaseRepository = new InAppPurchaseRepository();

                            var existingPurchase = inAppPurchaseRepository.GetPurchaseByProductId(simsipProductId);

                            if (existingPurchase == null)
                            {
                                var newPurchase = new InAppPurchaseEntity
                                {
                                    OrderId = paymentCode,
                                    ProductId = simsipProductId,
                                    PurchaseTime = DateTime.Now
                                };

                                inAppPurchaseRepository.Create(newPurchase);
                            }
                            else
                            {
                                existingPurchase.OrderId = paymentCode;
                                existingPurchase.ProductId = simsipProductId;
                                existingPurchase.PurchaseTime = DateTime.Now;

                                inAppPurchaseRepository.Update(existingPurchase);
                            }
                            */

                            // Let anyone know who is interested that purchase has completed
                            inAppService.FireOnPurchaseProduct(paymentResponse.BillingStatus, null, string.Empty, string.Empty);

                            break;
                        }
                    case MpUtils.MessageStatusNotSent:
                    case MpUtils.MessageStatusFailed:
                        {
                            inAppService.FireOnPurchaseProductError(paymentResponse.BillingStatus, string.Empty);
                            break;
                        }
                    case MpUtils.MessageStatusPending:
                        {
                            break;
                        }
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception in OnReceive: " + ex);
                inAppService.FireOnPurchaseProductError(-1, string.Empty);
            }
        }