public void CostEstimatesTest()
        {
            PayementStatusResponse actualResponse = paymentStatus.Get(PaymentStatusParams());

            string expectedResponse = TestHelper.GetJson(TestResource.ExpectedResponse + "paymentStatus.json");

            TestHelper.CompareProperties(expectedResponse, actualResponse.JsonResponse());

            PayementStatusResponse expectedObj = JsonConvert.DeserializeObject <PayementStatusResponse>(expectedResponse);
            PayementStatusResponse actualObj   = JsonConvert.DeserializeObject <PayementStatusResponse>(actualResponse.JsonResponse());

            TestHelper.PropertyValuesAreEquals(actualObj, expectedObj);
        }
Example #2
0
        public override void ProcessCallback(Payment payment)
        {
            var request = HttpContext.Current.Request;

            if (!IsValidCallback(payment.PaymentMethod))
            {
                string message = string.Format("Could not validate IPN from PayPal. TransactionId {0}. Request received {1} at {2}.", request["txn_id"], request.Form, request.RawUrl);
                LoggingService.Log <PayPalRecurringPaymentMethodService>(message);
                throw new SecurityException(message);
            }

            string transactParameter = request["subscr_id"];

            if (string.IsNullOrEmpty(transactParameter))
            {
                throw new ArgumentException(@"subscr_id must be present in query string.");
            }

            payment.TransactionId = transactParameter;

            bool isPendingAuth = payment.PaymentStatus.PaymentStatusId == (int)PaymentStatusCode.PendingAuthorization;

            if (isPendingAuth)
            {
                payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Acquired);
                ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            }

            payment.Save();
        }
        public void PaymentStatusCorrectionRequiredTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "78787878";
            try
            {
                var actualResponse = paymentStatus.Get(input);
            }
            catch (EligibleService.Exceptions.EligibleException ex)
            {
                Assert.IsNotNull(ex.EligibleError.EligibleId);
                Assert.IsNotNull(ex.EligibleError.CreatedAt);
                Assert.AreEqual("Y", ex.EligibleError.Error.ResponseCode);
                Assert.AreEqual("Yes", ex.EligibleError.Error.ResponseDescription);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierCode);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierDescription);
                Assert.AreEqual("E3", ex.EligibleError.Error.RejectReasonCode);
                Assert.AreEqual("Correction required - relational fields in error.", ex.EligibleError.Error.RejectReasonDescription);
                Assert.AreEqual("C", ex.EligibleError.Error.FollowUpActionCode);
                Assert.AreEqual("Please Correct and Resubmit", ex.EligibleError.Error.FollowUpActionDescription);
                string expected = "Missing or invalid information. Note: "
                                  + "At least one other status code is required to identify the missing or invalid information.";
                Assert.AreEqual(expected, ex.EligibleError.Error.Details);
                Assert.AreEqual(0, ex.EligibleError.KnownIssues.Count);
            }
        }
        /// <summary>
        /// Processed the callback received from the payment provider.
        /// </summary>
        /// <param name="payment">The payment.</param>
        public override void ProcessCallback(Payment payment)
        {
            if (payment.PaymentStatus.PaymentStatusId != (int)PaymentStatusCode.PendingAuthorization)
            {
                return;
            }

            int transactionid = GetTransactionIdFromHttpRequestThrowsExceptionIfNotInt();

            var paymentStatus = PaymentStatusCode.Authorized;

            if (payment.PaymentMethod.DynamicProperty <bool>().UseMd5)
            {
                var parameters = new Dictionary <string, string>();
                foreach (var key in HttpContext.Current.Request.QueryString.AllKeys.Where(x => x != "hash"))
                {
                    parameters.Add(key, HttpContext.Current.Request.QueryString[key]);
                }

                string md5Key           = payment.PaymentMethod.DynamicProperty <string>().Key;
                var    calculatedMd5Key = Md5Computer.GetPreMd5Key(parameters, md5Key);

                const string format = "When using md5 \"{0}\" cannot be null or empty.";
                var          md5ReceivedFromEPay = GetParameter("hash", format);

                if (!md5ReceivedFromEPay.Equals(calculatedMd5Key))
                {
                    paymentStatus = PaymentStatusCode.Declined;
                }
            }

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            payment.TransactionId = transactionid.ToString();
            ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
        }
        public void PaymentStatusExceptionTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "11111111";
            try
            {
                var actualResponse = paymentStatus.Get(input);
            }
            catch (EligibleService.Exceptions.EligibleException ex)
            {
                Assert.IsNotNull(ex.EligibleError.EligibleId);
                Assert.IsNotNull(ex.EligibleError.CreatedAt);
                Assert.AreEqual("Y", ex.EligibleError.Error.ResponseCode);
                Assert.AreEqual("Yes", ex.EligibleError.Error.ResponseDescription);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierCode);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierDescription);
                Assert.AreEqual("A4", ex.EligibleError.Error.RejectReasonCode);
                Assert.AreEqual("Acknowledgement/Not Found-The claim/encounter can not be found in the adjudication system.", ex.EligibleError.Error.RejectReasonDescription);
                Assert.AreEqual("C", ex.EligibleError.Error.FollowUpActionCode);
                Assert.AreEqual("Please Correct and Resubmit", ex.EligibleError.Error.FollowUpActionDescription);
                Assert.AreEqual("Cannot provide further status electronically.", ex.EligibleError.Error.Details);
                Assert.AreEqual(0, ex.EligibleError.KnownIssues.Count);
            }
        }
        public void PaymentStatusDataSearchUnsuccessfulTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "56565656";
            try
            {
                var actualResponse = paymentStatus.Get(input);
            }
            catch (EligibleService.Exceptions.EligibleException ex)
            {
                Assert.IsNotNull(ex.EligibleError.EligibleId);
                Assert.IsNotNull(ex.EligibleError.CreatedAt);
                Assert.AreEqual("Y", ex.EligibleError.Error.ResponseCode);
                Assert.AreEqual("Yes", ex.EligibleError.Error.ResponseDescription);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierCode);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierDescription);
                Assert.AreEqual("D0", ex.EligibleError.Error.RejectReasonCode);
                string expected = "Data Search Unsuccessful - The payer is unable to return status on the requested claim(s) "
                                  + "based on the submitted search criteria.";
                Assert.AreEqual(expected, ex.EligibleError.Error.RejectReasonDescription);
                Assert.AreEqual("C", ex.EligibleError.Error.FollowUpActionCode);
                Assert.AreEqual("Please Correct and Resubmit", ex.EligibleError.Error.FollowUpActionDescription);
                Assert.AreEqual("Subscriber and subscriber id not found.", ex.EligibleError.Error.Details);
                Assert.AreEqual(0, ex.EligibleError.KnownIssues.Count);
            }
        }
Example #7
0
        protected override bool RefundPaymentInternal(Payment payment, out string status)
        {
            InitClient(payment);
            var paymentIntentId = payment.PaymentProperties.First(p => p.Key == PaymentIntentKey).Value;
            var paymentIntent   = PaymentIntentService.Get(paymentIntentId);
            var refundOptions   = new RefundCreateOptions()
            {
                PaymentIntent = paymentIntentId
            };
            var refunded = false;

            switch (paymentIntent.Status)
            {
            case StripeStatus.Succeeded:
                var refundResult = RefundService.Create(refundOptions);
                status = refundResult.Status;
                if (refundResult.Status != StripeStatus.Failed || refundResult.Status != StripeStatus.Canceled)
                {
                    // In the process of being refunded, at least
                    refunded = true;
                    payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Refunded);
                    payment.Save();
                }
                break;

            default:
                return(CancelPaymentInternal(payment, out status));
            }
            return(refunded);
        }
        public void PaymentStatusNoPaymentErrorTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "10101010";
            var actualResponse = paymentStatus.Get(input);

            Assert.AreEqual("F4", actualResponse.Claims[0].Statuses[0].Codes[0].CategoryCode);
            Assert.AreEqual("104", actualResponse.Claims[0].Statuses[0].Codes[0].StatusCode);
            string expexted = "Processed according to plan provisions " +
                              "(Plan refers to provisions that exist between the Health Plan and the Consumer or Patient)";

            Assert.AreEqual(expexted, actualResponse.Claims[0].Statuses[0].Codes[0].StatusLabel);
            Assert.AreEqual(null, actualResponse.Claims[0].Statuses[0].Codes[0].EntityCode);
            Assert.AreEqual(null, actualResponse.Claims[0].Statuses[0].Codes[0].EntityLabel);
            expexted = "Finalized/Adjudication Complete - No payment forthcoming-" +
                       "The claim/encounter has been adjudicated and no further payment is forthcoming.";
            Assert.AreEqual(expexted, actualResponse.Claims[0].Statuses[0].Codes[0].CategoryLabel);

            expexted = "Health Care Financing Administration Common Procedural Coding System (HCPCS) Codes. " +
                       "HCFA coding scheme to group procedure(s) performed on an outpatient basis for payment to hospital under Medicare; " +
                       "primarily used for ambulatory surgical and other diagnostic departments";
            Assert.AreEqual(expexted, actualResponse.Claims[0].ServiceLines[0].ProcedureQualifierLabel);
        }
        public override void ProcessCallback(Payment payment)
        {
            if (payment.PaymentStatus.PaymentStatusId != (int)PaymentStatusCode.PendingAuthorization)
            {
                return;
            }

            string token          = HttpContext.Current.Request.QueryString["token"];
            var    responseValues = EnsureTransactionIsValid(payment, token);
            string transactionId  = DoPayment(payment, responseValues);

            if (InstantAcquireIsConfigured(payment))
            {
                payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Acquired);
            }
            else
            {
                payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Authorized);
            }

            payment.TransactionId = transactionId;

            ExecutePostProcessingPipeline(payment);

            string returnUrl = new Uri(_absoluteUrlService.GetAbsoluteUrl(payment.PaymentMethod.DynamicProperty <string>().Return))
                               .AddOrderGuidParameter(payment.PurchaseOrder)
                               .ToString();

            HttpContext.Current.Response.Redirect(returnUrl, true);
        }
        public PaymentStatus GetPaymentStatusFromOrderStatus(int status)
        {
            PaymentStatusCode paymentStatusCode;

            switch (status)
            {
            case -2:
                paymentStatusCode = PaymentStatusCode.Cancelled; break;

            case -1:
                paymentStatusCode = PaymentStatusCode.Declined; break;

            case 0:
                paymentStatusCode = PaymentStatusCode.New; break;

            case 1:
                paymentStatusCode = PaymentStatusCode.PendingAuthorization; break;

            case 2:
                paymentStatusCode = PaymentStatusCode.Acquired; break;

            case 3:
                paymentStatusCode = PaymentStatusCode.Refunded; break;

            case 4:
                paymentStatusCode = PaymentStatusCode.Authorized; break;

            default:
                paymentStatusCode = PaymentStatusCode.Declined; break;
            }

            return(PaymentStatus.Get((int)paymentStatusCode));
        }
        public void PaymentStatusInformationHolderNotRespondingTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "89898989";
            try
            {
                var actualResponse = paymentStatus.Get(input);
            }
            catch (EligibleService.Exceptions.EligibleException ex)
            {
                Assert.IsNotNull(ex.EligibleError.EligibleId);
                Assert.IsNotNull(ex.EligibleError.CreatedAt);
                Assert.AreEqual("Y", ex.EligibleError.Error.ResponseCode);
                Assert.AreEqual("Yes", ex.EligibleError.Error.ResponseDescription);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierCode);
                Assert.AreEqual("", ex.EligibleError.Error.AgencyQualifierDescription);
                Assert.AreEqual("E2", ex.EligibleError.Error.RejectReasonCode);
                Assert.AreEqual("Information Holder is not responding: resubmit at a later time.", ex.EligibleError.Error.RejectReasonDescription);
                Assert.AreEqual("C", ex.EligibleError.Error.FollowUpActionCode);
                Assert.AreEqual("Please Correct and Resubmit", ex.EligibleError.Error.FollowUpActionDescription);
                Assert.AreEqual("Cannot provide further status electronically.", ex.EligibleError.Error.Details);
                Assert.AreEqual(0, ex.EligibleError.KnownIssues.Count);
            }
        }
Example #12
0
        /// <summary>
        /// Refunds the payment from the payment provider.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="status">The status.</param>
        /// <returns>Succes</returns>
        protected override bool RefundPaymentInternal(Payment payment, out string status)
        {
            var         gateway     = GetBraintreeGateway(payment.PaymentMethod);
            Transaction transaction = gateway.Transaction.Find(payment.TransactionId);

            if (transaction.Status == TransactionStatus.AUTHORIZED || transaction.Status == TransactionStatus.SUBMITTED_FOR_SETTLEMENT)
            {
                return(CancelPaymentInternal(payment, out status));
            }

            if (transaction.Status != TransactionStatus.SETTLING && transaction.Status != TransactionStatus.SETTLED)
            {
                throw new InvalidOperationException(string.Format("It is not possible to refund a payment with a remote status of either 'settling' or 'settled'. Remote payment status is '{0}'.", transaction.Status.ToString().ToLower()));
            }

            Result <Transaction> result = gateway.Transaction.Refund(payment.TransactionId);

            if (result.IsSuccess())
            {
                status = "";
                payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Refunded);
            }
            else
            {
                status = GetErrorMessage(result);
            }

            return(result.IsSuccess());
        }
Example #13
0
        /// <summary>
        /// Cancels the payment with the payment gateway.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="status">The status.</param>
        /// <returns>Succes</returns>
        protected override bool CancelPaymentInternal(Payment payment, out string status)
        {
            //Verify transaction status with braintree.
            var         gateway     = GetBraintreeGateway(payment.PaymentMethod);
            Transaction transaction = gateway.Transaction.Find(payment.TransactionId);

            if (transaction.Status != TransactionStatus.AUTHORIZED && transaction.Status != TransactionStatus.SUBMITTED_FOR_SETTLEMENT)
            {
                throw new InvalidOperationException(string.Format("Coundn't void payment that doesn't have a status of either 'authorized' or 'submitted_for_settlement'. Payment status is '{0}'.", transaction.Status.ToString().ToLower()));
            }

            Result <Transaction> result = gateway.Transaction.Void(payment.TransactionId);

            if (result.IsSuccess())
            {
                status = "";
                payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Cancelled);
            }
            else
            {
                status = GetErrorMessage(result);
            }

            return(result.IsSuccess());
        }
Example #14
0
        /// <summary>
        /// Acquires the payment from the payment provider.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="status">The status.</param>
        /// <returns>Succes</returns>
        protected override bool AcquirePaymentInternal(Payment payment, out string status)
        {
            //Verify transaction status with braintree.
            var         gateway     = GetBraintreeGateway(payment.PaymentMethod);
            Transaction transaction = gateway.Transaction.Find(payment.TransactionId);

            if (transaction.Status == TransactionStatus.SUBMITTED_FOR_SETTLEMENT || transaction.Status == TransactionStatus.SETTLING || transaction.Status == TransactionStatus.SETTLED)
            {
                status = string.Format("The payment is in the process of being acquired. Status is '{0}'. This might be because the order was submitted in the merchant interface.", transaction.Status.ToString().ToLower());
                payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Acquired);
                return(true);
            }

            Result <Transaction> result = gateway.Transaction.SubmitForSettlement(payment.TransactionId);
            var paymentStatus           = PaymentStatusCode.AcquireFailed;

            if (result.IsSuccess())
            {
                paymentStatus = PaymentStatusCode.Acquired;
                status        = "";
            }
            else
            {
                status = GetErrorMessage(result);
            }

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            return(result.IsSuccess());
        }
        public void PaymentStatusFinalisedButNoPaymentTest()
        {
            var hashParams = PaymentStatusParams();

            hashParams.Add("member_id", "10101010");

            PayementStatusResponse actualResponse = paymentStatus.Get(hashParams);

            string expectedResponse = TestHelper.GetJson(TestResource.ExpectedResponse + "paymentStatus.json");

            TestHelper.CompareProperties(expectedResponse, actualResponse.JsonResponse());

            PayementStatusResponse expectedObj = JsonConvert.DeserializeObject <PayementStatusResponse>(expectedResponse);
            PayementStatusResponse actualObj   = JsonConvert.DeserializeObject <PayementStatusResponse>(actualResponse.JsonResponse());

            TestHelper.PropertyValuesAreEquals(actualObj, expectedObj);
        }
        /// <summary>
        /// Processes the callback from Authorize.NET after a customer authorizes a payment request.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <remarks>Method communicates with Authorize.NET server and processes the auth_codes from the response.
        /// Normally the callback would do a redirect at the end.
        /// Instead we write the page directly to them.
        /// </remarks>
        public override void ProcessCallback(Payment payment)
        {
            if (payment.PaymentStatus.PaymentStatusId != (int)PaymentStatusCode.PendingAuthorization)
            {
                return;
            }

            var paymentStatus = PaymentStatusCode.Declined;

            var responseCodeParameter       = GetParameter("x_response_code", "\"{0}\" cannot be null or empty");
            var responseReasonCodeParameter = GetParameter("x_response_reason_code", "\"{0}\" cannot be null or empty");
            var responseReasonTextParameter = GetParameter("x_response_reason_text", "\"{0}\" cannot be null or empty");

            string transactParameter = HttpContext.Current.Request["x_trans_id"];

            if (string.IsNullOrEmpty(transactParameter))
            {
                throw new ArgumentException(@"transact must be present in query string.");
            }

            string transact = transactParameter;

            // If payment received OK, proceed with processing
            if (responseCodeParameter == "1")
            {
                const string format = "When using md5 \"{0}\" cannot be null or empty";
                payment["auth_code"] = GetParameter("x_auth_code", format);

                var md5KeyParameter = GetParameter("x_MD5_Hash", format).ToLower();
                var amountParameter = GetParameter("x_amount", format);

                // Configuration values
                string md5Hash        = payment.PaymentMethod.DynamicProperty <string>().Md5Hash;
                string apiLogin       = payment.PaymentMethod.DynamicProperty <string>().ApiLogin;
                bool   instantAcquire = payment.PaymentMethod.DynamicProperty <bool>().InstantAcquire;

                var hashComputer = new AuthorizedotnetMd5Computer();
                if (hashComputer.IsMatch(md5Hash, apiLogin, transact, amountParameter, md5KeyParameter))
                {
                    paymentStatus = instantAcquire ? PaymentStatusCode.Acquired : PaymentStatusCode.Authorized;
                }

                payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
                payment.TransactionId = transact;
                ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            }

            // Configuration values
            string declineUrl = payment.PaymentMethod.DynamicProperty <string>().DeclineUrl;
            string acceptUrl  = payment.PaymentMethod.DynamicProperty <string>().AcceptUrl;

            HttpContext.Current.Response.Write(paymentStatus == PaymentStatusCode.Declined
                                                                        ? DownloadPageContent(new Uri(_absoluteUrlService.GetAbsoluteUrl(declineUrl))
                                                                                              .AddQueryStringParameter("x_response_reason_code", responseReasonCodeParameter)
                                                                                              .AddQueryStringParameter("x_response_reason_text", responseReasonTextParameter), payment)

                                                                        : DownloadPageContent(new Uri(_absoluteUrlService.GetAbsoluteUrl(acceptUrl)), payment));
        }
Example #17
0
        private void HandleDeclinedResponse(Payment payment, dynamic cancelUrlForPaymentMethod)
        {
            payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Declined);
            payment.Save();

            HttpContext.Current.Response.Redirect(
                new Uri(_absoluteUrlService.GetAbsoluteUrl(cancelUrlForPaymentMethod)).AddOrderGuidParameter(payment.PurchaseOrder)
                .ToString());
        }
        /// <summary>
        /// Method is called when the order is being canceled by the merchant before the <see cref="Payment"/> is acquired.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="status">The status.</param>
        protected override bool CancelPaymentInternal(Payment payment, out string status)
        {
            var    paymentMethod = payment.PaymentMethod;
            string pspId         = paymentMethod.DynamicProperty <string>().PspId;
            string password      = paymentMethod.DynamicProperty <string>().Password;
            string userId        = paymentMethod.DynamicProperty <string>().UserId;
            string shaSignIn     = paymentMethod.DynamicProperty <string>().ShaSignIn;
            bool   testMode      = paymentMethod.DynamicProperty <bool>().TestMode;

            int ogonePaymentStatus = RequestPaymentStatusAtOgone(payment, pspId, userId, password, testMode);

            if (ogonePaymentStatus == 9 || ogonePaymentStatus == 91)
            {
                return(RefundPaymentInternal(payment, out status));
            }
            if (ogonePaymentStatus != 5)
            {
                status = string.Format("expected status was 5 or 91 for cancel payment, but was {0}. Check STATUS message at {1}"
                                       , ogonePaymentStatus
                                       , "https://secure.ogone.com/ncol/param_cookbook.asp?CSRFSP=%2Fncol%2Ftest%2Fdownload_docs%2Easp&CSRFKEY=7E003EFC9703DF1A30BF28559ED87B534C0F0309&CSRFTS=20110822081113"
                                       );
                return(false);
            }

            var dict = new Dictionary <string, string>();

            dict.Add("amount", payment.Amount.ToCents().ToString());
            dict.Add("currency", payment.PurchaseOrder.BillingCurrency.ISOCode);
            dict.Add("operation", "DES");
            dict.Add("orderid", payment.PurchaseOrder.OrderId.ToString());
            dict.Add("payid", payment.TransactionId);
            dict.Add("pspid", pspId);
            dict.Add("pswd", password);
            dict.Add("userid", userId);

            var shaComputer            = new OgoneSha1Computer();
            var cancelPaymentShaSignIn = new CancelPaymentShaSignIn();

            dict.Add("SHASign", shaComputer.ComputeHash(cancelPaymentShaSignIn.BuildHashString(dict, shaSignIn)).ToUpper());

            var url = GetMaintenanceDirectUrl(testMode);

            var oGoneDataCapture = RequestOgone(url, dict);

            var ncresponse        = oGoneDataCapture.Descendants("ncresponse").Single();
            var maintenanceStatus = Convert.ToInt32(ncresponse.Attributes("STATUS").Single().Value);

            payment.PaymentStatus = PaymentStatus.Get((int)ConvertCancelResultToPaymentStatus(maintenanceStatus));
            status = "";
            if (payment.PaymentStatus.PaymentStatusId == (int)PaymentStatusCode.Declined)
            {
                status = GetNCResponseErrorMessage(ncresponse);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Method is called when the order is being completed by the merchant when the <see cref="Payment"/> is authorized.
        /// </summary>
        /// <param name="payment">The authorized payment.</param>
        /// <param name="status">The status.</param>
        protected override bool AcquirePaymentInternal(Payment payment, out string status)
        {
            var    paymentMethod = payment.PaymentMethod;
            string pspId         = paymentMethod.DynamicProperty <string>().PspId;
            string password      = paymentMethod.DynamicProperty <string>().Password;
            string userId        = paymentMethod.DynamicProperty <string>().UserId;
            string shaSignIn     = paymentMethod.DynamicProperty <string>().ShaSignIn;
            bool   testMode      = paymentMethod.DynamicProperty <bool>().TestMode;


            int ogonePaymentStatus = RequestPaymentStatusAtOgone(payment, pspId, userId, password, testMode);

            if (ogonePaymentStatus != 5)
            {
                status = string.Format("Expected status was 'Payment Authorized' (5) but was {0}. {1}. Check STATUS message at {2}.",
                                       ogonePaymentStatus,
                                       "Processing a payment request takes time. Please wait for Ogone to finalize the authorization.",
                                       "https://secure.ogone.com/ncol/param_cookbook.asp"
                                       );
                return(false);
            }

            var dict = new Dictionary <string, string>();

            dict.Add("amount", payment.Amount.ToCents().ToString());
            dict.Add("currency", payment.PurchaseOrder.BillingCurrency.ISOCode);
            dict.Add("operation", "SAS");
            dict.Add("orderid", payment.ReferenceId);
            dict.Add("payid", payment.TransactionId);
            dict.Add("pspid", pspId);
            dict.Add("pswd", password);
            dict.Add("userid", userId);

            var shaComputer             = new OgoneSha1Computer();
            var acquirePaymentShaSignIn = new AcquirePaymentShaSignIn();

            dict.Add("SHASign", shaComputer.ComputeHash(acquirePaymentShaSignIn.BuildHashString(dict, shaSignIn)).ToUpper());

            var url = GetMaintenanceDirectUrl(testMode);

            var oGoneDataCapture = RequestOgone(url, dict);

            var ncresponse        = oGoneDataCapture.Descendants("ncresponse").Single();
            var maintenanceStatus = Convert.ToInt32(ncresponse.Attributes("STATUS").Single().Value);

            payment.PaymentStatus = PaymentStatus.Get((int)ConvertAcquireResultToPaymentStatus(maintenanceStatus));

            status = "";

            if (payment.PaymentStatus.PaymentStatusId == (int)PaymentStatusCode.AcquireFailed)
            {
                status = GetNCResponseErrorMessage(ncresponse);
                return(false);
            }

            return(true);
        }
        public void GetPaymentStatusTest()
        {
            restClient.Setup(x => x.Execute(It.IsAny <string>(), It.IsAny <RequestOptions>(), It.IsAny <Hashtable>()))
            .Returns(new RestResponse()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = TestHelper.GetJson(TestResource.MocksPath + "paymentStatus.json")
            });

            paymentStatus.ExecuteObj = restClient.Object;

            var acknowledgements = paymentStatus.Get(param);

            Fixture fixture            = new Fixture();
            PayementStatusResponse sut = fixture.Create <PayementStatusResponse>();

            TestHelper.PropertiesAreEqual(sut, acknowledgements.JsonResponse());
        }
        public void PaymentStatusPendingTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "34343434";
            var actualResponse = paymentStatus.Get(input);

            Assert.AreEqual("pending", actualResponse.Claims[0].Statuses[0].AdjudicationStatus);
        }
        public void PaymentStatusPaidTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "12312312";
            var actualResponse = paymentStatus.Get(input);

            Assert.AreEqual("completed", actualResponse.Claims[0].Statuses[0].AdjudicationStatus);
        }
Example #23
0
        private void HandleAuthorizedResponse(Payment payment, string acceptUrl, string transactionId)
        {
            payment.TransactionId = transactionId;
            payment.PaymentStatus = PaymentStatus.Get((int)PaymentStatusCode.Authorized);

            ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));

            HttpContext.Current.Response.Redirect(
                new Uri(_absoluteUrlService.GetAbsoluteUrl(acceptUrl)).AddOrderGuidParameter(payment.PurchaseOrder).ToString());
        }
        public void PaymentStatusDeniedTest()
        {
            var       paymentStatus = new PaymentStatus();
            Hashtable input         = PaymentStatusParams();

            input["member_id"] = "45454545";
            var actualResponse = paymentStatus.Get(input);

            Assert.AreEqual("Finalized/Denial-The claim/line has been denied.", actualResponse.Claims[0].Statuses[0].Codes[0].CategoryLabel);
            Assert.AreEqual("Denied Charge or Non-covered Charge", actualResponse.Claims[0].Statuses[0].Codes[0].StatusLabel);
        }
        /// <summary>
        /// Method is called when the order is being canceled by the merchant, after the <see cref="Payment"/> have been acquired by the merchant.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="status">The status.</param>
        protected override bool RefundPaymentInternal(Payment payment, out string status)
        {
            var    paymentMethod = payment.PaymentMethod;
            string pspId         = paymentMethod.DynamicProperty <string>().PspId;
            string password      = paymentMethod.DynamicProperty <string>().Password;
            string userId        = paymentMethod.DynamicProperty <string>().UserId;
            string shaSignIn     = paymentMethod.DynamicProperty <string>().ShaSignIn;
            bool   testMode      = paymentMethod.DynamicProperty <bool>().TestMode;

            int paymentStatus = RequestPaymentStatusAtOgone(payment, pspId, userId, password, testMode);

            if (paymentStatus != 9 && paymentStatus != 91)
            {
                status = string.Format("Expected status was 'Payment requested' (9) or 'Payment Processig' (91) for refund, but was {0}. Check 'STATUS' message at {1}",
                                       paymentStatus,
                                       "https://secure.ogone.com/ncol/param_cookbook.asp"
                                       );
                return(false);
            }
            var dict = new Dictionary <string, string>();

            dict.Add("amount", payment.Amount.ToCents().ToString());
            dict.Add("currency", payment.PurchaseOrder.BillingCurrency.ISOCode);
            dict.Add("operation", "RFS");
            dict.Add("orderid", payment.ReferenceId);
            dict.Add("payid", payment.TransactionId);
            dict.Add("pspid", pspId);
            dict.Add("pswd", password);
            dict.Add("userid", userId);

            var shaComputer = new OgoneSha1Computer();
            var hashString  = new CancelPaymentShaSignIn();

            dict.Add("SHASign", shaComputer.ComputeHash(hashString.BuildHashString(dict, shaSignIn)).ToUpper());

            var url = GetMaintenanceDirectUrl(testMode);

            var oGoneDataCapture = RequestOgone(url, dict);
            var ncresponse       = oGoneDataCapture.Descendants("ncresponse").Single();

            var maintenanceStatus = Convert.ToInt32(ncresponse.Attributes("STATUS").Single().Value);

            payment.PaymentStatus = PaymentStatus.Get((int)ConvertRefundResultToPaymentStatus(maintenanceStatus));

            status = "";
            if (payment.PaymentStatus.PaymentStatusId == (int)PaymentStatusCode.Declined)
            {
                status = GetNCResponseErrorMessage(ncresponse);
                return(false);
            }

            return(true);
        }
Example #26
0
        /// <summary>
        /// Processes the callback and excecutes a pipeline if there is one specified for this paymentmethodservice.
        /// </summary>
        /// <param name="payment">The payment to process.</param>
        public override void ProcessCallback(Payment payment)
        {
            string paymentFormUrl = payment.PaymentMethod.DynamicProperty <string>().PaymentFormUrl;
            string acceptUrl      = payment.PaymentMethod.DynamicProperty <string>().AcceptUrl;
            string declineUrl     = payment.PaymentMethod.DynamicProperty <string>().DeclineUrl;

            if (payment.PaymentStatus.PaymentStatusId != (int)PaymentStatusCode.PendingAuthorization)
            {
                return;
            }

            Result <Transaction> result = GetBraintreeGateway(payment.PaymentMethod).TransparentRedirect.ConfirmTransaction(HttpContext.Current.Request.Url.Query);

            if (!result.IsSuccess())
            {
                HttpContext.Current.Response.Redirect(paymentFormUrl == "(auto)"
                    ? string.Format("/{0}/{1}/PaymentRequest.axd?errorMessage={2}", payment.PaymentMethod.PaymentMethodId, payment["paymentGuid"], result.Message.Replace('\n', ';'))
                    : string.Format("{0}?paymentGuid={1}&errorMessage={2}", paymentFormUrl, payment["paymentGuid"], result.Message.Replace('\n', ';')));
            }

            // Validates that the currency configured in the merchant account matches payment currency.
            // We can only check the currency when the transaction is returned from Braintree. There's no way to
            // to verify that the configured currency in Braintree is the same as the billing currency before submitting
            // the transaction.
            Transaction transaction = result.Target;

            if (transaction.CurrencyIsoCode.ToLower() != payment.PurchaseOrder.BillingCurrency.ISOCode.ToLower())
            {
                throw new InvalidOperationException(string.Format("The payment currency ({0}) and the currency configured for the merchant account ({1}) doesn't match. Make sure that the payment currency matches the currency selected in the merchant account.", payment.PurchaseOrder.BillingCurrency.ISOCode.ToUpper(), transaction.CurrencyIsoCode.ToUpper()));
            }

            var paymentStatus = PaymentStatusCode.Declined;

            if (result.IsSuccess())
            {
                if (string.IsNullOrEmpty(transaction.Id))
                {
                    throw new ArgumentException(@"transactionId must be present in query string.");
                }
                if (transaction.Id.Length < 6)
                {
                    throw new ArgumentException(@"transactionId must be at least 6 characters in length.");
                }
                payment.TransactionId = transaction.Id;
                paymentStatus         = PaymentStatusCode.Authorized;
            }

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            HttpContext.Current.Response.Redirect(paymentStatus == PaymentStatusCode.Authorized
                                ? new Uri(_absoluteUrlService.GetAbsoluteUrl(acceptUrl)).AddOrderGuidParameter(payment.PurchaseOrder).ToString()
                                : new Uri(_absoluteUrlService.GetAbsoluteUrl(declineUrl)).AddOrderGuidParameter(payment.PurchaseOrder).ToString());
        }
Example #27
0
        /// <summary>
        /// Extracts the transaction result from the body of the HTTP request
        /// </summary>
        /// <param name="payment"></param>
        public override void ProcessCallback(Payment payment)
        {
            if (payment.PaymentStatus.PaymentStatusId != (int)PaymentStatusCode.PendingAuthorization)
            {
                return;
            }

            var response = payment["response"];

            if (response == null)
            {
                throw new NullReferenceException(
                          @"response was not found in payment[""response""], please make sure to insert the response string in the Extract method");
            }

            XDocument xmlBody = XDocument.Parse(response);

            XNamespace xNs = "http://www.idealdesk.com/Message";

            var xmlTransactionStatus = xmlBody.Descendants(xNs + "status").FirstOrDefault();

            if (xmlTransactionStatus == null)
            {
                throw new ArgumentException("Status was not found in XML returned to PaymentProcessor.axd. Expected response with XML element 'status' included.");
            }


            bool requestSuccessful = xmlTransactionStatus.Value.ToLower() == "success";
            var  paymentStatus     = requestSuccessful
                                    ? PaymentStatusCode.Acquired
                                    : PaymentStatusCode.Declined;

            var xmlTransactionId = xmlBody.Descendants(xNs + "transactionID").FirstOrDefault();

            if (xmlTransactionId == null)
            {
                throw new ArgumentException("Transaction ID was not found in xml returned with PaymentProcessor.axd. Expected response with XML element 'transactionID'.");
            }

            string transactionId = xmlTransactionId.Value;

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            payment.TransactionId = transactionId;

            if (requestSuccessful)
            {
                ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            }
        }
        public override Payment CreatePayment(PaymentRequest request)
        {
            var payment = base.CreatePayment(request);

            payment.ReferenceId         = GetReferenceId(request);
            payment.PaymentStatus       = PaymentStatus.Get((int)PaymentStatusCode.PendingAuthorization);
            payment.TransactionId       = null;
            payment["paymentGuid"]      = Guid.NewGuid().ToString();
            payment[LatestPspReference] = "EMPTY";

            request.PurchaseOrder.AddPayment(payment);

            payment.Save();
            return(payment);
        }
Example #29
0
        private void ProcessOrderPayment(string schibstedOrderId, string orderCheck, Payment payment, SppContainer <Order> orderStatus)
        {
            var    paymentMethod = payment.PaymentMethod;
            string cancelUrl     = paymentMethod.DynamicProperty <string>().CancelUrl;
            string acceptUrl     = paymentMethod.DynamicProperty <string>().AcceptUrl;

            // Save order id on payment
            payment.TransactionId = schibstedOrderId;

            // Compare the checksum, and set payment status
            if (orderCheck != orderStatus.Data.ClientReference && (orderStatus.Data.ClientReference != null && payment.PurchaseOrder.OrderTotal > 0))
            {
                throw new SecurityException("Checksum mismatch");
            }

            // Process payment
            var schibstedUtil = GetSchibstedUtil(payment.PaymentMethod);

            payment.PaymentStatus = schibstedUtil.GetPaymentStatusFromOrderStatus(orderStatus.Data.Status);

            Uri redirectUrl;

            if (payment.PaymentStatus != PaymentStatus.Get((int)PaymentStatusCode.Declined))
            {
                ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));

                // Changing order status to completed, if necessary
                if (payment.PaymentStatus == PaymentStatus.Get((int)PaymentStatusCode.Acquired))
                {
                    new OrderService().ChangeOrderStatus(
                        payment.PurchaseOrder,
                        OrderStatus.Get((int)OrderStatusCode.CompletedOrder));
                }

                // Redirecting to the confirmation page
                redirectUrl = new Uri(_absoluteUrlService.GetAbsoluteUrl(acceptUrl));
            }
            else
            {
                redirectUrl = new Uri(_absoluteUrlService.GetAbsoluteUrl(cancelUrl));
            }

            redirectUrl = redirectUrl.AddOrderGuidParameter(payment.PurchaseOrder)
                          .AddQueryStringParameter("order_id", schibstedOrderId)
                          .AddQueryStringParameter("code", HttpContext.Current.Request["code"]);

            HttpContext.Current.Response.Redirect(redirectUrl.AbsoluteUri);
        }
Example #30
0
        public override void ProcessCallback(Payment payment)
        {
            InitClient(payment);
            // BH: Normally, our payment processor would "ping" this endpoint.
            // However, we're going to do it from AJAX ourselves, thus negating the need for a Stripe webhook.
            var paymentIntentId = payment.PaymentProperties.First(p => p.Key == PaymentIntentKey).Value;

            // Just confirm the payment intent exists
            var paymentIntent = PaymentIntentService.Get(paymentIntentId);

            // Firstly: does the payment intent require manual confirmation?
            if (paymentIntent.ConfirmationMethod == "manual")
            {
                try {
                    paymentIntent = PaymentIntentService.Confirm(paymentIntent.Id);
                } catch {
                    throw new InvalidOperationException("Could not confirm payment intent");
                }
            }

            if (paymentIntent.Status != StripeStatus.Succeeded)
            {
                throw new InvalidOperationException("Payment intent capture not successful");
            }

            var transaction = paymentIntent.Charges.First();

            if (transaction.Currency != payment.PurchaseOrder.BillingCurrency.ISOCode.ToLower())
            {
                throw new InvalidOperationException($"The payment currency ({payment.PurchaseOrder.BillingCurrency.ISOCode.ToUpper()}) and the currency configured for the merchant account ({transaction.Currency.ToUpper()}) doesn't match. Make sure that the payment currency matches the currency selected in the merchant account.");
            }

            var paymentStatus = PaymentStatusCode.Declined;

            if (paymentIntent.Status == StripeStatus.Succeeded)
            {
                if (string.IsNullOrEmpty(transaction.Id))
                {
                    throw new ArgumentException(@"Charge ID must be present in the PaymentIntent object.");
                }
                payment.TransactionId = paymentIntent.Id;                 // This is used for
                paymentStatus         = PaymentStatusCode.Authorized;
            }

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            HttpContext.Current.Response.StatusCode = 200;
        }