コード例 #1
0
        /// <summary>
        /// Loads the items.
        /// </summary>
        /// <param name="showAll">if set to <c>true</c> [show all].</param>
        private void LoadItems(bool showAll)
        {
            int?selectedItem = this.SelectedValueAsInt();

            this.Items.Clear();
            this.Items.Add(new ListItem());

            using (var rockContext = new RockContext())
            {
                foreach (var gateway in new FinancialGatewayService(rockContext)
                         .Queryable().AsNoTracking()
                         .Where(g => g.EntityTypeId.HasValue)
                         .OrderBy(g => g.Name)
                         .ToList())
                {
                    var entityType             = EntityTypeCache.Get(gateway.EntityTypeId.Value);
                    GatewayComponent component = GatewayContainer.GetComponent(entityType.Name);
                    if (showAll || (gateway.IsActive && component != null && component.IsActive && component.SupportsRockInitiatedTransactions))
                    {
                        this.Items.Add(new ListItem(gateway.Name, gateway.Id.ToString()));
                    }
                }
            }

            this.SetValue(selectedItem);
        }
コード例 #2
0
        private GatewayComponent GetSelectedGateway()
        {
            Guid?gatewayGuid = cpGateway.SelectedValueAsGuid();

            if (gatewayGuid.HasValue)
            {
                return(GatewayContainer.GetComponent(gatewayGuid.Value.ToString()));
            }
            return(null);
        }
コード例 #3
0
        public HttpResponseMessage StopScheduledGiving(int id)
        {
            var rockContext = new RockContext();

            try
            {
                rockContext.WrapTransaction(() =>
                {
                    var gatewayComponent = GatewayContainer.GetComponent(gatewayName);

                    if (gatewayComponent == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the gateway component");
                    }

                    var financialGateway = new FinancialGatewayService(rockContext).Queryable().FirstOrDefault(g => g.EntityTypeId == gatewayComponent.EntityType.Id);

                    if (financialGateway == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the financial gateway");
                    }

                    var schedule = (new FinancialScheduledTransactionService(rockContext)).Get(id);

                    if (schedule == null)
                    {
                        GenerateResponse(HttpStatusCode.BadRequest, "No schedule with Id: " + id);
                    }

                    string errorMessage;
                    var error = gatewayComponent.CancelScheduledPayment(schedule, out errorMessage);

                    if (error || errorMessage != null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, errorMessage ?? "There was an error with the gateway");
                    }

                    schedule.IsActive = false;
                    rockContext.SaveChanges();
                });
            }
            catch (HttpResponseException exception)
            {
                return(exception.Response);
            }
            catch (Exception exception)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(exception.Message);
                return(response);
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
コード例 #4
0
ファイル: FinancialGateway.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Gets the gateway component.
        /// </summary>
        /// <returns></returns>
        public virtual GatewayComponent GetGatewayComponent()
        {
            if (EntityTypeId.HasValue)
            {
                var entityType = EntityTypeCache.Get(EntityTypeId.Value);
                if (entityType != null)
                {
                    return(GatewayContainer.GetComponent(entityType.Name));
                }
            }

            return(null);
        }
コード例 #5
0
        /// <summary>
        /// Gets the gateway.
        /// </summary>
        /// <param name="scheduledTransaction">The scheduled transaction.</param>
        /// <returns></returns>
        private GatewayComponent GetGateway(FinancialScheduledTransaction scheduledTransaction)
        {
            if (scheduledTransaction.GatewayEntityType != null)
            {
                Guid gatewayGuid = scheduledTransaction.GatewayEntityType.Guid;
                var  gateway     = GatewayContainer.GetComponent(gatewayGuid.ToString());
                if (gateway != null && gateway.IsActive)
                {
                    return(gateway);
                }
            }

            return(null);
        }
コード例 #6
0
        /// <summary>
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            try
            {
                // get the job map
                JobDataMap dataMap = context.JobDetail.JobDataMap;

                string gatewayGuid = dataMap.GetString("PaymentGateway");
                if (!string.IsNullOrWhiteSpace(gatewayGuid))
                {
                    GatewayComponent gateway = GatewayContainer.GetComponent(gatewayGuid);
                    if (gateway != null)
                    {
                        int daysBack = dataMap.GetString("DaysBack").AsIntegerOrNull() ?? 1;

                        DateTime today       = RockDateTime.Today;
                        TimeSpan days        = new TimeSpan(daysBack, 0, 0, 0);
                        DateTime endDateTime = today.Add(gateway.BatchTimeOffset);
                        endDateTime = RockDateTime.Now.CompareTo(endDateTime) < 0 ? endDateTime.AddDays(-1) : today;
                        DateTime startDateTime = endDateTime.Subtract(days);

                        string errorMessage = string.Empty;
                        var    payments     = gateway.GetPayments(startDateTime, endDateTime, out errorMessage);

                        if (string.IsNullOrWhiteSpace(errorMessage))
                        {
                            string batchNamePrefix = dataMap.GetString("BatchNamePrefix");
                            FinancialScheduledTransactionService.ProcessPayments(gateway, batchNamePrefix, payments);
                        }
                        else
                        {
                            throw new Exception(errorMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
            }
        }
コード例 #7
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="txn">The TXN.</param>
        private void ShowView(FinancialScheduledTransaction txn)
        {
            if (txn != null)
            {
                hlStatus.Text      = txn.IsActive ? "Active" : "Inactive";
                hlStatus.LabelType = txn.IsActive ? LabelType.Success : LabelType.Danger;

                string rockUrlRoot = ResolveRockUrl("/");

                var detailsLeft = new DescriptionList()
                                  .Add("Person", (txn.AuthorizedPersonAlias != null && txn.AuthorizedPersonAlias.Person != null) ?
                                       txn.AuthorizedPersonAlias.Person.GetAnchorTag(rockUrlRoot) : string.Empty);

                var detailsRight = new DescriptionList()
                                   .Add("Amount", (txn.ScheduledTransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M).FormatAsCurrency())
                                   .Add("Frequency", txn.TransactionFrequencyValue != null ? txn.TransactionFrequencyValue.Value : string.Empty)
                                   .Add("Start Date", txn.StartDate.ToShortDateString())
                                   .Add("End Date", txn.EndDate.HasValue ? txn.EndDate.Value.ToShortDateString() : string.Empty)
                                   .Add("Next Payment Date", txn.NextPaymentDate.HasValue ? txn.NextPaymentDate.Value.ToShortDateString() : string.Empty)
                                   .Add("Last Status Refresh", txn.LastStatusUpdateDateTime.HasValue ? txn.LastStatusUpdateDateTime.Value.ToString("g") : string.Empty);

                detailsLeft.Add("Source", txn.SourceTypeValue != null ? txn.SourceTypeValue.Value : string.Empty);

                if (txn.FinancialPaymentDetail != null && txn.FinancialPaymentDetail.CurrencyTypeValue != null)
                {
                    var paymentMethodDetails = new DescriptionList();

                    var currencyType = txn.FinancialPaymentDetail.CurrencyTypeValue;
                    if (currencyType.Guid.Equals(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid()))
                    {
                        // Credit Card
                        paymentMethodDetails.Add("Type", currencyType.Value + (txn.FinancialPaymentDetail.CreditCardTypeValue != null ? (" - " + txn.FinancialPaymentDetail.CreditCardTypeValue.Value) : string.Empty));
                        paymentMethodDetails.Add("Name on Card", txn.FinancialPaymentDetail.NameOnCard.Trim());
                        paymentMethodDetails.Add("Account Number", txn.FinancialPaymentDetail.AccountNumberMasked);
                        paymentMethodDetails.Add("Expires", txn.FinancialPaymentDetail.ExpirationDate);
                    }
                    else
                    {
                        // ACH
                        paymentMethodDetails.Add("Type", currencyType.Value);
                        paymentMethodDetails.Add("Account Number", txn.FinancialPaymentDetail.AccountNumberMasked);
                    }

                    detailsLeft.Add("Payment Method", paymentMethodDetails.GetFormattedList("{0}: {1}").AsDelimited("<br/>"));
                }

                GatewayComponent gateway = null;
                if (txn.FinancialGateway != null)
                {
                    gateway = txn.FinancialGateway.GetGatewayComponent();
                    if (gateway != null)
                    {
                        detailsLeft.Add("Payment Gateway", GatewayContainer.GetComponentName(gateway.TypeName));
                    }
                }

                detailsLeft
                .Add("Transaction Code", txn.TransactionCode)
                .Add("Schedule Id", txn.GatewayScheduleId);

                lDetailsLeft.Text  = detailsLeft.Html;
                lDetailsRight.Text = detailsRight.Html;

                gAccountsView.DataSource = txn.ScheduledTransactionDetails.ToList();
                gAccountsView.DataBind();

                var noteType = NoteTypeCache.Read(Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid());
                if (noteType != null)
                {
                    var rockContext = new RockContext();
                    rptrNotes.DataSource = new NoteService(rockContext).Get(noteType.Id, txn.Id)
                                           .Where(n => n.CreatedDateTime.HasValue)
                                           .OrderBy(n => n.CreatedDateTime)
                                           .ToList()
                                           .Select(n => new
                    {
                        n.Caption,
                        Text   = n.Text.ConvertCrLfToHtmlBr(),
                        Person = (n.CreatedByPersonAlias != null && n.CreatedByPersonAlias.Person != null) ? n.CreatedByPersonAlias.Person.FullName : "",
                        Date   = n.CreatedDateTime.HasValue ? n.CreatedDateTime.Value.ToShortDateString() : "",
                        Time   = n.CreatedDateTime.HasValue ? n.CreatedDateTime.Value.ToShortTimeString() : ""
                    })
                                           .ToList();
                    rptrNotes.DataBind();
                }

                lbRefresh.Visible            = gateway != null && gateway.GetScheduledPaymentStatusSupported;
                lbUpdate.Visible             = gateway != null && gateway.UpdateScheduledPaymentSupported;
                lbCancelSchedule.Visible     = txn.IsActive;
                lbReactivateSchedule.Visible = !txn.IsActive && gateway != null && gateway.ReactivateScheduledPaymentSupported;
            }
        }
コード例 #8
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="financialScheduledTransaction">The TXN.</param>
        private void ShowView(FinancialScheduledTransaction financialScheduledTransaction)
        {
            if (financialScheduledTransaction == null)
            {
                return;
            }

            hlStatus.Text      = financialScheduledTransaction.IsActive ? "Active" : "Inactive";
            hlStatus.LabelType = financialScheduledTransaction.IsActive ? LabelType.Success : LabelType.Danger;

            string rockUrlRoot = ResolveRockUrl("/");
            Person person      = null;

            if (financialScheduledTransaction.AuthorizedPersonAlias != null)
            {
                person = financialScheduledTransaction.AuthorizedPersonAlias.Person;
            }

            var detailsLeft = new DescriptionList().Add("Person", person);

            var detailsRight = new DescriptionList()
                               .Add("Amount", (financialScheduledTransaction.ScheduledTransactionDetails.Sum(d => ( decimal? )d.Amount) ?? 0.0M).FormatAsCurrency())
                               .Add("Frequency", financialScheduledTransaction.TransactionFrequencyValue != null ? financialScheduledTransaction.TransactionFrequencyValue.Value : string.Empty)
                               .Add("Start Date", financialScheduledTransaction.StartDate.ToShortDateString())
                               .Add("End Date", financialScheduledTransaction.EndDate.HasValue ? financialScheduledTransaction.EndDate.Value.ToShortDateString() : string.Empty)
                               .Add("Next Payment Date", financialScheduledTransaction.NextPaymentDate.HasValue ? financialScheduledTransaction.NextPaymentDate.Value.ToShortDateString() : string.Empty)
                               .Add("Last Status Refresh", financialScheduledTransaction.LastStatusUpdateDateTime.HasValue ? financialScheduledTransaction.LastStatusUpdateDateTime.Value.ToString("g") : string.Empty);

            detailsLeft.Add("Source", financialScheduledTransaction.SourceTypeValue != null ? financialScheduledTransaction.SourceTypeValue.Value : string.Empty);

            if (financialScheduledTransaction.FinancialPaymentDetail != null && financialScheduledTransaction.FinancialPaymentDetail.CurrencyTypeValue != null)
            {
                var paymentMethodDetails = new DescriptionList();

                var currencyType = financialScheduledTransaction.FinancialPaymentDetail.CurrencyTypeValue;
                if (currencyType.Guid.Equals(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid()))
                {
                    // Credit Card
                    paymentMethodDetails.Add("Type", currencyType.Value + (financialScheduledTransaction.FinancialPaymentDetail.CreditCardTypeValue != null ? (" - " + financialScheduledTransaction.FinancialPaymentDetail.CreditCardTypeValue.Value) : string.Empty));
                    paymentMethodDetails.Add("Name on Card", financialScheduledTransaction.FinancialPaymentDetail.NameOnCard.Trim());
                    paymentMethodDetails.Add("Account Number", financialScheduledTransaction.FinancialPaymentDetail.AccountNumberMasked);
                    paymentMethodDetails.Add("Expires", financialScheduledTransaction.FinancialPaymentDetail.ExpirationDate);
                }
                else
                {
                    // ACH
                    paymentMethodDetails.Add("Type", currencyType.Value);
                    paymentMethodDetails.Add("Account Number", financialScheduledTransaction.FinancialPaymentDetail.AccountNumberMasked);
                }

                detailsLeft.Add("Payment Method", paymentMethodDetails.GetFormattedList("{0}: {1}").AsDelimited("<br/>"));
            }

            GatewayComponent gateway = null;

            if (financialScheduledTransaction.FinancialGateway != null)
            {
                gateway = financialScheduledTransaction.FinancialGateway.GetGatewayComponent();
                if (gateway != null)
                {
                    detailsLeft.Add("Payment Gateway", GatewayContainer.GetComponentName(gateway.TypeName));
                }
            }

            detailsLeft
            .Add("Transaction Code", financialScheduledTransaction.TransactionCode)
            .Add("Schedule Id", financialScheduledTransaction.GatewayScheduleId);

            lSummary.Visible = financialScheduledTransaction.Summary.IsNotNullOrWhiteSpace();
            lSummary.Text    = financialScheduledTransaction.Summary.ConvertCrLfToHtmlBr();

            lDetailsLeft.Text  = detailsLeft.Html;
            lDetailsRight.Text = detailsRight.Html;

            gAccountsView.DataSource = financialScheduledTransaction.ScheduledTransactionDetails.ToList();
            gAccountsView.DataBind();

            btnRefresh.Visible            = gateway != null && gateway.GetScheduledPaymentStatusSupported;
            btnUpdate.Visible             = gateway != null && gateway.UpdateScheduledPaymentSupported;
            btnCancelSchedule.Visible     = financialScheduledTransaction.IsActive;
            btnReactivateSchedule.Visible = !financialScheduledTransaction.IsActive && gateway != null && gateway.ReactivateScheduledPaymentSupported;
        }
コード例 #9
0
        public HttpResponseMessage Give([FromBody] GiveParameters giveParameters)
        {
            var rockContext = new RockContext();

            try
            {
                rockContext.WrapTransaction(() =>
                {
                    int?locationId = null;
                    FinancialPaymentDetail paymentDetail = null;
                    PaymentInfo paymentInfo = null;
                    FinancialPersonSavedAccount savedAccount = null;
                    bool newSavedAccount = true;

                    var gatewayComponent = GatewayContainer.GetComponent(gatewayName);

                    if (gatewayComponent == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the gateway component");
                    }

                    var financialGateway = new FinancialGatewayService(rockContext).Queryable().FirstOrDefault(g => g.EntityTypeId == gatewayComponent.EntityType.Id);

                    if (financialGateway == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the financial gateway");
                    }

                    var totalAmount = CalculateTotalAmount(giveParameters, rockContext);
                    var person      = GetExistingPerson(giveParameters.PersonId, rockContext);

                    if (person == null)
                    {
                        // New person
                        locationId = CreateLocation(giveParameters, rockContext);
                        person     = CreatePerson(giveParameters, locationId.Value, rockContext);
                    }
                    else
                    {
                        // Existing person
                        savedAccount = GetExistingSavedAccount(giveParameters, person, rockContext);

                        if (savedAccount != null)
                        {
                            locationId      = savedAccount.FinancialPaymentDetail.BillingLocationId;
                            newSavedAccount = false;
                        }
                    }

                    if (!locationId.HasValue)
                    {
                        locationId = CreateLocation(giveParameters, rockContext);
                    }

                    if (savedAccount == null)
                    {
                        paymentDetail   = CreatePaymentDetail(giveParameters, person, locationId.Value, rockContext);
                        savedAccount    = CreateSavedAccount(giveParameters, paymentDetail, financialGateway, person, rockContext);
                        newSavedAccount = true;
                        paymentInfo     = GetPaymentInfo(giveParameters, person, rockContext, totalAmount.Value, paymentDetail);
                    }
                    else
                    {
                        paymentDetail = savedAccount.FinancialPaymentDetail;
                        locationId    = paymentDetail.BillingLocationId;
                        paymentInfo   = savedAccount.GetReferencePayment();
                        UpdatePaymentInfoForSavedAccount(giveParameters, paymentInfo, person, rockContext, locationId.Value, totalAmount.Value);
                    }

                    SaveLocationToFamilyIfNone(person, locationId.Value, rockContext);
                    string errorMessage;
                    var transaction = gatewayComponent.Charge(financialGateway, paymentInfo, out errorMessage);

                    if (transaction == null || !string.IsNullOrWhiteSpace(errorMessage))
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, errorMessage ?? "The gateway had a problem and/or did not create a transaction as expected");
                    }

                    transaction.FinancialPaymentDetail   = null;
                    transaction.SourceTypeValueId        = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE)).Id;
                    transaction.TransactionDateTime      = RockDateTime.Now;
                    transaction.AuthorizedPersonAliasId  = person.PrimaryAliasId;
                    transaction.AuthorizedPersonAlias    = person.PrimaryAlias;
                    transaction.FinancialGatewayId       = financialGateway.Id;
                    transaction.TransactionTypeValueId   = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION)).Id;
                    transaction.FinancialPaymentDetailId = paymentDetail.Id;
                    savedAccount.TransactionCode         = transaction.TransactionCode;

                    foreach (var accountAmount in giveParameters.AmountDetails)
                    {
                        transaction.TransactionDetails.Add(new FinancialTransactionDetail()
                        {
                            Amount    = accountAmount.Amount,
                            AccountId = accountAmount.TargetAccountId
                        });
                    }

                    new FinancialTransactionService(rockContext).Add(transaction);
                    rockContext.SaveChanges();

                    if (newSavedAccount)
                    {
                        var newReferenceNumber       = gatewayComponent.GetReferenceNumber(transaction, out errorMessage);
                        savedAccount.ReferenceNumber = newReferenceNumber;
                    }

                    rockContext.SaveChanges();
                });
            }
            catch (HttpResponseException exception)
            {
                return(exception.Response);
            }
            catch (Exception exception)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(exception.Message);
                return(response);
            }

            return(new HttpResponseMessage(HttpStatusCode.NoContent));
        }
コード例 #10
0
        public HttpResponseMessage SavePaymentAccount([FromBody] PaymentParameters paymentParameters)
        {
            var rockContext = new RockContext();

            try
            {
                rockContext.WrapTransaction(() =>
                {
                    var person = GetExistingPerson(paymentParameters.PersonId, rockContext);

                    if (person == null)
                    {
                        GenerateResponse(HttpStatusCode.BadRequest, "An existing person is required to save a payment");
                    }

                    var gatewayComponent = GatewayContainer.GetComponent(gatewayName);

                    if (gatewayComponent == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the gateway component");
                    }

                    var financialGateway = new FinancialGatewayService(rockContext).Queryable().FirstOrDefault(g => g.EntityTypeId == gatewayComponent.EntityType.Id);

                    if (financialGateway == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the financial gateway");
                    }

                    var locationId    = CreateLocation(paymentParameters, rockContext);
                    var paymentDetail = CreatePaymentDetail(paymentParameters, person, locationId, rockContext);
                    var savedAccount  = CreateSavedAccount(paymentParameters, paymentDetail, financialGateway, person, rockContext);
                    var paymentInfo   = GetPaymentInfo(paymentParameters, person, rockContext, 0, paymentDetail);

                    string errorMessage;
                    var transaction = gatewayComponent.Authorize(financialGateway, paymentInfo, out errorMessage);

                    if (transaction == null || !string.IsNullOrWhiteSpace(errorMessage))
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, errorMessage ?? "The gateway had a problem and/or did not create a transaction as expected");
                    }

                    transaction.FinancialPaymentDetail   = null;
                    transaction.SourceTypeValueId        = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE)).Id;
                    transaction.TransactionDateTime      = RockDateTime.Now;
                    transaction.AuthorizedPersonAliasId  = person.PrimaryAliasId;
                    transaction.AuthorizedPersonAlias    = person.PrimaryAlias;
                    transaction.FinancialGateway         = financialGateway;
                    transaction.FinancialGatewayId       = financialGateway.Id;
                    transaction.TransactionTypeValueId   = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION)).Id;
                    transaction.FinancialPaymentDetailId = paymentDetail.Id;
                    savedAccount.TransactionCode         = transaction.TransactionCode;
                    SaveLocationToFamilyIfNone(person, locationId, rockContext);
                    savedAccount.ReferenceNumber = gatewayComponent.GetReferenceNumber(transaction, out errorMessage);
                    rockContext.SaveChanges();
                });
            }
            catch (HttpResponseException exception)
            {
                return(exception.Response);
            }
            catch (Exception exception)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(exception.Message);
                return(response);
            }

            return(new HttpResponseMessage(HttpStatusCode.NoContent));
        }
コード例 #11
0
        public HttpResponseMessage ScheduleGiving([FromBody] ScheduleParameters scheduleParameters)
        {
            var rockContext = new RockContext();

            try
            {
                rockContext.WrapTransaction(() =>
                {
                    var person = GetExistingPerson(scheduleParameters.PersonId, rockContext);

                    if (person == null)
                    {
                        GenerateResponse(HttpStatusCode.BadRequest, "An existing person is required to schedule giving");
                    }

                    var totalAmount      = CalculateTotalAmount(scheduleParameters, rockContext);
                    var paymentSchedule  = GetPaymentSchedule(scheduleParameters, person);
                    var gatewayComponent = GatewayContainer.GetComponent(gatewayName);

                    if (gatewayComponent == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the gateway component");
                    }

                    var financialGateway = new FinancialGatewayService(rockContext).Queryable().FirstOrDefault(g => g.EntityTypeId == gatewayComponent.EntityType.Id);

                    if (financialGateway == null)
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, "There was a problem creating the financial gateway");
                    }

                    var savedAccount = GetExistingSavedAccount(scheduleParameters, person, rockContext);
                    FinancialPaymentDetail paymentDetail = null;
                    PaymentInfo paymentInfo = null;
                    int?locationId          = null;

                    if (savedAccount == null)
                    {
                        locationId    = CreateLocation(scheduleParameters, rockContext);
                        paymentDetail = CreatePaymentDetail(scheduleParameters, person, locationId.Value, rockContext);
                        savedAccount  = CreateSavedAccount(scheduleParameters, paymentDetail, financialGateway, person, rockContext);
                        paymentInfo   = GetPaymentInfo(scheduleParameters, person, rockContext, totalAmount.Value, paymentDetail);
                    }
                    else
                    {
                        paymentDetail = savedAccount.FinancialPaymentDetail;
                        locationId    = paymentDetail.BillingLocationId;
                        paymentInfo   = savedAccount.GetReferencePayment();
                        UpdatePaymentInfoForSavedAccount(scheduleParameters, paymentInfo, person, rockContext, paymentDetail.BillingLocationId.Value, totalAmount.Value);
                    }

                    SaveLocationToFamilyIfNone(person, locationId.Value, rockContext);
                    string errorMessage;
                    var schedule = gatewayComponent.AddScheduledPayment(financialGateway, paymentSchedule, paymentInfo, out errorMessage);

                    if (schedule == null || !string.IsNullOrWhiteSpace(errorMessage))
                    {
                        GenerateResponse(HttpStatusCode.InternalServerError, errorMessage ?? "The gateway had a problem and/or did not create a transaction as expected");
                    }

                    schedule.TransactionFrequencyValueId = paymentSchedule.TransactionFrequencyValue.Id;

                    if (person.PrimaryAliasId.HasValue)
                    {
                        schedule.AuthorizedPersonAliasId = person.PrimaryAliasId.Value;
                    }

                    schedule.FinancialPaymentDetail = paymentDetail;
                    schedule.FinancialPaymentDetail.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;

                    if (paymentInfo.CreditCardTypeValue != null)
                    {
                        schedule.FinancialPaymentDetail.CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
                    }

                    foreach (var accountAmount in scheduleParameters.AmountDetails)
                    {
                        schedule.ScheduledTransactionDetails.Add(new FinancialScheduledTransactionDetail()
                        {
                            Amount    = accountAmount.Amount,
                            AccountId = accountAmount.TargetAccountId
                        });
                    }

                    new FinancialScheduledTransactionService(rockContext).Add(schedule);
                    rockContext.SaveChanges();
                });
            }
            catch (HttpResponseException exception)
            {
                return(exception.Response);
            }
            catch (Exception exception)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(exception.Message);
                return(response);
            }

            return(new HttpResponseMessage(HttpStatusCode.NoContent));
        }