コード例 #1
0
        public async Task <PaymentAuthorizationGuiResponse> ProcessResponse(
            PaymentProviderConfiguration configuration,
            NameValueCollection paramsCollection,
            ResponseParameters additionalParameters)
        {
            string paramsDesc = PaymentFrameworkUtility.DescribeNameValueCollection(paramsCollection);

            this.Logger.CreateEntry(typeof(CapitaPaymentProvider), LogLevel.Debug, $"ProcessResponse({paramsDesc})");

            string roundTripTransactionReference = paramsCollection[RoundTripTokenKey];

            if (String.IsNullOrEmpty(roundTripTransactionReference))
            {
                throw new InvalidOperationException($"response did not include required field '{RoundTripTokenKey}'");
            }

            Guid pendingPaymentRef = new Guid(roundTripTransactionReference);

            string paymentProviderTransactionReference = additionalParameters.ProviderReference;

            if (String.IsNullOrEmpty(paymentProviderTransactionReference))
            {
                throw new InvalidOperationException("response did not include required field \'PaymentProviderTransactionReference\'");
            }

            var backendResponse = await CheckAuthorizationInternal(configuration, pendingPaymentRef.ToString(), paymentProviderTransactionReference);

            return(new PaymentAuthorizationGuiResponse(backendResponse, null));
        }
コード例 #2
0
        public ActionResult SendToPaymentProvider(
            PaymentProviderConfiguration configuration,
            GeneralisedPaymentTransfer transferObject,
            Action <PaymentProviderConfiguration, GeneralisedPaymentTransfer, string> saveProviderReference)
        {
            var civicaXfer = new CivicaPaymentTransfer()
            {
                ProviderUrl          = Shared.Civica.Default.CivicaPostUrl,
                ReturnUrl            = transferObject.ReturnUrl,
                CallingApplicationId = Shared.Civica.Default.CivicaAppId,
                CallingApplicationTransactionReference = transferObject.TransactionId,
                GeneralLedgerCode = $"{transferObject.GeneralLedgerCode}-{transferObject.ProductId}",
                //PaymentSourceCode = transferObject.PaymentSourceCode,
                PaymentSourceCode = transferObject.IsMediated ? "02" : "01",
                PaymentTotal      = transferObject.Amount,
                PaymentLines      = new List <string>()
            };

            foreach (var item in transferObject.LineItems)
            {
                civicaXfer.PaymentLines.Add(FormatPaymentLine(item));
            }
            var resultView = PaymentFrameworkUtility.CreateView("~/Views/Payment/SendToCivica.cshtml", civicaXfer);

            var sendToPaymentLogMessage = PaymentFrameworkUtility.DescribeActionResultForLogging(resultView, true);

            this.Logger.CreateEntry(typeof(CivicaPaymentProvider), LogLevel.Info, sendToPaymentLogMessage);
            return(resultView);
        }
コード例 #3
0
        public ActionResult ProcessPayment(FormCollection form)
        {
            string requestId = _paymentProvider.GenerateUniqueIdentifier();

            this.Session["RequestId"] = requestId;


            var xfer = new GeneralisedPaymentTransfer()
            {
                Amount        = decimal.Parse(form["Amount"]), // -> "AMOUNT"
                ReturnUrl     = "http://localhost:59412" + Url.Action("ProviderCallback", "Capita"),
                TransactionId = requestId
            };

            PaymentProviderConfiguration providerConfig = new PaymentProviderConfiguration()
            {
                AccountIdentifer = this._capitaMerchantid,
                SharedSecret     = this._capitaSecretKey,
                SubAccountNumber = this._capitaScpid
            };

            xfer.Account           = this._capitaScpid;
            xfer.VariableReference = "164 Wandsworth Borough Council";
            xfer.Comment1          = "Activity : After school club";
            xfer.Comment2          = "PS56789/456";
            xfer.CustomerNumber    = "50939";
            xfer.GeneralLedgerCode = "WE333292049,WE330192071,WE333592049,WE333792049";
            xfer.IsMediated        = false;
            xfer.ProductId         = "56789";
            //xfer.VatCode = CapitaVatCode.StandardRate;
            //xfer.VatRate = 20;
            xfer.VatCode = CapitaVatCode.ZeroRate;
            xfer.VatRate = 0;
            //xfer.SaveCard = new SaveCard()
            //{
            //    PayerReference = "s12u34"
            //};
            xfer.LineItems = new System.Collections.Generic.List <CivicaLineItem>()
            {
                new CivicaLineItem()
                {
                    Amount    = decimal.Parse(form["Amount"]),
                    FundCode  = "16",
                    Narrative = "Play Service booking MULTI_153997_112816_138579",
                    Reference = "56789"
                }
            };

            var result = _paymentProvider.SendToPaymentProvider(providerConfig, xfer, SaveProviderReference);

            string rawHtml = PaymentFrameworkUtility.DescribeActionResultForLogging(result);

            System.Diagnostics.Trace.WriteLine(rawHtml);
            System.Diagnostics.Trace.WriteLine("Provider Reference: " + this.Session["ProviderReference"]);

            return(result);
        }
コード例 #4
0
        public void TestSendToRealexNoSaveCard()
        {
            RealExPaymentProvider realexInstance = new RealExPaymentProvider(new TraceWriterLogAdapter());

            Assert.AreEqual(ProviderType.Realex, realexInstance.ProviderType);

            var scenario = new
            {
                SimulateAt     = new DateTime(2016, 02, 03, 10, 34, 21),
                providerConfig = new PaymentProviderConfiguration()
                {
                    AccountIdentifer = "test-id",
                    SharedSecret     = "test-secret"
                },
                PaymentTransfer = new GeneralisedPaymentTransfer()
                {
                    Account           = "test-account",
                    Amount            = 234.56m,
                    Comment1          = "Hello [World] this is a test!",
                    Comment2          = "** some \"unusual<b>tokens</b>'\\ /etc..",
                    CustomerNumber    = "1x2x345",
                    ProductId         = "PS-a/b\\3",
                    ReturnUrl         = "http://unit.localtest.me/something",
                    SaveCard          = null,
                    TransactionId     = "A453F8F7-E5DD-473F-B555-33839CA44C63",
                    VariableReference = "Another ref"
                }
            };

            var xferResult = realexInstance.SendToPaymentProvider(scenario.providerConfig, scenario.PaymentTransfer, scenario.SimulateAt);

            string generatedHtml = PaymentFrameworkUtility.DescribeActionResultForLogging(xferResult, true);

            string expectedHtml =
                "<form action=\"http://localhost:2437/Realex/epage.cgi.aspx\" method=\"post\" name=\"paymentForm\"> " +
                "<input type=\"hidden\" name=\"MERCHANT_RESPONSE_URL\" value=\"http://unit.localtest.me/something\" /> " +
                "<input type=\"hidden\" name=\"MERCHANT_ID\" value=\"test-id\" /> " +
                "<input type=\"hidden\" name=\"ORDER_ID\" value=\"A453F8F7-E5DD-473F-B555-33839CA44C63\" /> " +
                "<input type=\"hidden\" name=\"AMOUNT\" value=\"23456\" /> " +
                "<input type=\"hidden\" name=\"CURRENCY\" value=\"GBP\" /> " +
                "<input type=\"hidden\" name=\"TIMESTAMP\" value=\"20160203103421\" /> " +
                "<input type=\"hidden\" name=\"SHA1HASH\" value=\"a1134e0c769e30844dd1941c446c9eafe6f78026\" /> " +
                "<input type=\"hidden\" name=\"ACCOUNT\" value=\"test-account\" /> " +
                "<input type=\"hidden\" name=\"AUTO_SETTLE_FLAG\" value=\"1\" /> " +
                "<input type=\"hidden\" name=\"COMMENT1\" value=\"Hello [World] this is a test!\" /> " +
                "<input type=\"hidden\" name=\"COMMENT2\" value=\"** some &quot;unusualbtokens/b&#39;\\ /etc..\" /> " +
                "<input type=\"hidden\" name=\"CUST_NUM\" value=\"1x2x345\" /> " +
                "<input type=\"hidden\" name=\"VAR_REF\" value=\"Anotherref\" /> " +
                "<input type=\"hidden\" name=\"PROD_ID\" value=\"PSab3\" /> " +
                "</form> " +
                "<script type=\"text/javascript\"> document.forms['paymentForm'].submit(); </script>";

            Assert.AreEqual(expectedHtml, generatedHtml);
        }
コード例 #5
0
        public ActionResult SendToPaymentProvider(
            PaymentProviderConfiguration configuration,
            GeneralisedPaymentTransfer transferObject, DateTime nowLocalTime)
        {
            var realExXfer = new RealExPaymentTransfer()
            {
                MerchantId     = configuration.AccountIdentifer,
                OrderId        = transferObject.TransactionId,
                Amount         = (int)(transferObject.Amount * 100),
                ProviderUrl    = Shared.RealEx.Default.RealExPostUrl,
                ReturnUrl      = transferObject.ReturnUrl,
                Currency       = "GBP",
                Timestamp      = nowLocalTime.ToString("yyyyMMddHHmmss"),
                AutoSettleFlag = true
            };

            realExXfer.Account           = transferObject.Account;
            realExXfer.VariableReference = MessageContentUtility.TruncateAndStripDisallowed(transferObject.VariableReference, 50, RealexFields.RealexFieldVarRefDisallowRegex);
            realExXfer.CustomerNumber    = transferObject.CustomerNumber;
            realExXfer.ProductId         = MessageContentUtility.TruncateAndStripDisallowed(transferObject.ProductId, null, RealexFields.RealexFieldProductIdDisallowRegex);
            realExXfer.Comment1          = MessageContentUtility.TruncateAndStripDisallowed(transferObject.Comment1, 255, RealexFields.RealexFieldCommentDisallowRegex);
            realExXfer.Comment2          = MessageContentUtility.TruncateAndStripDisallowed(transferObject.Comment2, 255, RealexFields.RealexFieldCommentDisallowRegex);

            var fieldsForSignature = new List <string>();

            fieldsForSignature.Add(realExXfer.Timestamp);
            fieldsForSignature.Add(realExXfer.MerchantId);
            fieldsForSignature.Add(realExXfer.OrderId);
            fieldsForSignature.Add(realExXfer.Amount.ToString());
            fieldsForSignature.Add(realExXfer.Currency);

            if (transferObject.SaveCard != null)
            {
                realExXfer.HasSavedCard       = true;
                realExXfer.CardStorageEnabled = true;
                realExXfer.OfferSaveCard      = transferObject.SaveCard.OfferSaveCard;
                realExXfer.PaymentReference   = MessageContentUtility.TruncateAndStripDisallowed(transferObject.SaveCard.PaymentReference, 30, RealexFields.RealexFieldPaymentRefDisallowRegex);
                realExXfer.PayerReference     = MessageContentUtility.TruncateAndStripDisallowed(transferObject.SaveCard.PayerReference, 50, RealexFields.RealexFieldPayerRefDisallowRegex);
                realExXfer.PayerExists        = transferObject.SaveCard.PayerExists;
                fieldsForSignature.Add(realExXfer.PayerReference);
                fieldsForSignature.Add(realExXfer.PaymentReference);
            }

            realExXfer.Sha1Hash = CalculateRealexSignature(fieldsForSignature.ToArray(), configuration.SharedSecret);

            var resultView = PaymentFrameworkUtility.CreateView("~/Views/Payment/SendToRealEx.cshtml", realExXfer);

            var sendToPaymentLogMessage = PaymentFrameworkUtility.DescribeActionResultForLogging(resultView, true);

            this.Logger.CreateEntry(typeof(RealExPaymentProvider), LogLevel.Info, sendToPaymentLogMessage);
            return(resultView);
        }
コード例 #6
0
        public async Task <PaymentAuthorizationGuiResponse> ProcessResponse(
            PaymentProviderConfiguration configuration,
            NameValueCollection paramsCollection,
            ResponseParameters additionalParameters)
        {
            string paramsDesc = PaymentFrameworkUtility.DescribeNameValueCollection(paramsCollection);

            Logger.CreateEntry(typeof(CivicaPaymentProvider), LogLevel.Debug, $"ProcessResponse({paramsDesc})");

            string responseCode = paramsCollection["ResponseCode"] ?? "-1";

            int  responseCodeParsed = -1;
            bool didParse           = Int32.TryParse(responseCode, out responseCodeParsed);

            if (didParse && (0 == responseCodeParsed))
            {
                string roundTripTransactionReference = paramsCollection["CallingApplicationTransactionReference"];
                if (String.IsNullOrEmpty(roundTripTransactionReference))
                {
                    throw new InvalidOperationException(String.Format("response did not include required field '{0}'",
                                                                      "CallingApplicationTransactionReference"));
                }

                Guid pendingPaymentRef = new Guid(roundTripTransactionReference);

                var backendResponse = await CheckAuthorizationInternal(configuration, pendingPaymentRef.ToString());

                backendResponse.ResponseCode  = responseCode;
                backendResponse.TransactionId = roundTripTransactionReference;
                return(new PaymentAuthorizationGuiResponse(backendResponse, null));
            }
            else
            {
                var backendResponse = new PaymentAuthorizationResponse(false, PaymentAuthorizationResult.Declined,
                                                                       !string.IsNullOrEmpty(paramsCollection["PaymentAmount"]) ? decimal.Parse(paramsCollection["PaymentAmount"]) : 0.00m,
                                                                       paramsCollection["ResponseDescription"],
                                                                       paramsCollection["IncomeManagementReceiptNumber"])
                {
                    ResponseCode  = responseCode,
                    TransactionId = paramsCollection["CallingApplicationTransactionReference"]
                };
                return(new PaymentAuthorizationGuiResponse(backendResponse, null));
            }
        }
コード例 #7
0
        public ActionResult ProcessPayment(FormCollection form)
        {
            var xfer = new GeneralisedPaymentTransfer()
            {
                Amount            = decimal.Parse(form["Amount"]),               // -> "AMOUNT"
                ReturnUrl         = "http://localhost:59412" + Url.Action("ProviderCallback", "Default"),
                TransactionId     = _paymentProvider.GenerateUniqueIdentifier(), // -> "ORDER_ID"
                GeneralLedgerCode = "SOMECIVICACODE"
            };

            PaymentProviderConfiguration providerConfig = new PaymentProviderConfiguration()
            {
                AccountIdentifer = _realExMerchantid,
                SharedSecret     = _realExSecretKey
            };

            xfer.Account           = "";
            xfer.VariableReference = "";
            xfer.Comment1          = "";
            xfer.Comment2          = "";
            xfer.LineItems.Add(new CivicaLineItem()
            {
                Reference = "LINEREF",
                Amount    = 10.00m,
                Narrative = "Stuff paid for",
                FundCode  = "FUND"
            });

            var result = _paymentProvider.SendToPaymentProvider(providerConfig, xfer, null);

            string rawHtml = PaymentFrameworkUtility.DescribeActionResultForLogging(result);

            System.Diagnostics.Trace.WriteLine(rawHtml);

            return(result);
        }
コード例 #8
0
        public Task <PaymentAuthorizationGuiResponse> ProcessResponse(
            PaymentProviderConfiguration configuration,
            NameValueCollection paramsCollection,
            ResponseParameters additionalParameters)
        {
            string timestamp         = paramsCollection[RealexFields.RealexFieldTimestamp];
            string merchantid        = paramsCollection[RealexFields.RealexFieldMerchantId];
            string orderid           = paramsCollection[RealexFields.RealexFieldOrderId];
            string authcode          = paramsCollection[RealexFields.RealexFieldAuthCode];
            string resultCode        = paramsCollection[RealexFields.RealexFieldResult];
            string textmsg           = paramsCollection[RealexFields.RealexFieldResponseTextMessage];
            string receiptNumber     = paramsCollection[RealexFields.RealexFieldPasRef];
            string responseSignature = paramsCollection[RealexFields.RealexFieldHashSignature];
            string amountString      = paramsCollection[RealexFields.RealexFieldAmount];

            string[] fieldsForResponseSignature = new string[]
            {
                timestamp,
                merchantid,
                orderid,
                resultCode,
                textmsg,
                receiptNumber, // PASREF
                authcode
            };
            string expectedResponseHash = CalculateRealexSignature(fieldsForResponseSignature, configuration.SharedSecret);

            decimal amount;

            if (decimal.TryParse(amountString, out amount))
            {
                amount = amount / 100m;
            }
            else
            {
                amount = 0;
            }

            if (expectedResponseHash != responseSignature)
            {
                PaymentAuthorizationResponse dummyBackendResponse = new PaymentAuthorizationResponse(false, PaymentAuthorizationResult.Unknown, amount,
                                                                                                     "incorrect SHA1HASH.", receiptNumber)
                {
                    ResponseCode  = resultCode,
                    TransactionId = orderid
                };
                return(Task.FromResult(new PaymentAuthorizationGuiResponse(dummyBackendResponse, null)));
            }

            PaymentAuthorizationResult isAuthorized = IsResponseCodeSuccess(resultCode) ? PaymentAuthorizationResult.Authorized : PaymentAuthorizationResult.Declined;

            var savedCardResponse = new SavedCardResponse();

            if (!string.IsNullOrEmpty(paramsCollection[RealVaultFields.ResponsePayerSetupResultCode]) && paramsCollection[RealVaultFields.ResponsePayerSetupResultCode] == "00")
            {
                savedCardResponse.NewCardholderSaved = true;
            }

            if (!string.IsNullOrEmpty(paramsCollection[RealVaultFields.ResponseSavedPayerRef]))
            {
                savedCardResponse.CardholderReference = paramsCollection[RealVaultFields.ResponseSavedPayerRef];
            }

            if (!string.IsNullOrEmpty(paramsCollection[RealVaultFields.ResponseSavedCardResultCode]))
            {
                if (IsResponseCodeSuccess(paramsCollection[RealVaultFields.ResponseSavedCardResultCode]))
                {
                    savedCardResponse.CardSaved     = true;
                    savedCardResponse.CardReference = paramsCollection[RealVaultFields.ResponseSavedCardRef];
                    savedCardResponse.CardDigits    = paramsCollection[RealVaultFields.ResponseMaskedCardDigits];
                    savedCardResponse.ExpiryDate    =
                        Utility.ParseExpiryDate(paramsCollection[RealVaultFields.ResponseSavedCardExpiryDate]);
                }
                else
                {
                    savedCardResponse.CardSaved      = false;
                    savedCardResponse.CardSaveStatus = paramsCollection[RealVaultFields.ResponseSavedCardResultMessage];
                }
            }

            PaymentAuthorizationResponse response = new PaymentAuthorizationResponse(
                IsResponseCodeSuccess(resultCode), isAuthorized, amount, textmsg, receiptNumber)
            {
                ResponseCode  = resultCode,
                TransactionId = orderid,
                SavedCard     = savedCardResponse
            };

            var realExResponse = new RealExServerResponse();

            StringBuilder displayText = new StringBuilder();

            if (!response.ResponseOk)
            {
                realExResponse.ImagePath         = additionalParameters.FailureImageUrl;
                realExResponse.ConfigDescription = "Payment failed";

                displayText.Append("There was an error while processing your payment.<br />Please contact <a href=\"mailto:[email protected]\">My Play Service Support</a><br />");

                displayText.AppendFormat($"ERROR DETAILS : {textmsg}");
            }
            else
            {
                // TODO: show AUTHCODE to user (a legal requirement?) and an absolute hyperlink back in to the ebooking application

                realExResponse.ConfigDescription = "Payment Success";

                displayText.AppendFormat($"Payment Reference Number = {response.ReceiptNumber}<br />");
                displayText.AppendFormat($"Amount Paid = {response.AmountAuthorized:c}<br />");
                displayText.AppendFormat("Booking Reference Number {0}<br />", additionalParameters.Reference);
                displayText.AppendFormat("A confirmation email will be sent shortly with all details and invoice");

                realExResponse.ImagePath = additionalParameters.SuccessImageUrl;
                realExResponse.AdditionalSuccessMessage = additionalParameters.AdditionalSuccessMessage;
            }
            realExResponse.MainResult = displayText.ToString();

            realExResponse.NextUrl = additionalParameters.NextUrl;

            PartialViewResult serverReply = PaymentFrameworkUtility.CreatePartialView("~/Views/Payment/ReplyToRealEx.cshtml", realExResponse);

            PaymentAuthorizationGuiResponse guiResponse = new PaymentAuthorizationGuiResponse(response, serverReply);

            return(Task.FromResult <PaymentAuthorizationGuiResponse>(guiResponse));
        }
コード例 #9
0
        public ActionResult SendToPaymentProvider(
            PaymentProviderConfiguration configuration,
            GeneralisedPaymentTransfer transferObject,
            Action <PaymentProviderConfiguration, GeneralisedPaymentTransfer, string> saveProviderReference)
        {
            int siteId;

            int.TryParse(configuration.AccountIdentifer, out siteId);

            int scpId;

            int.TryParse(transferObject.Account, out scpId);

            int    hmacKeyId;
            string hmacSecretKey;

            CapitaApiHelpers.GetHmacIdAndSecretKey(configuration.SharedSecret, out hmacKeyId, out hmacSecretKey);

            string returnUrl = $"{transferObject.ReturnUrl}?{RoundTripTokenKey}={transferObject.TransactionId}";

            CapitaInvokeRequest request = new CapitaInvokeRequest()
            {
                SiteId              = siteId,
                ScpId               = scpId,
                HmacKeyId           = hmacKeyId,
                HmacKey             = hmacSecretKey,
                UniqueReference     = transferObject.TransactionId,
                PurchaseId          = transferObject.ProductId,
                BookingRef          = transferObject.Comment2,
                PurchaseDescription = transferObject.Comment1,
                PaymentTotal        = (int)(transferObject.Amount * 100),
                ReturnUrl           = returnUrl,
                IntegraCode         = transferObject.GeneralLedgerCode,
                IsMediated          = transferObject.IsMediated,
                FundCode            = Shared.Capita.Default.FundCode,
                VatCode             = transferObject.VatCode,
                VatRate             = transferObject.VatRate
            };

            if (transferObject.SaveCard != null)
            {
                request.SaveCard     = true;
                request.CardHolderId = MessageContentUtility.TruncateAndStripDisallowed(transferObject.SaveCard.PayerReference, 50, null);
            }

            //Call Capita web service to set up the payment
            CapitaInvokeResponse response = InvokeRequest(request);

            if (response != null && !response.Error)
            {
                //call this action method to save scpReference into PendingPayment table
                saveProviderReference(configuration, transferObject, response.ScpReference);
                RedirectResult resultView = new RedirectResult(response.RedirectUrl, true);
                var            sendToPaymentLogMessage = PaymentFrameworkUtility.DescribeActionResultForLogging(resultView, true);
                this.Logger.CreateEntry(typeof(CapitaPaymentProvider), LogLevel.Info, sendToPaymentLogMessage);
                return(resultView);
            }
            else
            {
                string errorMessage = "Capita Server returns null response.";
                if (response != null)
                {
                    errorMessage += " " + response.ErrorMessage;
                }

                this.Logger.CreateEntry(typeof(CapitaPaymentProvider), LogLevel.Error, errorMessage);
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }