diff --git a/AdvancedBilling.Standard/Controllers/APIExportsController.cs b/AdvancedBilling.Standard/Controllers/APIExportsController.cs index d4c0420..5e3faca 100644 --- a/AdvancedBilling.Standard/Controllers/APIExportsController.cs +++ b/AdvancedBilling.Standard/Controllers/APIExportsController.cs @@ -67,28 +67,28 @@ internal APIExportsController(GlobalConfiguration globalConfiguration) : base(gl .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. - /// Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. + /// This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. + /// Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. /// /// Object containing request parameters. - /// Returns the List of Models.Invoice response from the API call. - public List ListExportedInvoices( - Models.ListExportedInvoicesInput input) - => CoreHelper.RunTask(ListExportedInvoicesAsync(input)); + /// Returns the List of Models.Subscription response from the API call. + public List ListExportedSubscriptions( + Models.ListExportedSubscriptionsInput input) + => CoreHelper.RunTask(ListExportedSubscriptionsAsync(input)); /// - /// This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. - /// Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. + /// This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. + /// Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.Invoice response from the API call. - public async Task> ListExportedInvoicesAsync( - Models.ListExportedInvoicesInput input, + /// Returns the List of Models.Subscription response from the API call. + public async Task> ListExportedSubscriptionsAsync( + Models.ListExportedSubscriptionsInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/api_exports/invoices/{batch_id}/rows.json") + .Setup(HttpMethod.Get, "/api_exports/subscriptions/{batch_id}/rows.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("batch_id", input.BatchId).Required()) @@ -99,28 +99,28 @@ internal APIExportsController(GlobalConfiguration globalConfiguration) : base(gl .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. - /// Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. + /// This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. + /// Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. /// /// Object containing request parameters. - /// Returns the List of Models.Subscription response from the API call. - public List ListExportedSubscriptions( - Models.ListExportedSubscriptionsInput input) - => CoreHelper.RunTask(ListExportedSubscriptionsAsync(input)); + /// Returns the List of Models.Invoice response from the API call. + public List ListExportedInvoices( + Models.ListExportedInvoicesInput input) + => CoreHelper.RunTask(ListExportedInvoicesAsync(input)); /// - /// This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. - /// Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. + /// This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. + /// Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.Subscription response from the API call. - public async Task> ListExportedSubscriptionsAsync( - Models.ListExportedSubscriptionsInput input, + /// Returns the List of Models.Invoice response from the API call. + public async Task> ListExportedInvoicesAsync( + Models.ListExportedInvoicesInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/api_exports/subscriptions/{batch_id}/rows.json") + .Setup(HttpMethod.Get, "/api_exports/invoices/{batch_id}/rows.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("batch_id", input.BatchId).Required()) @@ -155,46 +155,31 @@ public Models.BatchJobResponse ExportProformaInvoices() .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This API creates an invoices export and returns a batchjob object. - /// - /// Returns the Models.BatchJobResponse response from the API call. - public Models.BatchJobResponse ExportInvoices() - => CoreHelper.RunTask(ExportInvoicesAsync()); - - /// - /// This API creates an invoices export and returns a batchjob object. - /// - /// cancellationToken. - /// Returns the Models.BatchJobResponse response from the API call. - public async Task ExportInvoicesAsync(CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/api_exports/invoices.json") - .WithAuth("global")) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("409", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This API creates a subscriptions export and returns a batchjob object. + /// This API returns a batchjob object for subscriptions export. /// + /// Required parameter: Id of a Batch Job.. /// Returns the Models.BatchJobResponse response from the API call. - public Models.BatchJobResponse ExportSubscriptions() - => CoreHelper.RunTask(ExportSubscriptionsAsync()); + public Models.BatchJobResponse ReadSubscriptionsExport( + string batchId) + => CoreHelper.RunTask(ReadSubscriptionsExportAsync(batchId)); /// - /// This API creates a subscriptions export and returns a batchjob object. + /// This API returns a batchjob object for subscriptions export. /// + /// Required parameter: Id of a Batch Job.. /// cancellationToken. /// Returns the Models.BatchJobResponse response from the API call. - public async Task ExportSubscriptionsAsync(CancellationToken cancellationToken = default) + public async Task ReadSubscriptionsExportAsync( + string batchId, + CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/api_exports/subscriptions.json") - .WithAuth("global")) + .Setup(HttpMethod.Get, "/api_exports/subscriptions/{batch_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("batch_id", batchId).Required()))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("409", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -226,54 +211,69 @@ public Models.BatchJobResponse ReadProformaInvoicesExport( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This API returns a batchjob object for invoices export. + /// This API creates an invoices export and returns a batchjob object. /// - /// Required parameter: Id of a Batch Job.. /// Returns the Models.BatchJobResponse response from the API call. - public Models.BatchJobResponse ReadInvoicesExport( - string batchId) - => CoreHelper.RunTask(ReadInvoicesExportAsync(batchId)); + public Models.BatchJobResponse ExportInvoices() + => CoreHelper.RunTask(ExportInvoicesAsync()); /// - /// This API returns a batchjob object for invoices export. + /// This API creates an invoices export and returns a batchjob object. /// - /// Required parameter: Id of a Batch Job.. /// cancellationToken. /// Returns the Models.BatchJobResponse response from the API call. - public async Task ReadInvoicesExportAsync( - string batchId, - CancellationToken cancellationToken = default) + public async Task ExportInvoicesAsync(CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/api_exports/invoices/{batch_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("batch_id", batchId).Required()))) + .Setup(HttpMethod.Post, "/api_exports/invoices.json") + .WithAuth("global")) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("409", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This API returns a batchjob object for subscriptions export. + /// This API creates a subscriptions export and returns a batchjob object. + /// + /// Returns the Models.BatchJobResponse response from the API call. + public Models.BatchJobResponse ExportSubscriptions() + => CoreHelper.RunTask(ExportSubscriptionsAsync()); + + /// + /// This API creates a subscriptions export and returns a batchjob object. + /// + /// cancellationToken. + /// Returns the Models.BatchJobResponse response from the API call. + public async Task ExportSubscriptionsAsync(CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/api_exports/subscriptions.json") + .WithAuth("global")) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("409", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This API returns a batchjob object for invoices export. /// /// Required parameter: Id of a Batch Job.. /// Returns the Models.BatchJobResponse response from the API call. - public Models.BatchJobResponse ReadSubscriptionsExport( + public Models.BatchJobResponse ReadInvoicesExport( string batchId) - => CoreHelper.RunTask(ReadSubscriptionsExportAsync(batchId)); + => CoreHelper.RunTask(ReadInvoicesExportAsync(batchId)); /// - /// This API returns a batchjob object for subscriptions export. + /// This API returns a batchjob object for invoices export. /// /// Required parameter: Id of a Batch Job.. /// cancellationToken. /// Returns the Models.BatchJobResponse response from the API call. - public async Task ReadSubscriptionsExportAsync( + public async Task ReadInvoicesExportAsync( string batchId, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/api_exports/subscriptions/{batch_id}.json") + .Setup(HttpMethod.Get, "/api_exports/invoices/{batch_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("batch_id", batchId).Required()))) diff --git a/AdvancedBilling.Standard/Controllers/AdvanceInvoiceController.cs b/AdvancedBilling.Standard/Controllers/AdvanceInvoiceController.cs index b5bb991..0e97b98 100644 --- a/AdvancedBilling.Standard/Controllers/AdvanceInvoiceController.cs +++ b/AdvancedBilling.Standard/Controllers/AdvanceInvoiceController.cs @@ -76,65 +76,65 @@ public Models.Invoice IssueAdvanceInvoice( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. + /// Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. + /// A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). /// /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . /// Returns the Models.Invoice response from the API call. - public Models.Invoice ReadAdvanceInvoice( - int subscriptionId) - => CoreHelper.RunTask(ReadAdvanceInvoiceAsync(subscriptionId)); + public Models.Invoice VoidAdvanceInvoice( + int subscriptionId, + Models.VoidInvoiceRequest body = null) + => CoreHelper.RunTask(VoidAdvanceInvoiceAsync(subscriptionId, body)); /// - /// Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. + /// Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. + /// A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). /// /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.Invoice response from the API call. - public async Task ReadAdvanceInvoiceAsync( + public async Task VoidAdvanceInvoiceAsync( int subscriptionId, + Models.VoidInvoiceRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/advance_invoice.json") + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/advance_invoice/void.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. - /// A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). + /// Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. /// /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . /// Returns the Models.Invoice response from the API call. - public Models.Invoice VoidAdvanceInvoice( - int subscriptionId, - Models.VoidInvoiceRequest body = null) - => CoreHelper.RunTask(VoidAdvanceInvoiceAsync(subscriptionId, body)); + public Models.Invoice ReadAdvanceInvoice( + int subscriptionId) + => CoreHelper.RunTask(ReadAdvanceInvoiceAsync(subscriptionId)); /// - /// Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. - /// A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). + /// Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. /// /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.Invoice response from the API call. - public async Task VoidAdvanceInvoiceAsync( + public async Task ReadAdvanceInvoiceAsync( int subscriptionId, - Models.VoidInvoiceRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/advance_invoice/void.json") + .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/advance_invoice.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Template(_template => _template.Setup("subscription_id", subscriptionId)))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); diff --git a/AdvancedBilling.Standard/Controllers/BaseController.cs b/AdvancedBilling.Standard/Controllers/BaseController.cs index 7600288..8657e77 100644 --- a/AdvancedBilling.Standard/Controllers/BaseController.cs +++ b/AdvancedBilling.Standard/Controllers/BaseController.cs @@ -29,12 +29,12 @@ public class BaseController protected static ErrorCase CreateErrorCase(string reason, Func error, bool isErrorTemplate = false) => new ErrorCase(reason, error, isErrorTemplate); - protected ApiCall CreateApiCall() + protected ApiCall CreateApiCall(ArraySerialization arraySerialization = ArraySerialization.CSV) => new ApiCall( globalConfiguration, compatibilityFactory, - globalErrors: globalErrors, - serialization: ArraySerialization.CSV + serialization: arraySerialization, + globalErrors: globalErrors ); private static readonly CompatibilityFactory compatibilityFactory = new CompatibilityFactory(); diff --git a/AdvancedBilling.Standard/Controllers/BillingPortalController.cs b/AdvancedBilling.Standard/Controllers/BillingPortalController.cs index ef18180..57236b4 100644 --- a/AdvancedBilling.Standard/Controllers/BillingPortalController.cs +++ b/AdvancedBilling.Standard/Controllers/BillingPortalController.cs @@ -34,6 +34,38 @@ public class BillingPortalController : BaseController /// internal BillingPortalController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } + /// + /// You can revoke a customer's Billing Portal invitation. + /// If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. + /// ## Limitations. + /// This endpoint will only return a JSON response. + /// + /// Required parameter: The Chargify id of the customer. + /// Returns the Models.RevokedInvitation response from the API call. + public Models.RevokedInvitation RevokeBillingPortalAccess( + int customerId) + => CoreHelper.RunTask(RevokeBillingPortalAccessAsync(customerId)); + + /// + /// You can revoke a customer's Billing Portal invitation. + /// If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. + /// ## Limitations. + /// This endpoint will only return a JSON response. + /// + /// Required parameter: The Chargify id of the customer. + /// cancellationToken. + /// Returns the Models.RevokedInvitation response from the API call. + public async Task RevokeBillingPortalAccessAsync( + int customerId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/portal/customers/{customer_id}/invitations/revoke.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("customer_id", customerId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// ## Billing Portal Documentation. /// Full documentation on how the Billing Portal operates within the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407648972443). @@ -162,37 +194,5 @@ public Models.ResentInvitation ResendBillingPortalInvitation( .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// You can revoke a customer's Billing Portal invitation. - /// If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. - /// ## Limitations. - /// This endpoint will only return a JSON response. - /// - /// Required parameter: The Chargify id of the customer. - /// Returns the Models.RevokedInvitation response from the API call. - public Models.RevokedInvitation RevokeBillingPortalAccess( - int customerId) - => CoreHelper.RunTask(RevokeBillingPortalAccessAsync(customerId)); - - /// - /// You can revoke a customer's Billing Portal invitation. - /// If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. - /// ## Limitations. - /// This endpoint will only return a JSON response. - /// - /// Required parameter: The Chargify id of the customer. - /// cancellationToken. - /// Returns the Models.RevokedInvitation response from the API call. - public async Task RevokeBillingPortalAccessAsync( - int customerId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/portal/customers/{customer_id}/invitations/revoke.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("customer_id", customerId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/ComponentsController.cs b/AdvancedBilling.Standard/Controllers/ComponentsController.cs index cec6308..11e46fe 100644 --- a/AdvancedBilling.Standard/Controllers/ComponentsController.cs +++ b/AdvancedBilling.Standard/Controllers/ComponentsController.cs @@ -16,7 +16,6 @@ namespace AdvancedBilling.Standard.Controllers using AdvancedBilling.Standard.Authentication; using AdvancedBilling.Standard.Exceptions; using AdvancedBilling.Standard.Http.Client; - using AdvancedBilling.Standard.Models.Containers; using AdvancedBilling.Standard.Utilities; using APIMatic.Core; using APIMatic.Core.Types; @@ -36,56 +35,320 @@ public class ComponentsController : BaseController internal ComponentsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// This request will create a component definition under the specified product family. These component definitions determine what components are named, how they are measured, and how much they cost. - /// Components can then be added and “allocated” for each subscription to a product in the product family. These component line-items affect how much a subscription will be charged, depending on the current allocations (i.e. 4 IP Addresses, or SSL “enabled”). - /// This documentation covers both component definitions and component line-items. Please understand the difference. - /// Please note that you may not edit components via API. To do so, please log into the application. - /// ### Component Documentation. + /// This request will create a component definition of kind **on_off_component** under the specified product family. On/Off component can then be added and “allocated” for a subscription. + /// On/off components are used for any flat fee, recurring add on (think $99/month for tech support or a flat add on shipping fee). /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - /// For information on how to record component usage against a subscription, please see the following resources:. - /// + [Proration and Component Allocations](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#applying-proration-and-recording-components). - /// + [Recording component usage against a subscription](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404606587917#recording-component-usage). /// /// Required parameter: The Chargify id of the product family to which the component belongs. - /// Required parameter: The component kind. /// Optional parameter: Example: . /// Returns the Models.ComponentResponse response from the API call. - public Models.ComponentResponse CreateComponent( + public Models.ComponentResponse CreateOnOffComponent( int productFamilyId, - Models.ComponentKindPath componentKind, - CreateComponentBody body = null) - => CoreHelper.RunTask(CreateComponentAsync(productFamilyId, componentKind, body)); + Models.CreateOnOffComponent body = null) + => CoreHelper.RunTask(CreateOnOffComponentAsync(productFamilyId, body)); /// - /// This request will create a component definition under the specified product family. These component definitions determine what components are named, how they are measured, and how much they cost. - /// Components can then be added and “allocated” for each subscription to a product in the product family. These component line-items affect how much a subscription will be charged, depending on the current allocations (i.e. 4 IP Addresses, or SSL “enabled”). - /// This documentation covers both component definitions and component line-items. Please understand the difference. - /// Please note that you may not edit components via API. To do so, please log into the application. - /// ### Component Documentation. + /// This request will create a component definition of kind **on_off_component** under the specified product family. On/Off component can then be added and “allocated” for a subscription. + /// On/off components are used for any flat fee, recurring add on (think $99/month for tech support or a flat add on shipping fee). /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - /// For information on how to record component usage against a subscription, please see the following resources:. - /// + [Proration and Component Allocations](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#applying-proration-and-recording-components). - /// + [Recording component usage against a subscription](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404606587917#recording-component-usage). /// /// Required parameter: The Chargify id of the product family to which the component belongs. - /// Required parameter: The component kind. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ComponentResponse response from the API call. - public async Task CreateComponentAsync( + public async Task CreateOnOffComponentAsync( int productFamilyId, - Models.ComponentKindPath componentKind, - CreateComponentBody body = null, + Models.CreateOnOffComponent body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/product_families/{product_family_id}/{component_kind}.json") + .Setup(HttpMethod.Post, "/product_families/{product_family_id}/on_off_components.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("product_family_id", productFamilyId)) - .Template(_template => _template.Setup("component_kind", ApiHelper.JsonSerialize(componentKind).Trim('\"'))) .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will create a component definition of kind **prepaid_usage_component** under the specified product family. Prepaid component can then be added and “allocated” for a subscription. + /// Prepaid components allow customers to pre-purchase units that can be used up over time on their subscription. In a sense, they are the mirror image of metered components; while metered components charge at the end of the period for the amount of units used, prepaid components are charged for at the time of purchase, and we subsequently keep track of the usage against the amount purchased. + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// Returns the Models.ComponentResponse response from the API call. + public Models.ComponentResponse CreatePrepaidUsageComponent( + int productFamilyId, + Models.CreatePrepaidComponent body = null) + => CoreHelper.RunTask(CreatePrepaidUsageComponentAsync(productFamilyId, body)); + + /// + /// This request will create a component definition of kind **prepaid_usage_component** under the specified product family. Prepaid component can then be added and “allocated” for a subscription. + /// Prepaid components allow customers to pre-purchase units that can be used up over time on their subscription. In a sense, they are the mirror image of metered components; while metered components charge at the end of the period for the amount of units used, prepaid components are charged for at the time of purchase, and we subsequently keep track of the usage against the amount purchased. + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ComponentResponse response from the API call. + public async Task CreatePrepaidUsageComponentAsync( + int productFamilyId, + Models.CreatePrepaidComponent body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/product_families/{product_family_id}/prepaid_usage_components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will create a component definition of kind **event_based_component** under the specified product family. Event-based component can then be added and “allocated” for a subscription. + /// Event-based components are similar to other component types, in that you define the component parameters (such as name and taxability) and the pricing. A key difference for the event-based component is that it must be attached to a metric. This is because the metric provides the component with the actual quantity used in computing what and how much will be billed each period for each subscription. + /// So, instead of reporting usage directly for each component (as you would with metered components), the usage is derived from analysis of your events. . + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// Returns the Models.ComponentResponse response from the API call. + public Models.ComponentResponse CreateEventBasedComponent( + int productFamilyId, + Models.CreateEBBComponent body = null) + => CoreHelper.RunTask(CreateEventBasedComponentAsync(productFamilyId, body)); + + /// + /// This request will create a component definition of kind **event_based_component** under the specified product family. Event-based component can then be added and “allocated” for a subscription. + /// Event-based components are similar to other component types, in that you define the component parameters (such as name and taxability) and the pricing. A key difference for the event-based component is that it must be attached to a metric. This is because the metric provides the component with the actual quantity used in computing what and how much will be billed each period for each subscription. + /// So, instead of reporting usage directly for each component (as you would with metered components), the usage is derived from analysis of your events. . + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ComponentResponse response from the API call. + public async Task CreateEventBasedComponentAsync( + int productFamilyId, + Models.CreateEBBComponent body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/product_families/{product_family_id}/event_based_components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will create a component definition of kind **quantity_based_component** under the specified product family. Quantity Based component can then be added and “allocated” for a subscription. + /// When defining Quantity Based component, You can choose one of 2 types:. + /// #### Recurring. + /// Recurring quantity-based components are used to bill for the number of some unit (think monthly software user licenses or the number of pairs of socks in a box-a-month club). This is most commonly associated with billing for user licenses, number of users, number of employees, etc. + /// #### One-time. + /// One-time quantity-based components are used to create ad hoc usage charges that do not recur. For example, at the time of signup, you might want to charge your customer a one-time fee for onboarding or other services. + /// The allocated quantity for one-time quantity-based components immediately gets reset back to zero after the allocation is made. + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// Returns the Models.ComponentResponse response from the API call. + public Models.ComponentResponse CreateQuantityBasedComponent( + int productFamilyId, + Models.CreateQuantityBasedComponent body = null) + => CoreHelper.RunTask(CreateQuantityBasedComponentAsync(productFamilyId, body)); + + /// + /// This request will create a component definition of kind **quantity_based_component** under the specified product family. Quantity Based component can then be added and “allocated” for a subscription. + /// When defining Quantity Based component, You can choose one of 2 types:. + /// #### Recurring. + /// Recurring quantity-based components are used to bill for the number of some unit (think monthly software user licenses or the number of pairs of socks in a box-a-month club). This is most commonly associated with billing for user licenses, number of users, number of employees, etc. + /// #### One-time. + /// One-time quantity-based components are used to create ad hoc usage charges that do not recur. For example, at the time of signup, you might want to charge your customer a one-time fee for onboarding or other services. + /// The allocated quantity for one-time quantity-based components immediately gets reset back to zero after the allocation is made. + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ComponentResponse response from the API call. + public async Task CreateQuantityBasedComponentAsync( + int productFamilyId, + Models.CreateQuantityBasedComponent body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/product_families/{product_family_id}/quantity_based_components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will create a component definition of kind **metered_component** under the specified product family. Metered component can then be added and “allocated” for a subscription. + /// Metered components are used to bill for any type of unit that resets to 0 at the end of the billing period (think daily Google Adwords clicks or monthly cell phone minutes). This is most commonly associated with usage-based billing and many other pricing schemes. + /// Note that this is different from recurring quantity-based components, which DO NOT reset to zero at the start of every billing period. If you want to bill for a quantity of something that does not change unless you change it, then you want quantity components, instead. + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// Returns the Models.ComponentResponse response from the API call. + public Models.ComponentResponse CreateMeteredComponent( + int productFamilyId, + Models.CreateMeteredComponent body = null) + => CoreHelper.RunTask(CreateMeteredComponentAsync(productFamilyId, body)); + + /// + /// This request will create a component definition of kind **metered_component** under the specified product family. Metered component can then be added and “allocated” for a subscription. + /// Metered components are used to bill for any type of unit that resets to 0 at the end of the billing period (think daily Google Adwords clicks or monthly cell phone minutes). This is most commonly associated with usage-based billing and many other pricing schemes. + /// Note that this is different from recurring quantity-based components, which DO NOT reset to zero at the start of every billing period. If you want to bill for a quantity of something that does not change unless you change it, then you want quantity components, instead. + /// For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + /// + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ComponentResponse response from the API call. + public async Task CreateMeteredComponentAsync( + int productFamilyId, + Models.CreateMeteredComponent body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/product_families/{product_family_id}/metered_components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will return a list of components for a site. + /// + /// Object containing request parameters. + /// Returns the List of Models.ComponentResponse response from the API call. + public List ListComponents( + Models.ListComponentsInput input) + => CoreHelper.RunTask(ListComponentsAsync(input)); + + /// + /// This request will return a list of components for a site. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the List of Models.ComponentResponse response from the API call. + public async Task> ListComponentsAsync( + Models.ListComponentsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("start_date", input.StartDate)) + .Query(_query => _query.Setup("end_date", input.EndDate)) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) + .Query(_query => _query.Setup("include_archived", input.IncludeArchived)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) + .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to read current price points that are associated with a component. + /// You may specify the component by using either the numeric id or the `handle:gold` syntax. + /// When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. + /// If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + /// + /// Object containing request parameters. + /// Returns the Models.ComponentPricePointsResponse response from the API call. + public Models.ComponentPricePointsResponse ListComponentPricePoints( + Models.ListComponentPricePointsInput input) + => CoreHelper.RunTask(ListComponentPricePointsAsync(input)); + + /// + /// Use this endpoint to read current price points that are associated with a component. + /// You may specify the component by using either the numeric id or the `handle:gold` syntax. + /// When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. + /// If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.ComponentPricePointsResponse response from the API call. + public async Task ListComponentPricePointsAsync( + Models.ListComponentPricePointsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/components/{component_id}/price_points.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("component_id", input.ComponentId)) + .Query(_query => _query.Setup("currency_prices", input.CurrencyPrices)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This method allows to retrieve a list of Components Price Points belonging to a Site. + /// + /// Object containing request parameters. + /// Returns the Models.ListComponentsPricePointsResponse response from the API call. + public Models.ListComponentsPricePointsResponse ListAllComponentPricePoints( + Models.ListAllComponentPricePointsInput input) + => CoreHelper.RunTask(ListAllComponentPricePointsAsync(input)); + + /// + /// This method allows to retrieve a list of Components Price Points belonging to a Site. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.ListComponentsPricePointsResponse response from the API call. + public async Task ListAllComponentPricePointsAsync( + Models.ListAllComponentPricePointsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/components_price_points.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("filter[date_field]", (input.FilterDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterDateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[end_date]", input.FilterEndDate.HasValue ? input.FilterEndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("filter[end_datetime]", input.FilterEndDatetime.HasValue ? input.FilterEndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("filter[start_date]", input.FilterStartDate.HasValue ? input.FilterStartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("filter[start_datetime]", input.FilterStartDatetime.HasValue ? input.FilterStartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) + .Query(_query => _query.Setup("filter[archived_at]", (input.FilterArchivedAt.HasValue) ? ApiHelper.JsonSerialize(input.FilterArchivedAt.Value).Trim('\"') : null)))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); @@ -117,73 +380,68 @@ public Models.ComponentResponse ReadComponentByHandle( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This request will return information regarding a component from a specific product family. - /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + /// Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. /// /// Required parameter: The Chargify id of the product family to which the component belongs. /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. - /// Returns the Models.ComponentResponse response from the API call. - public Models.ComponentResponse ReadComponentById( + /// Returns the Models.Component response from the API call. + public Models.Component ArchiveComponent( int productFamilyId, string componentId) - => CoreHelper.RunTask(ReadComponentByIdAsync(productFamilyId, componentId)); + => CoreHelper.RunTask(ArchiveComponentAsync(productFamilyId, componentId)); /// - /// This request will return information regarding a component from a specific product family. - /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + /// Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. /// /// Required parameter: The Chargify id of the product family to which the component belongs. /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. /// cancellationToken. - /// Returns the Models.ComponentResponse response from the API call. - public async Task ReadComponentByIdAsync( + /// Returns the Models.Component response from the API call. + public async Task ArchiveComponentAsync( int productFamilyId, string componentId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/product_families/{product_family_id}/components/{component_id}.json") + .Setup(HttpMethod.Delete, "/product_families/{product_family_id}/components/{component_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("product_family_id", productFamilyId)) .Template(_template => _template.Setup("component_id", componentId).Required()))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This request will update a component from a specific product family. + /// This request will update a component. /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. /// - /// Required parameter: The Chargify id of the product family to which the component belongs. - /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. + /// Required parameter: The id or handle of the component. /// Optional parameter: Example: . /// Returns the Models.ComponentResponse response from the API call. - public Models.ComponentResponse UpdateProductFamilyComponent( - int productFamilyId, + public Models.ComponentResponse UpdateComponent( string componentId, Models.UpdateComponentRequest body = null) - => CoreHelper.RunTask(UpdateProductFamilyComponentAsync(productFamilyId, componentId, body)); + => CoreHelper.RunTask(UpdateComponentAsync(componentId, body)); /// - /// This request will update a component from a specific product family. + /// This request will update a component. /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. /// - /// Required parameter: The Chargify id of the product family to which the component belongs. - /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. + /// Required parameter: The id or handle of the component. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ComponentResponse response from the API call. - public async Task UpdateProductFamilyComponentAsync( - int productFamilyId, + public async Task UpdateComponentAsync( string componentId, Models.UpdateComponentRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/product_families/{product_family_id}/components/{component_id}.json") + .Setup(HttpMethod.Put, "/components/{component_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("product_family_id", productFamilyId)) .Template(_template => _template.Setup("component_id", componentId).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler @@ -191,103 +449,182 @@ public Models.ComponentResponse UpdateProductFamilyComponent( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. + /// When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. + /// Passing in a price bracket without an `id` will attempt to create a new price. + /// Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. + /// Note: Custom price points cannot be updated directly. They must be edited through the Subscription. + /// + /// Required parameter: The Chargify id of the component to which the price point belongs. + /// Required parameter: The Chargify id of the price point. + /// Optional parameter: Example: . + /// Returns the Models.ComponentPricePointResponse response from the API call. + public Models.ComponentPricePointResponse UpdateComponentPricePoint( + int componentId, + int pricePointId, + Models.UpdateComponentPricePointRequest body = null) + => CoreHelper.RunTask(UpdateComponentPricePointAsync(componentId, pricePointId, body)); + + /// + /// When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. + /// Passing in a price bracket without an `id` will attempt to create a new price. + /// Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. + /// Note: Custom price points cannot be updated directly. They must be edited through the Subscription. + /// + /// Required parameter: The Chargify id of the component to which the price point belongs. + /// Required parameter: The Chargify id of the price point. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ComponentPricePointResponse response from the API call. + public async Task UpdateComponentPricePointAsync( + int componentId, + int pricePointId, + Models.UpdateComponentPricePointRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/components/{component_id}/price_points/{price_point_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("component_id", componentId)) + .Template(_template => _template.Setup("price_point_id", pricePointId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. + /// + /// Required parameter: The Chargify id of the component to which the price point belongs. + /// Required parameter: The Chargify id of the price point. + /// Returns the Models.ComponentPricePointResponse response from the API call. + public Models.ComponentPricePointResponse ArchiveComponentPricePoint( + int componentId, + int pricePointId) + => CoreHelper.RunTask(ArchiveComponentPricePointAsync(componentId, pricePointId)); + + /// + /// A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. + /// + /// Required parameter: The Chargify id of the component to which the price point belongs. + /// Required parameter: The Chargify id of the price point. + /// cancellationToken. + /// Returns the Models.ComponentPricePointResponse response from the API call. + public async Task ArchiveComponentPricePointAsync( + int componentId, + int pricePointId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/components/{component_id}/price_points/{price_point_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("component_id", componentId)) + .Template(_template => _template.Setup("price_point_id", pricePointId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to unarchive a component price point. + /// + /// Required parameter: The Chargify id of the component to which the price point belongs. + /// Required parameter: The Chargify id of the price point. + /// Returns the Models.ComponentPricePointResponse response from the API call. + public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( + int componentId, + int pricePointId) + => CoreHelper.RunTask(UnarchiveComponentPricePointAsync(componentId, pricePointId)); + + /// + /// Use this endpoint to unarchive a component price point. + /// + /// Required parameter: The Chargify id of the component to which the price point belongs. + /// Required parameter: The Chargify id of the price point. + /// cancellationToken. + /// Returns the Models.ComponentPricePointResponse response from the API call. + public async Task UnarchiveComponentPricePointAsync( + int componentId, + int pricePointId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/components/{component_id}/price_points/{price_point_id}/unarchive.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("component_id", componentId)) + .Template(_template => _template.Setup("price_point_id", pricePointId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will return information regarding a component from a specific product family. + /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. /// /// Required parameter: The Chargify id of the product family to which the component belongs. /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. - /// Returns the Models.Component response from the API call. - public Models.Component ArchiveComponent( + /// Returns the Models.ComponentResponse response from the API call. + public Models.ComponentResponse ReadComponentById( int productFamilyId, string componentId) - => CoreHelper.RunTask(ArchiveComponentAsync(productFamilyId, componentId)); + => CoreHelper.RunTask(ReadComponentByIdAsync(productFamilyId, componentId)); /// - /// Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. + /// This request will return information regarding a component from a specific product family. + /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. /// /// Required parameter: The Chargify id of the product family to which the component belongs. /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. /// cancellationToken. - /// Returns the Models.Component response from the API call. - public async Task ArchiveComponentAsync( + /// Returns the Models.ComponentResponse response from the API call. + public async Task ReadComponentByIdAsync( int productFamilyId, string componentId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/product_families/{product_family_id}/components/{component_id}.json") + .Setup(HttpMethod.Get, "/product_families/{product_family_id}/components/{component_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("product_family_id", productFamilyId)) .Template(_template => _template.Setup("component_id", componentId).Required()))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This request will return a list of components for a site. - /// - /// Object containing request parameters. - /// Returns the List of Models.ComponentResponse response from the API call. - public List ListComponents( - Models.ListComponentsInput input) - => CoreHelper.RunTask(ListComponentsAsync(input)); - - /// - /// This request will return a list of components for a site. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the List of Models.ComponentResponse response from the API call. - public async Task> ListComponentsAsync( - Models.ListComponentsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/components.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("start_date", input.StartDate)) - .Query(_query => _query.Setup("end_date", input.EndDate)) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) - .Query(_query => _query.Setup("include_archived", input.IncludeArchived)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) - .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This request will update a component. + /// This request will update a component from a specific product family. /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. /// - /// Required parameter: The id or handle of the component. + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. /// Optional parameter: Example: . /// Returns the Models.ComponentResponse response from the API call. - public Models.ComponentResponse UpdateComponent( + public Models.ComponentResponse UpdateProductFamilyComponent( + int productFamilyId, string componentId, Models.UpdateComponentRequest body = null) - => CoreHelper.RunTask(UpdateComponentAsync(componentId, body)); + => CoreHelper.RunTask(UpdateProductFamilyComponentAsync(productFamilyId, componentId, body)); /// - /// This request will update a component. + /// This request will update a component from a specific product family. /// You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. /// - /// Required parameter: The id or handle of the component. + /// Required parameter: The Chargify id of the product family to which the component belongs. + /// Required parameter: Either the Chargify id of the component or the handle for the component prefixed with `handle:`. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ComponentResponse response from the API call. - public async Task UpdateComponentAsync( + public async Task UpdateProductFamilyComponentAsync( + int productFamilyId, string componentId, Models.UpdateComponentRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/components/{component_id}.json") + .Setup(HttpMethod.Put, "/product_families/{product_family_id}/components/{component_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_family_id", productFamilyId)) .Template(_template => _template.Setup("component_id", componentId).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler @@ -397,42 +734,6 @@ public Models.ComponentPricePointResponse CreateComponentPricePoint( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// Use this endpoint to read current price points that are associated with a component. - /// You may specify the component by using either the numeric id or the `handle:gold` syntax. - /// When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. - /// If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - /// - /// Object containing request parameters. - /// Returns the Models.ComponentPricePointsResponse response from the API call. - public Models.ComponentPricePointsResponse ListComponentPricePoints( - Models.ListComponentPricePointsInput input) - => CoreHelper.RunTask(ListComponentPricePointsAsync(input)); - - /// - /// Use this endpoint to read current price points that are associated with a component. - /// You may specify the component by using either the numeric id or the `handle:gold` syntax. - /// When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. - /// If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.ComponentPricePointsResponse response from the API call. - public async Task ListComponentPricePointsAsync( - Models.ListComponentPricePointsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/components/{component_id}/price_points.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("component_id", input.ComponentId)) - .Query(_query => _query.Setup("currency_prices", input.CurrencyPrices)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// Use this endpoint to create multiple component price points in one request. /// @@ -465,111 +766,6 @@ public Models.ComponentPricePointsResponse CreateComponentPricePoints( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. - /// Passing in a price bracket without an `id` will attempt to create a new price. - /// Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. - /// Note: Custom price points cannot be updated directly. They must be edited through the Subscription. - /// - /// Required parameter: The Chargify id of the component to which the price point belongs. - /// Required parameter: The Chargify id of the price point. - /// Optional parameter: Example: . - /// Returns the Models.ComponentPricePointResponse response from the API call. - public Models.ComponentPricePointResponse UpdateComponentPricePoint( - int componentId, - int pricePointId, - Models.UpdateComponentPricePointRequest body = null) - => CoreHelper.RunTask(UpdateComponentPricePointAsync(componentId, pricePointId, body)); - - /// - /// When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. - /// Passing in a price bracket without an `id` will attempt to create a new price. - /// Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. - /// Note: Custom price points cannot be updated directly. They must be edited through the Subscription. - /// - /// Required parameter: The Chargify id of the component to which the price point belongs. - /// Required parameter: The Chargify id of the price point. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.ComponentPricePointResponse response from the API call. - public async Task UpdateComponentPricePointAsync( - int componentId, - int pricePointId, - Models.UpdateComponentPricePointRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/components/{component_id}/price_points/{price_point_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("component_id", componentId)) - .Template(_template => _template.Setup("price_point_id", pricePointId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. - /// - /// Required parameter: The Chargify id of the component to which the price point belongs. - /// Required parameter: The Chargify id of the price point. - /// Returns the Models.ComponentPricePointResponse response from the API call. - public Models.ComponentPricePointResponse ArchiveComponentPricePoint( - int componentId, - int pricePointId) - => CoreHelper.RunTask(ArchiveComponentPricePointAsync(componentId, pricePointId)); - - /// - /// A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. - /// - /// Required parameter: The Chargify id of the component to which the price point belongs. - /// Required parameter: The Chargify id of the price point. - /// cancellationToken. - /// Returns the Models.ComponentPricePointResponse response from the API call. - public async Task ArchiveComponentPricePointAsync( - int componentId, - int pricePointId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/components/{component_id}/price_points/{price_point_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("component_id", componentId)) - .Template(_template => _template.Setup("price_point_id", pricePointId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to unarchive a component price point. - /// - /// Required parameter: The Chargify id of the component to which the price point belongs. - /// Required parameter: The Chargify id of the price point. - /// Returns the Models.ComponentPricePointResponse response from the API call. - public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( - int componentId, - int pricePointId) - => CoreHelper.RunTask(UnarchiveComponentPricePointAsync(componentId, pricePointId)); - - /// - /// Use this endpoint to unarchive a component price point. - /// - /// Required parameter: The Chargify id of the component to which the price point belongs. - /// Required parameter: The Chargify id of the price point. - /// cancellationToken. - /// Returns the Models.ComponentPricePointResponse response from the API call. - public async Task UnarchiveComponentPricePointAsync( - int componentId, - int pricePointId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/components/{component_id}/price_points/{price_point_id}/unarchive.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("component_id", componentId)) - .Template(_template => _template.Setup("price_point_id", pricePointId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. /// When creating currency prices, they need to mirror the structure of your primary pricing. For each price level defined on the component price point, there should be a matching price level created in the given currency. @@ -577,8 +773,8 @@ public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( /// /// Required parameter: The Chargify id of the price point. /// Optional parameter: Example: . - /// Returns the List of Models.CurrencyPrice response from the API call. - public List CreateCurrencyPrices( + /// Returns the Models.ComponentCurrencyPricesResponse response from the API call. + public Models.ComponentCurrencyPricesResponse CreateCurrencyPrices( int pricePointId, Models.CreateCurrencyPricesRequest body = null) => CoreHelper.RunTask(CreateCurrencyPricesAsync(pricePointId, body)); @@ -591,12 +787,12 @@ public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( /// Required parameter: The Chargify id of the price point. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the List of Models.CurrencyPrice response from the API call. - public async Task> CreateCurrencyPricesAsync( + /// Returns the Models.ComponentCurrencyPricesResponse response from the API call. + public async Task CreateCurrencyPricesAsync( int pricePointId, Models.CreateCurrencyPricesRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Post, "/price_points/{price_point_id}/currency_prices.json") .WithAuth("global") @@ -604,6 +800,8 @@ public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("price_point_id", pricePointId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("Unprocessable Entity (WebDAV)", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -612,8 +810,8 @@ public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( /// /// Required parameter: The Chargify id of the price point. /// Optional parameter: Example: . - /// Returns the List of Models.CurrencyPrice response from the API call. - public List UpdateCurrencyPrices( + /// Returns the Models.ComponentCurrencyPricesResponse response from the API call. + public Models.ComponentCurrencyPricesResponse UpdateCurrencyPrices( int pricePointId, Models.UpdateCurrencyPricesRequest body = null) => CoreHelper.RunTask(UpdateCurrencyPricesAsync(pricePointId, body)); @@ -625,12 +823,12 @@ public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( /// Required parameter: The Chargify id of the price point. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the List of Models.CurrencyPrice response from the API call. - public async Task> UpdateCurrencyPricesAsync( + /// Returns the Models.ComponentCurrencyPricesResponse response from the API call. + public async Task UpdateCurrencyPricesAsync( int pricePointId, Models.UpdateCurrencyPricesRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Put, "/price_points/{price_point_id}/currency_prices.json") .WithAuth("global") @@ -638,45 +836,8 @@ public Models.ComponentPricePointResponse UnarchiveComponentPricePoint( .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("price_point_id", pricePointId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This method allows to retrieve a list of Components Price Points belonging to a Site. - /// - /// Object containing request parameters. - /// Returns the Models.ListComponentsPricePointsResponse response from the API call. - public Models.ListComponentsPricePointsResponse ListAllComponentPricePoints( - Models.ListAllComponentPricePointsInput input) - => CoreHelper.RunTask(ListAllComponentPricePointsAsync(input)); - - /// - /// This method allows to retrieve a list of Components Price Points belonging to a Site. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.ListComponentsPricePointsResponse response from the API call. - public async Task ListAllComponentPricePointsAsync( - Models.ListAllComponentPricePointsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/components_price_points.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("filter[date_field]", (input.FilterDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterDateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[end_date]", input.FilterEndDate.HasValue ? input.FilterEndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("filter[end_datetime]", input.FilterEndDatetime.HasValue ? input.FilterEndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("filter[start_date]", input.FilterStartDate.HasValue ? input.FilterStartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("filter[start_datetime]", input.FilterStartDatetime.HasValue ? input.FilterStartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())) - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) - .Query(_query => _query.Setup("filter[archived_at]", (input.FilterArchivedAt.HasValue) ? ApiHelper.JsonSerialize(input.FilterArchivedAt.Value).Trim('\"') : null)))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("Unprocessable Entity (WebDAV)", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/CouponsController.cs b/AdvancedBilling.Standard/Controllers/CouponsController.cs index 83fec58..2a1cbd8 100644 --- a/AdvancedBilling.Standard/Controllers/CouponsController.cs +++ b/AdvancedBilling.Standard/Controllers/CouponsController.cs @@ -82,115 +82,6 @@ public Models.CouponResponse CreateCoupon( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// List coupons for a specific Product Family in a Site. - /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - /// - /// Object containing request parameters. - /// Returns the List of Models.CouponResponse response from the API call. - public List ListCouponsForProductFamily( - Models.ListCouponsForProductFamilyInput input) - => CoreHelper.RunTask(ListCouponsForProductFamilyAsync(input)); - - /// - /// List coupons for a specific Product Family in a Site. - /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the List of Models.CouponResponse response from the API call. - public async Task> ListCouponsForProductFamilyAsync( - Models.ListCouponsForProductFamilyInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/product_families/{product_family_id}/coupons.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_family_id", input.ProductFamilyId)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("filter[date_field]", (input.FilterDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterDateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[end_date]", input.FilterEndDate.HasValue ? input.FilterEndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("filter[end_datetime]", input.FilterEndDatetime.HasValue ? input.FilterEndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("filter[start_date]", input.FilterStartDate.HasValue ? input.FilterStartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("filter[start_datetime]", input.FilterStartDatetime.HasValue ? input.FilterStartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) - .Query(_query => _query.Setup("filter[codes]", input.FilterCodes)) - .Query(_query => _query.Setup("currency_prices", input.CurrencyPrices)) - .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. - /// If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. - /// - /// Optional parameter: The Chargify id of the product family to which the coupon belongs. - /// Optional parameter: The code of the coupon. - /// Returns the Models.CouponResponse response from the API call. - public Models.CouponResponse ReadCouponByCode( - int? productFamilyId = null, - string code = null) - => CoreHelper.RunTask(ReadCouponByCodeAsync(productFamilyId, code)); - - /// - /// You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. - /// If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. - /// - /// Optional parameter: The Chargify id of the product family to which the coupon belongs. - /// Optional parameter: The code of the coupon. - /// cancellationToken. - /// Returns the Models.CouponResponse response from the API call. - public async Task ReadCouponByCodeAsync( - int? productFamilyId = null, - string code = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/coupons/find.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("product_family_id", productFamilyId)) - .Query(_query => _query.Setup("code", code)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. - /// If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. - /// When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. - /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - /// - /// Required parameter: The Chargify id of the product family to which the coupon belongs. - /// Required parameter: The Chargify id of the coupon. - /// Returns the Models.CouponResponse response from the API call. - public Models.CouponResponse ReadCoupon( - int productFamilyId, - int couponId) - => CoreHelper.RunTask(ReadCouponAsync(productFamilyId, couponId)); - - /// - /// You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. - /// If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. - /// When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. - /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - /// - /// Required parameter: The Chargify id of the product family to which the coupon belongs. - /// Required parameter: The Chargify id of the coupon. - /// cancellationToken. - /// Returns the Models.CouponResponse response from the API call. - public async Task ReadCouponAsync( - int productFamilyId, - int couponId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/product_families/{product_family_id}/coupons/{coupon_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_family_id", productFamilyId)) - .Template(_template => _template.Setup("coupon_id", couponId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// ## Update Coupon. /// You can update a Coupon via the API with a PUT request to the resource endpoint. @@ -234,41 +125,6 @@ public Models.CouponResponse UpdateCoupon( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// You can archive a Coupon via the API with the archive method. - /// Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. - /// The `archived_at` date and time will be assigned. - /// - /// Required parameter: The Chargify id of the product family to which the coupon belongs. - /// Required parameter: The Chargify id of the coupon. - /// Returns the Models.CouponResponse response from the API call. - public Models.CouponResponse ArchiveCoupon( - int productFamilyId, - int couponId) - => CoreHelper.RunTask(ArchiveCouponAsync(productFamilyId, couponId)); - - /// - /// You can archive a Coupon via the API with the archive method. - /// Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. - /// The `archived_at` date and time will be assigned. - /// - /// Required parameter: The Chargify id of the product family to which the coupon belongs. - /// Required parameter: The Chargify id of the coupon. - /// cancellationToken. - /// Returns the Models.CouponResponse response from the API call. - public async Task ArchiveCouponAsync( - int productFamilyId, - int couponId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/product_families/{product_family_id}/coupons/{coupon_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_family_id", productFamilyId)) - .Template(_template => _template.Setup("coupon_id", couponId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// You can retrieve a list of coupons. /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. @@ -343,99 +199,6 @@ public Models.CouponResponse ArchiveCoupon( .Template(_template => _template.Setup("coupon_id", couponId)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. - /// If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported:. - /// + Coupon not found. - /// + Coupon is invalid. - /// + Coupon expired. - /// If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. - /// Eg. - /// ```. - /// https://.chargify.com/product_families/handle:/coupons/validate.?code=. - /// ```. - /// Or:. - /// ```. - /// https://.chargify.com/coupons/validate.?code=&product_family_id=. - /// ```. - /// - /// Required parameter: The code of the coupon. - /// Optional parameter: The Chargify id of the product family to which the coupon belongs. - /// Returns the Models.CouponResponse response from the API call. - public Models.CouponResponse ValidateCoupon( - string code, - int? productFamilyId = null) - => CoreHelper.RunTask(ValidateCouponAsync(code, productFamilyId)); - - /// - /// You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. - /// If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported:. - /// + Coupon not found. - /// + Coupon is invalid. - /// + Coupon expired. - /// If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. - /// Eg. - /// ```. - /// https://.chargify.com/product_families/handle:/coupons/validate.?code=. - /// ```. - /// Or:. - /// ```. - /// https://.chargify.com/coupons/validate.?code=&product_family_id=. - /// ```. - /// - /// Required parameter: The code of the coupon. - /// Optional parameter: The Chargify id of the product family to which the coupon belongs. - /// cancellationToken. - /// Returns the Models.CouponResponse response from the API call. - public async Task ValidateCouponAsync( - string code, - int? productFamilyId = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/coupons/validate.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("code", code).Required()) - .Query(_query => _query.Setup("product_family_id", productFamilyId)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new SingleStringErrorResponseException(_reason, _context)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. - /// Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. - /// - /// Required parameter: The Chargify id of the coupon. - /// Optional parameter: Example: . - /// Returns the Models.CouponCurrencyResponse response from the API call. - public Models.CouponCurrencyResponse UpdateCouponCurrencyPrices( - int couponId, - Models.CouponCurrencyRequest body = null) - => CoreHelper.RunTask(UpdateCouponCurrencyPricesAsync(couponId, body)); - - /// - /// This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. - /// Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. - /// - /// Required parameter: The Chargify id of the coupon. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.CouponCurrencyResponse response from the API call. - public async Task UpdateCouponCurrencyPricesAsync( - int couponId, - Models.CouponCurrencyRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/coupons/{coupon_id}/currency_prices.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("coupon_id", couponId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// ## Coupon Subcodes Intro. /// Coupon Subcodes allow you to create a set of unique codes that allow you to expand the use of one coupon. @@ -514,6 +277,74 @@ public Models.CouponSubcodesResponse CreateCouponSubcodes( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. + /// If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. + /// + /// Optional parameter: The Chargify id of the product family to which the coupon belongs. + /// Optional parameter: The code of the coupon. + /// Returns the Models.CouponResponse response from the API call. + public Models.CouponResponse ReadCouponByCode( + int? productFamilyId = null, + string code = null) + => CoreHelper.RunTask(ReadCouponByCodeAsync(productFamilyId, code)); + + /// + /// You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. + /// If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. + /// + /// Optional parameter: The Chargify id of the product family to which the coupon belongs. + /// Optional parameter: The code of the coupon. + /// cancellationToken. + /// Returns the Models.CouponResponse response from the API call. + public async Task ReadCouponByCodeAsync( + int? productFamilyId = null, + string code = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/coupons/find.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("product_family_id", productFamilyId)) + .Query(_query => _query.Setup("code", code)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// You can archive a Coupon via the API with the archive method. + /// Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. + /// The `archived_at` date and time will be assigned. + /// + /// Required parameter: The Chargify id of the product family to which the coupon belongs. + /// Required parameter: The Chargify id of the coupon. + /// Returns the Models.CouponResponse response from the API call. + public Models.CouponResponse ArchiveCoupon( + int productFamilyId, + int couponId) + => CoreHelper.RunTask(ArchiveCouponAsync(productFamilyId, couponId)); + + /// + /// You can archive a Coupon via the API with the archive method. + /// Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. + /// The `archived_at` date and time will be assigned. + /// + /// Required parameter: The Chargify id of the product family to which the coupon belongs. + /// Required parameter: The Chargify id of the coupon. + /// cancellationToken. + /// Returns the Models.CouponResponse response from the API call. + public async Task ArchiveCouponAsync( + int productFamilyId, + int couponId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/product_families/{product_family_id}/coupons/{coupon_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Template(_template => _template.Setup("coupon_id", couponId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// This request allows you to request the subcodes that are attached to a coupon. /// @@ -542,6 +373,102 @@ public Models.CouponSubcodes ListCouponSubcodes( .Query(_query => _query.Setup("per_page", input.PerPage)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. + /// If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. + /// When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. + /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + /// + /// Required parameter: The Chargify id of the product family to which the coupon belongs. + /// Required parameter: The Chargify id of the coupon. + /// Returns the Models.CouponResponse response from the API call. + public Models.CouponResponse ReadCoupon( + int productFamilyId, + int couponId) + => CoreHelper.RunTask(ReadCouponAsync(productFamilyId, couponId)); + + /// + /// You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. + /// If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. + /// When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. + /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + /// + /// Required parameter: The Chargify id of the product family to which the coupon belongs. + /// Required parameter: The Chargify id of the coupon. + /// cancellationToken. + /// Returns the Models.CouponResponse response from the API call. + public async Task ReadCouponAsync( + int productFamilyId, + int couponId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/product_families/{product_family_id}/coupons/{coupon_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Template(_template => _template.Setup("coupon_id", couponId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. + /// If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported:. + /// + Coupon not found. + /// + Coupon is invalid. + /// + Coupon expired. + /// If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. + /// Eg. + /// ```. + /// https://.chargify.com/product_families/handle:/coupons/validate.?code=. + /// ```. + /// Or:. + /// ```. + /// https://.chargify.com/coupons/validate.?code=&product_family_id=. + /// ```. + /// + /// Required parameter: The code of the coupon. + /// Optional parameter: The Chargify id of the product family to which the coupon belongs. + /// Returns the Models.CouponResponse response from the API call. + public Models.CouponResponse ValidateCoupon( + string code, + int? productFamilyId = null) + => CoreHelper.RunTask(ValidateCouponAsync(code, productFamilyId)); + + /// + /// You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. + /// If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported:. + /// + Coupon not found. + /// + Coupon is invalid. + /// + Coupon expired. + /// If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. + /// Eg. + /// ```. + /// https://.chargify.com/product_families/handle:/coupons/validate.?code=. + /// ```. + /// Or:. + /// ```. + /// https://.chargify.com/coupons/validate.?code=&product_family_id=. + /// ```. + /// + /// Required parameter: The code of the coupon. + /// Optional parameter: The Chargify id of the product family to which the coupon belongs. + /// cancellationToken. + /// Returns the Models.CouponResponse response from the API call. + public async Task ValidateCouponAsync( + string code, + int? productFamilyId = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/coupons/validate.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("code", code).Required()) + .Query(_query => _query.Setup("product_family_id", productFamilyId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new SingleStringErrorResponseException(_reason, _context)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// You can update the subcodes for the given Coupon via the API with a PUT request to the resource endpoint. /// Send an array of new coupon subcodes. @@ -586,6 +513,79 @@ public Models.CouponSubcodesResponse UpdateCouponSubcodes( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// List coupons for a specific Product Family in a Site. + /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + /// + /// Object containing request parameters. + /// Returns the List of Models.CouponResponse response from the API call. + public List ListCouponsForProductFamily( + Models.ListCouponsForProductFamilyInput input) + => CoreHelper.RunTask(ListCouponsForProductFamilyAsync(input)); + + /// + /// List coupons for a specific Product Family in a Site. + /// If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the List of Models.CouponResponse response from the API call. + public async Task> ListCouponsForProductFamilyAsync( + Models.ListCouponsForProductFamilyInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/product_families/{product_family_id}/coupons.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("product_family_id", input.ProductFamilyId)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("filter[date_field]", (input.FilterDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterDateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[end_date]", input.FilterEndDate.HasValue ? input.FilterEndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("filter[end_datetime]", input.FilterEndDatetime.HasValue ? input.FilterEndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("filter[start_date]", input.FilterStartDate.HasValue ? input.FilterStartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("filter[start_datetime]", input.FilterStartDatetime.HasValue ? input.FilterStartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) + .Query(_query => _query.Setup("filter[codes]", input.FilterCodes)) + .Query(_query => _query.Setup("currency_prices", input.CurrencyPrices)) + .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. + /// Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. + /// + /// Required parameter: The Chargify id of the coupon. + /// Optional parameter: Example: . + /// Returns the Models.CouponCurrencyResponse response from the API call. + public Models.CouponCurrencyResponse UpdateCouponCurrencyPrices( + int couponId, + Models.CouponCurrencyRequest body = null) + => CoreHelper.RunTask(UpdateCouponCurrencyPricesAsync(couponId, body)); + + /// + /// This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. + /// Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. + /// + /// Required parameter: The Chargify id of the coupon. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.CouponCurrencyResponse response from the API call. + public async Task UpdateCouponCurrencyPricesAsync( + int couponId, + Models.CouponCurrencyRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/coupons/{coupon_id}/currency_prices.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("coupon_id", couponId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// ## Example. /// Given a coupon with an ID of 567, and a coupon subcode of 20OFF, the URL to `DELETE` this coupon subcode would be:. diff --git a/AdvancedBilling.Standard/Controllers/CustomFieldsController.cs b/AdvancedBilling.Standard/Controllers/CustomFieldsController.cs index c2302c4..1166e40 100644 --- a/AdvancedBilling.Standard/Controllers/CustomFieldsController.cs +++ b/AdvancedBilling.Standard/Controllers/CustomFieldsController.cs @@ -18,6 +18,7 @@ namespace AdvancedBilling.Standard.Controllers using AdvancedBilling.Standard.Http.Client; using AdvancedBilling.Standard.Utilities; using APIMatic.Core; + using APIMatic.Core.Http.Configuration; using APIMatic.Core.Types; using APIMatic.Core.Utilities; using APIMatic.Core.Utilities.Date.Xml; @@ -35,61 +36,72 @@ public class CustomFieldsController : BaseController internal CustomFieldsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// ## Custom Fields: Metafield Intro. - /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. - /// + **Metafield is the custom field**. - /// + **Metadata is the data populating the custom field.**. - /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields). - /// Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. - /// ## Create Metafields. - /// Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. - /// Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. - /// ### Metafields "On-the-Fly". - /// It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. - /// ### Metafield Scope Warning. - /// If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. + /// Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. /// /// Required parameter: the resource type to which the metafields belong. /// Optional parameter: Example: . /// Returns the List of Models.Metafield response from the API call. - public List CreateMetafields( + public List UpdateMetafield( Models.ResourceType resourceType, - Models.CreateMetafieldsRequest body = null) - => CoreHelper.RunTask(CreateMetafieldsAsync(resourceType, body)); + Models.UpdateMetafieldsRequest body = null) + => CoreHelper.RunTask(UpdateMetafieldAsync(resourceType, body)); /// - /// ## Custom Fields: Metafield Intro. - /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. - /// + **Metafield is the custom field**. - /// + **Metadata is the data populating the custom field.**. - /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields). - /// Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. - /// ## Create Metafields. - /// Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. - /// Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. - /// ### Metafields "On-the-Fly". - /// It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. - /// ### Metafield Scope Warning. - /// If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. + /// Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. /// /// Required parameter: the resource type to which the metafields belong. /// Optional parameter: Example: . /// cancellationToken. /// Returns the List of Models.Metafield response from the API call. - public async Task> CreateMetafieldsAsync( + public async Task> UpdateMetafieldAsync( Models.ResourceType resourceType, - Models.CreateMetafieldsRequest body = null, + Models.UpdateMetafieldsRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/{resource_type}/metafields.json") + .Setup(HttpMethod.Put, "/{resource_type}/metafields.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("resource_type", ApiHelper.JsonSerialize(resourceType).Trim('\"'))) .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This method allows you to update the existing metadata associated with a subscription or customer. + /// + /// Required parameter: the resource type to which the metafields belong. + /// Required parameter: The Chargify id of the customer or the subscription for which the metadata applies. + /// Optional parameter: Example: . + /// Returns the List of Models.Metadata response from the API call. + public List UpdateMetadata( + Models.ResourceType resourceType, + string resourceId, + Models.UpdateMetadataRequest body = null) + => CoreHelper.RunTask(UpdateMetadataAsync(resourceType, resourceId, body)); + + /// + /// This method allows you to update the existing metadata associated with a subscription or customer. + /// + /// Required parameter: the resource type to which the metafields belong. + /// Required parameter: The Chargify id of the customer or the subscription for which the metadata applies. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the List of Models.Metadata response from the API call. + public async Task> UpdateMetadataAsync( + Models.ResourceType resourceType, + string resourceId, + Models.UpdateMetadataRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/{resource_type}/{resource_id}/metadata.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("resource_type", ApiHelper.JsonSerialize(resourceType).Trim('\"'))) + .Template(_template => _template.Setup("resource_id", resourceId).Required()) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -122,48 +134,6 @@ public Models.ListMetafieldsResponse ListMetafields( .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. - /// - /// Required parameter: the resource type to which the metafields belong. - /// Required parameter: Name of the custom field.. - /// Optional parameter: This only applies when you are updating an existing record and you wish to rename the field. Note you must supply name and current_name to rename the field. - /// Optional parameter: Example: . - /// Returns the List of Models.Metafield response from the API call. - public List UpdateMetafield( - Models.ResourceType resourceType, - string name, - string currentName = null, - Models.UpdateMetafieldsRequest body = null) - => CoreHelper.RunTask(UpdateMetafieldAsync(resourceType, name, currentName, body)); - - /// - /// Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. - /// - /// Required parameter: the resource type to which the metafields belong. - /// Required parameter: Name of the custom field.. - /// Optional parameter: This only applies when you are updating an existing record and you wish to rename the field. Note you must supply name and current_name to rename the field. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the List of Models.Metafield response from the API call. - public async Task> UpdateMetafieldAsync( - Models.ResourceType resourceType, - string name, - string currentName = null, - Models.UpdateMetafieldsRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/{resource_type}/metafields.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("resource_type", ApiHelper.JsonSerialize(resourceType).Trim('\"'))) - .Query(_query => _query.Setup("name", name).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")) - .Query(_query => _query.Setup("current_name", currentName)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// Use the following method to delete a metafield. This will remove the metafield from the Site. /// Additionally, this will remove the metafield and associated metadata with all Subscriptions on the Site. @@ -198,67 +168,6 @@ public async Task DeleteMetafieldAsync( .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// ## Custom Fields: Metadata Intro. - /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. - /// + **Metafield is the custom field**. - /// + **Metadata is the data populating the custom field.**. - /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields). - /// Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. - /// ## Metadata limits. - /// Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. - /// ## Create Metadata. - /// This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. - /// ### Subscription or Customer Resource. - /// Please pay special attention to the resource you use when creating metadata. - /// - /// Required parameter: the resource type to which the metafields belong. - /// Required parameter: The Chargify id of the customer or the subscription for which the metadata applies. - /// Optional parameter: Example: . - /// Returns the List of Models.Metadata response from the API call. - public List CreateMetadata( - Models.ResourceType resourceType, - string resourceId, - Models.CreateMetadataRequest body = null) - => CoreHelper.RunTask(CreateMetadataAsync(resourceType, resourceId, body)); - - /// - /// ## Custom Fields: Metadata Intro. - /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. - /// + **Metafield is the custom field**. - /// + **Metadata is the data populating the custom field.**. - /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields). - /// Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. - /// ## Metadata limits. - /// Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. - /// ## Create Metadata. - /// This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. - /// ### Subscription or Customer Resource. - /// Please pay special attention to the resource you use when creating metadata. - /// - /// Required parameter: the resource type to which the metafields belong. - /// Required parameter: The Chargify id of the customer or the subscription for which the metadata applies. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the List of Models.Metadata response from the API call. - public async Task> CreateMetadataAsync( - Models.ResourceType resourceType, - string resourceId, - Models.CreateMetadataRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/{resource_type}/{resource_id}/metadata.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("resource_type", ApiHelper.JsonSerialize(resourceType).Trim('\"'))) - .Template(_template => _template.Setup("resource_id", resourceId).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("Unprocessable Entity (WebDAV)", (_reason, _context) => new SingleErrorResponseException(_reason, _context)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This request will list all of the metadata belonging to a particular resource (ie. subscription, customer) that is specified. /// ## Metadata Data. @@ -281,7 +190,7 @@ public Models.PaginatedMetadata ListMetadata( public async Task ListMetadataAsync( Models.ListMetadataInput input, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall(ArraySerialization.Plain) .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Get, "/{resource_type}/{resource_id}/metadata.json") .WithAuth("global") @@ -293,40 +202,122 @@ public Models.PaginatedMetadata ListMetadata( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method allows you to update the existing metadata associated with a subscription or customer. + /// ## Custom Fields: Metafield Intro. + /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. + /// + **Metafield is the custom field**. + /// + **Metadata is the data populating the custom field.**. + /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields). + /// Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. + /// ## Create Metafields. + /// Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. + /// Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. + /// ### Metafields "On-the-Fly". + /// It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. + /// ### Metafield Scope Warning. + /// If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. + /// + /// Required parameter: the resource type to which the metafields belong. + /// Optional parameter: Example: . + /// Returns the List of Models.Metafield response from the API call. + public List CreateMetafields( + Models.ResourceType resourceType, + Models.CreateMetafieldsRequest body = null) + => CoreHelper.RunTask(CreateMetafieldsAsync(resourceType, body)); + + /// + /// ## Custom Fields: Metafield Intro. + /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. + /// + **Metafield is the custom field**. + /// + **Metadata is the data populating the custom field.**. + /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields). + /// Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. + /// ## Create Metafields. + /// Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. + /// Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. + /// ### Metafields "On-the-Fly". + /// It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. + /// ### Metafield Scope Warning. + /// If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. + /// + /// Required parameter: the resource type to which the metafields belong. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the List of Models.Metafield response from the API call. + public async Task> CreateMetafieldsAsync( + Models.ResourceType resourceType, + Models.CreateMetafieldsRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/{resource_type}/metafields.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("resource_type", ApiHelper.JsonSerialize(resourceType).Trim('\"'))) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// ## Custom Fields: Metadata Intro. + /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. + /// + **Metafield is the custom field**. + /// + **Metadata is the data populating the custom field.**. + /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields). + /// Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. + /// ## Metadata limits. + /// Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. + /// ## Create Metadata. + /// This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. + /// ### Subscription or Customer Resource. + /// Please pay special attention to the resource you use when creating metadata. /// /// Required parameter: the resource type to which the metafields belong. /// Required parameter: The Chargify id of the customer or the subscription for which the metadata applies. /// Optional parameter: Example: . /// Returns the List of Models.Metadata response from the API call. - public List UpdateMetadata( + public List CreateMetadata( Models.ResourceType resourceType, string resourceId, - Models.UpdateMetadataRequest body = null) - => CoreHelper.RunTask(UpdateMetadataAsync(resourceType, resourceId, body)); + Models.CreateMetadataRequest body = null) + => CoreHelper.RunTask(CreateMetadataAsync(resourceType, resourceId, body)); /// - /// This method allows you to update the existing metadata associated with a subscription or customer. + /// ## Custom Fields: Metadata Intro. + /// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. + /// + **Metafield is the custom field**. + /// + **Metadata is the data populating the custom field.**. + /// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields). + /// Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. + /// ## Metadata limits. + /// Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. + /// ## Create Metadata. + /// This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. + /// ### Subscription or Customer Resource. + /// Please pay special attention to the resource you use when creating metadata. /// /// Required parameter: the resource type to which the metafields belong. /// Required parameter: The Chargify id of the customer or the subscription for which the metadata applies. /// Optional parameter: Example: . /// cancellationToken. /// Returns the List of Models.Metadata response from the API call. - public async Task> UpdateMetadataAsync( + public async Task> CreateMetadataAsync( Models.ResourceType resourceType, string resourceId, - Models.UpdateMetadataRequest body = null, + Models.CreateMetadataRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/{resource_type}/{resource_id}/metadata.json") + .Setup(HttpMethod.Post, "/{resource_type}/{resource_id}/metadata.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("resource_type", ApiHelper.JsonSerialize(resourceType).Trim('\"'))) .Template(_template => _template.Setup("resource_id", resourceId).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -384,7 +375,7 @@ public async Task DeleteMetadataAsync( string name = null, List names = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall(ArraySerialization.Plain) .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Delete, "/{resource_type}/{resource_id}/metadata.json") .WithAuth("global") diff --git a/AdvancedBilling.Standard/Controllers/CustomersController.cs b/AdvancedBilling.Standard/Controllers/CustomersController.cs index 6b6223d..b46cf5c 100644 --- a/AdvancedBilling.Standard/Controllers/CustomersController.cs +++ b/AdvancedBilling.Standard/Controllers/CustomersController.cs @@ -88,116 +88,90 @@ public Models.CustomerResponse CreateCustomer( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This request will by default list all customers associated with your Site. - /// ## Find Customer. - /// Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. - /// Common use cases are:. - /// + Search by an email. - /// + Search by a Chargify ID. - /// + Search by an organization. - /// + Search by a reference value from your application. - /// + Search by a first or last name. - /// To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). + /// This method allows to update the Customer. /// - /// Object containing request parameters. - /// Returns the List of Models.CustomerResponse response from the API call. - public List ListCustomers( - Models.ListCustomersInput input) - => CoreHelper.RunTask(ListCustomersAsync(input)); + /// Required parameter: The Chargify id of the customer. + /// Optional parameter: Example: . + /// Returns the Models.CustomerResponse response from the API call. + public Models.CustomerResponse UpdateCustomer( + int id, + Models.UpdateCustomerRequest body = null) + => CoreHelper.RunTask(UpdateCustomerAsync(id, body)); /// - /// This request will by default list all customers associated with your Site. - /// ## Find Customer. - /// Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. - /// Common use cases are:. - /// + Search by an email. - /// + Search by a Chargify ID. - /// + Search by an organization. - /// + Search by a reference value from your application. - /// + Search by a first or last name. - /// To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). + /// This method allows to update the Customer. /// - /// Object containing request parameters. + /// Required parameter: The Chargify id of the customer. + /// Optional parameter: Example: . /// cancellationToken. - /// Returns the List of Models.CustomerResponse response from the API call. - public async Task> ListCustomersAsync( - Models.ListCustomersInput input, + /// Returns the Models.CustomerResponse response from the API call. + public async Task UpdateCustomerAsync( + int id, + Models.UpdateCustomerRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/customers.json") + .Setup(HttpMethod.Put, "/customers/{id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("start_date", input.StartDate)) - .Query(_query => _query.Setup("end_date", input.EndDate)) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) - .Query(_query => _query.Setup("q", input.Q)))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("id", id)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new CustomerErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method allows to retrieve the Customer properties by Chargify-generated Customer ID. + /// Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. /// - /// Required parameter: The Chargify id of the customer. + /// Required parameter: Customer reference. /// Returns the Models.CustomerResponse response from the API call. - public Models.CustomerResponse ReadCustomer( - int id) - => CoreHelper.RunTask(ReadCustomerAsync(id)); + public Models.CustomerResponse ReadCustomerByReference( + string reference) + => CoreHelper.RunTask(ReadCustomerByReferenceAsync(reference)); /// - /// This method allows to retrieve the Customer properties by Chargify-generated Customer ID. + /// Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. /// - /// Required parameter: The Chargify id of the customer. + /// Required parameter: Customer reference. /// cancellationToken. /// Returns the Models.CustomerResponse response from the API call. - public async Task ReadCustomerAsync( - int id, + public async Task ReadCustomerByReferenceAsync( + string reference, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/customers/{id}.json") + .Setup(HttpMethod.Get, "/customers/lookup.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("id", id)))) + .Query(_query => _query.Setup("reference", reference).Required()))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method allows to update the Customer. + /// This method allows to retrieve the Customer properties by Chargify-generated Customer ID. /// /// Required parameter: The Chargify id of the customer. - /// Optional parameter: Example: . /// Returns the Models.CustomerResponse response from the API call. - public Models.CustomerResponse UpdateCustomer( - int id, - Models.UpdateCustomerRequest body = null) - => CoreHelper.RunTask(UpdateCustomerAsync(id, body)); + public Models.CustomerResponse ReadCustomer( + int id) + => CoreHelper.RunTask(ReadCustomerAsync(id)); /// - /// This method allows to update the Customer. + /// This method allows to retrieve the Customer properties by Chargify-generated Customer ID. /// /// Required parameter: The Chargify id of the customer. - /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.CustomerResponse response from the API call. - public async Task UpdateCustomerAsync( + public async Task ReadCustomerAsync( int id, - Models.UpdateCustomerRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/customers/{id}.json") + .Setup(HttpMethod.Get, "/customers/{id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("id", id)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new CustomerErrorResponseException(_reason, _context), true))) + .Template(_template => _template.Setup("id", id)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -226,29 +200,55 @@ public async Task DeleteCustomerAsync( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. + /// This request will by default list all customers associated with your Site. + /// ## Find Customer. + /// Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. + /// Common use cases are:. + /// + Search by an email. + /// + Search by a Chargify ID. + /// + Search by an organization. + /// + Search by a reference value from your application. + /// + Search by a first or last name. + /// To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). /// - /// Required parameter: Customer reference. - /// Returns the Models.CustomerResponse response from the API call. - public Models.CustomerResponse ReadCustomerByReference( - string reference) - => CoreHelper.RunTask(ReadCustomerByReferenceAsync(reference)); + /// Object containing request parameters. + /// Returns the List of Models.CustomerResponse response from the API call. + public List ListCustomers( + Models.ListCustomersInput input) + => CoreHelper.RunTask(ListCustomersAsync(input)); /// - /// Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. + /// This request will by default list all customers associated with your Site. + /// ## Find Customer. + /// Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. + /// Common use cases are:. + /// + Search by an email. + /// + Search by a Chargify ID. + /// + Search by an organization. + /// + Search by a reference value from your application. + /// + Search by a first or last name. + /// To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). /// - /// Required parameter: Customer reference. + /// Object containing request parameters. /// cancellationToken. - /// Returns the Models.CustomerResponse response from the API call. - public async Task ReadCustomerByReferenceAsync( - string reference, + /// Returns the List of Models.CustomerResponse response from the API call. + public async Task> ListCustomersAsync( + Models.ListCustomersInput input, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/customers/lookup.json") + .Setup(HttpMethod.Get, "/customers.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("reference", reference).Required()))) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("start_date", input.StartDate)) + .Query(_query => _query.Setup("end_date", input.EndDate)) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) + .Query(_query => _query.Setup("q", input.Q)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// diff --git a/AdvancedBilling.Standard/Controllers/EventsBasedBillingSegmentsController.cs b/AdvancedBilling.Standard/Controllers/EventsBasedBillingSegmentsController.cs index d401309..7724a52 100644 --- a/AdvancedBilling.Standard/Controllers/EventsBasedBillingSegmentsController.cs +++ b/AdvancedBilling.Standard/Controllers/EventsBasedBillingSegmentsController.cs @@ -34,48 +34,6 @@ public class EventsBasedBillingSegmentsController : BaseController /// internal EventsBasedBillingSegmentsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } - /// - /// This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. - /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - /// - /// Required parameter: ID or Handle for the Component. - /// Required parameter: ID or Handle for the Price Point belonging to the Component. - /// Optional parameter: Example: . - /// Returns the Models.SegmentResponse response from the API call. - public Models.SegmentResponse CreateSegment( - string componentId, - string pricePointId, - Models.CreateSegmentRequest body = null) - => CoreHelper.RunTask(CreateSegmentAsync(componentId, pricePointId, body)); - - /// - /// This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. - /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - /// - /// Required parameter: ID or Handle for the Component. - /// Required parameter: ID or Handle for the Price Point belonging to the Component. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.SegmentResponse response from the API call. - public async Task CreateSegmentAsync( - string componentId, - string pricePointId, - Models.CreateSegmentRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/components/{component_id}/price_points/{price_point_id}/segments.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("component_id", componentId).Required()) - .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new EventBasedBillingSegmentErrorsException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This endpoint allows you to fetch Segments created for a given Price Point. They will be returned in the order of creation. /// You can pass `page` and `per_page` parameters in order to access all of the segments. By default it will return `30` records. You can set `per_page` to `200` at most. @@ -116,6 +74,46 @@ public Models.ListSegmentsResponse ListSegmentsForPricePoint( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new EventBasedBillingListSegmentsErrorsException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// This endpoint allows you to delete a Segment with specified ID. + /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + /// + /// Required parameter: ID or Handle of the Component. + /// Required parameter: ID or Handle of the Price Point belonging to the Component. + /// Required parameter: The ID of the Segment. + public void DeleteSegment( + string componentId, + string pricePointId, + double id) + => CoreHelper.RunVoidTask(DeleteSegmentAsync(componentId, pricePointId, id)); + + /// + /// This endpoint allows you to delete a Segment with specified ID. + /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + /// + /// Required parameter: ID or Handle of the Component. + /// Required parameter: ID or Handle of the Price Point belonging to the Component. + /// Required parameter: The ID of the Segment. + /// cancellationToken. + /// Returns the void response from the API call. + public async Task DeleteSegmentAsync( + string componentId, + string pricePointId, + double id, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/components/{component_id}/price_points/{price_point_id}/segments/{id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("component_id", componentId).Required()) + .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) + .Template(_template => _template.Setup("id", id)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ApiException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// This endpoint updates a single Segment for a Component with a segmented Metric. It allows you to update the pricing for the segment. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. @@ -164,78 +162,80 @@ public Models.SegmentResponse UpdateSegment( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint allows you to delete a Segment with specified ID. + /// This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. + /// If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. /// - /// Required parameter: ID or Handle of the Component. - /// Required parameter: ID or Handle of the Price Point belonging to the Component. - /// Required parameter: The ID of the Segment. - public void DeleteSegment( + /// Required parameter: ID or Handle for the Component. + /// Required parameter: ID or Handle for the Price Point belonging to the Component. + /// Optional parameter: Example: . + /// Returns the Models.ListSegmentsResponse response from the API call. + public Models.ListSegmentsResponse UpdateSegments( string componentId, string pricePointId, - double id) - => CoreHelper.RunVoidTask(DeleteSegmentAsync(componentId, pricePointId, id)); + Models.BulkUpdateSegments body = null) + => CoreHelper.RunTask(UpdateSegmentsAsync(componentId, pricePointId, body)); /// - /// This endpoint allows you to delete a Segment with specified ID. + /// This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. + /// If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. /// - /// Required parameter: ID or Handle of the Component. - /// Required parameter: ID or Handle of the Price Point belonging to the Component. - /// Required parameter: The ID of the Segment. + /// Required parameter: ID or Handle for the Component. + /// Required parameter: ID or Handle for the Price Point belonging to the Component. + /// Optional parameter: Example: . /// cancellationToken. - /// Returns the void response from the API call. - public async Task DeleteSegmentAsync( + /// Returns the Models.ListSegmentsResponse response from the API call. + public async Task UpdateSegmentsAsync( string componentId, string pricePointId, - double id, + Models.BulkUpdateSegments body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/components/{component_id}/price_points/{price_point_id}/segments/{id}.json") + .Setup(HttpMethod.Put, "/components/{component_id}/price_points/{price_point_id}/segments/bulk.json") .WithAuth("global") .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("component_id", componentId).Required()) .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) - .Template(_template => _template.Setup("id", id)))) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ApiException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new EventBasedBillingSegmentException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. - /// If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. + /// This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. /// /// Required parameter: ID or Handle for the Component. /// Required parameter: ID or Handle for the Price Point belonging to the Component. /// Optional parameter: Example: . - /// Returns the Models.ListSegmentsResponse response from the API call. - public Models.ListSegmentsResponse CreateSegments( + /// Returns the Models.SegmentResponse response from the API call. + public Models.SegmentResponse CreateSegment( string componentId, string pricePointId, - Models.BulkCreateSegments body = null) - => CoreHelper.RunTask(CreateSegmentsAsync(componentId, pricePointId, body)); + Models.CreateSegmentRequest body = null) + => CoreHelper.RunTask(CreateSegmentAsync(componentId, pricePointId, body)); /// - /// This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. - /// If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. + /// This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. /// /// Required parameter: ID or Handle for the Component. /// Required parameter: ID or Handle for the Price Point belonging to the Component. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.ListSegmentsResponse response from the API call. - public async Task CreateSegmentsAsync( + /// Returns the Models.SegmentResponse response from the API call. + public async Task CreateSegmentAsync( string componentId, string pricePointId, - Models.BulkCreateSegments body = null, + Models.CreateSegmentRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/components/{component_id}/price_points/{price_point_id}/segments/bulk.json") + .Setup(HttpMethod.Post, "/components/{component_id}/price_points/{price_point_id}/segments.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) @@ -244,27 +244,27 @@ public Models.ListSegmentsResponse CreateSegments( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new EventBasedBillingSegmentException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new EventBasedBillingSegmentErrorsException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. - /// If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. + /// This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. + /// If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. /// /// Required parameter: ID or Handle for the Component. /// Required parameter: ID or Handle for the Price Point belonging to the Component. /// Optional parameter: Example: . /// Returns the Models.ListSegmentsResponse response from the API call. - public Models.ListSegmentsResponse UpdateSegments( + public Models.ListSegmentsResponse CreateSegments( string componentId, string pricePointId, - Models.BulkUpdateSegments body = null) - => CoreHelper.RunTask(UpdateSegmentsAsync(componentId, pricePointId, body)); + Models.BulkCreateSegments body = null) + => CoreHelper.RunTask(CreateSegmentsAsync(componentId, pricePointId, body)); /// - /// This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. - /// If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. + /// This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. + /// If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. /// You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. /// /// Required parameter: ID or Handle for the Component. @@ -272,14 +272,14 @@ public Models.ListSegmentsResponse UpdateSegments( /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ListSegmentsResponse response from the API call. - public async Task UpdateSegmentsAsync( + public async Task CreateSegmentsAsync( string componentId, string pricePointId, - Models.BulkUpdateSegments body = null, + Models.BulkCreateSegments body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/components/{component_id}/price_points/{price_point_id}/segments/bulk.json") + .Setup(HttpMethod.Post, "/components/{component_id}/price_points/{price_point_id}/segments/bulk.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) diff --git a/AdvancedBilling.Standard/Controllers/InsightsController.cs b/AdvancedBilling.Standard/Controllers/InsightsController.cs index f42bd5f..5c01af3 100644 --- a/AdvancedBilling.Standard/Controllers/InsightsController.cs +++ b/AdvancedBilling.Standard/Controllers/InsightsController.cs @@ -63,6 +63,40 @@ public Models.SiteSummary ReadSiteStats() .WithAuth("global")) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. + /// + /// Object containing request parameters. + /// Returns the Models.SubscriptionMRRResponse response from the API call. + [Obsolete] + public Models.SubscriptionMRRResponse ListMrrPerSubscription( + Models.ListMrrPerSubscriptionInput input) + => CoreHelper.RunTask(ListMrrPerSubscriptionAsync(input)); + + /// + /// This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.SubscriptionMRRResponse response from the API call. + [Obsolete] + public async Task ListMrrPerSubscriptionAsync( + Models.ListMrrPerSubscriptionInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions_mrr.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("filter[subscription_ids]", input.FilterSubscriptionIds)) + .Query(_query => _query.Setup("at_time", input.AtTime)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionsMrrErrorResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// This endpoint returns your site's current MRR, including plan and usage breakouts. /// @@ -152,39 +186,5 @@ public Models.ListMRRResponse ReadMrrMovements( .Query(_query => _query.Setup("per_page", input.PerPage)) .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. - /// - /// Object containing request parameters. - /// Returns the Models.SubscriptionMRRResponse response from the API call. - [Obsolete] - public Models.SubscriptionMRRResponse ListMrrPerSubscription( - Models.ListMrrPerSubscriptionInput input) - => CoreHelper.RunTask(ListMrrPerSubscriptionAsync(input)); - - /// - /// This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.SubscriptionMRRResponse response from the API call. - [Obsolete] - public async Task ListMrrPerSubscriptionAsync( - Models.ListMrrPerSubscriptionInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions_mrr.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("filter[subscription_ids]", input.FilterSubscriptionIds)) - .Query(_query => _query.Setup("at_time", input.AtTime)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionsMrrErrorResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/InvoicesController.cs b/AdvancedBilling.Standard/Controllers/InvoicesController.cs index d189076..898ab20 100644 --- a/AdvancedBilling.Standard/Controllers/InvoicesController.cs +++ b/AdvancedBilling.Standard/Controllers/InvoicesController.cs @@ -70,147 +70,43 @@ public Models.Invoice RefundInvoice( .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("uid", uid).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. + /// Credit Notes are like inverse invoices. They reduce the amount a customer owes. + /// By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. /// /// Object containing request parameters. - /// Returns the Models.ListInvoicesResponse response from the API call. - public Models.ListInvoicesResponse ListInvoices( - Models.ListInvoicesInput input) - => CoreHelper.RunTask(ListInvoicesAsync(input)); + /// Returns the Models.ListCreditNotesResponse response from the API call. + public Models.ListCreditNotesResponse ListCreditNotes( + Models.ListCreditNotesInput input) + => CoreHelper.RunTask(ListCreditNotesAsync(input)); /// - /// By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. + /// Credit Notes are like inverse invoices. They reduce the amount a customer owes. + /// By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. /// /// Object containing request parameters. /// cancellationToken. - /// Returns the Models.ListInvoicesResponse response from the API call. - public async Task ListInvoicesAsync( - Models.ListInvoicesInput input, + /// Returns the Models.ListCreditNotesResponse response from the API call. + public async Task ListCreditNotesAsync( + Models.ListCreditNotesInput input, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/invoices.json") + .Setup(HttpMethod.Get, "/credit_notes.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("start_date", input.StartDate)) - .Query(_query => _query.Setup("end_date", input.EndDate)) - .Query(_query => _query.Setup("status", (input.Status.HasValue) ? ApiHelper.JsonSerialize(input.Status.Value).Trim('\"') : null)) .Query(_query => _query.Setup("subscription_id", input.SubscriptionId)) - .Query(_query => _query.Setup("subscription_group_uid", input.SubscriptionGroupUid)) .Query(_query => _query.Setup("page", input.Page)) .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : "desc")) .Query(_query => _query.Setup("line_items", input.LineItems)) .Query(_query => _query.Setup("discounts", input.Discounts)) .Query(_query => _query.Setup("taxes", input.Taxes)) - .Query(_query => _query.Setup("credits", input.Credits)) - .Query(_query => _query.Setup("payments", input.Payments)) - .Query(_query => _query.Setup("custom_fields", input.CustomFields)) .Query(_query => _query.Setup("refunds", input.Refunds)) - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : "due_date")) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) - .Query(_query => _query.Setup("customer_ids", input.CustomerIds)) - .Query(_query => _query.Setup("number", input.Number)) - .Query(_query => _query.Setup("product_ids", input.ProductIds)) - .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : "number")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to retrieve the details for an invoice. - /// - /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. - /// Returns the Models.Invoice response from the API call. - public Models.Invoice ReadInvoice( - string uid) - => CoreHelper.RunTask(ReadInvoiceAsync(uid)); - - /// - /// Use this endpoint to retrieve the details for an invoice. - /// - /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. - /// cancellationToken. - /// Returns the Models.Invoice response from the API call. - public async Task ReadInvoiceAsync( - string uid, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/invoices/{uid}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("uid", uid).Required()))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. - /// Exposed event types are:. - /// + issue_invoice. - /// + apply_credit_note. - /// + apply_payment. - /// + refund_invoice. - /// + void_invoice. - /// + void_remainder. - /// + backport_invoice. - /// + change_invoice_status. - /// + change_invoice_collection_method. - /// + remove_payment. - /// + failed_payment. - /// + apply_debit_note. - /// + create_debit_note. - /// + change_chargeback_status. - /// Invoice events are returned in ascending order. - /// If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. - /// Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. - /// - /// Object containing request parameters. - /// Returns the Models.ListInvoiceEventsResponse response from the API call. - public Models.ListInvoiceEventsResponse ListInvoiceEvents( - Models.ListInvoiceEventsInput input) - => CoreHelper.RunTask(ListInvoiceEventsAsync(input)); - - /// - /// This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. - /// Exposed event types are:. - /// + issue_invoice. - /// + apply_credit_note. - /// + apply_payment. - /// + refund_invoice. - /// + void_invoice. - /// + void_remainder. - /// + backport_invoice. - /// + change_invoice_status. - /// + change_invoice_collection_method. - /// + remove_payment. - /// + failed_payment. - /// + apply_debit_note. - /// + create_debit_note. - /// + change_chargeback_status. - /// Invoice events are returned in ascending order. - /// If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. - /// Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.ListInvoiceEventsResponse response from the API call. - public async Task ListInvoiceEventsAsync( - Models.ListInvoiceEventsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/invoices/events.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("since_date", input.SinceDate)) - .Query(_query => _query.Setup("since_id", input.SinceId)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("invoice_uid", input.InvoiceUid)) - .Query(_query => _query.Setup("with_change_invoice_status", input.WithChangeInvoiceStatus)) - .Query(_query => _query.Setup("event_types", input.EventTypes?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) + .Query(_query => _query.Setup("applications", input.Applications)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -385,145 +281,144 @@ public Models.MultiInvoicePaymentResponse RecordExternalPaymentForInvoices( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Credit Notes are like inverse invoices. They reduce the amount a customer owes. - /// By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. + /// By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. /// /// Object containing request parameters. - /// Returns the Models.ListCreditNotesResponse response from the API call. - public Models.ListCreditNotesResponse ListCreditNotes( - Models.ListCreditNotesInput input) - => CoreHelper.RunTask(ListCreditNotesAsync(input)); + /// Returns the Models.ListInvoicesResponse response from the API call. + public Models.ListInvoicesResponse ListInvoices( + Models.ListInvoicesInput input) + => CoreHelper.RunTask(ListInvoicesAsync(input)); /// - /// Credit Notes are like inverse invoices. They reduce the amount a customer owes. - /// By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. + /// By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. /// /// Object containing request parameters. /// cancellationToken. - /// Returns the Models.ListCreditNotesResponse response from the API call. - public async Task ListCreditNotesAsync( - Models.ListCreditNotesInput input, + /// Returns the Models.ListInvoicesResponse response from the API call. + public async Task ListInvoicesAsync( + Models.ListInvoicesInput input, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/credit_notes.json") + .Setup(HttpMethod.Get, "/invoices.json") .WithAuth("global") .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("start_date", input.StartDate)) + .Query(_query => _query.Setup("end_date", input.EndDate)) + .Query(_query => _query.Setup("status", (input.Status.HasValue) ? ApiHelper.JsonSerialize(input.Status.Value).Trim('\"') : null)) .Query(_query => _query.Setup("subscription_id", input.SubscriptionId)) + .Query(_query => _query.Setup("subscription_group_uid", input.SubscriptionGroupUid)) .Query(_query => _query.Setup("page", input.Page)) .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : "desc")) .Query(_query => _query.Setup("line_items", input.LineItems)) .Query(_query => _query.Setup("discounts", input.Discounts)) .Query(_query => _query.Setup("taxes", input.Taxes)) + .Query(_query => _query.Setup("credits", input.Credits)) + .Query(_query => _query.Setup("payments", input.Payments)) + .Query(_query => _query.Setup("custom_fields", input.CustomFields)) .Query(_query => _query.Setup("refunds", input.Refunds)) - .Query(_query => _query.Setup("applications", input.Applications)))) + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : "due_date")) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) + .Query(_query => _query.Setup("customer_ids", input.CustomerIds)) + .Query(_query => _query.Setup("number", input.Number)) + .Query(_query => _query.Setup("product_ids", input.ProductIds)) + .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : "number")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to retrieve the details for a credit note. + /// Use this endpoint to retrieve the details for an invoice. /// - /// Required parameter: The unique identifier of the credit note. - /// Returns the Models.CreditNote response from the API call. - public Models.CreditNote ReadCreditNote( + /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. + /// Returns the Models.Invoice response from the API call. + public Models.Invoice ReadInvoice( string uid) - => CoreHelper.RunTask(ReadCreditNoteAsync(uid)); + => CoreHelper.RunTask(ReadInvoiceAsync(uid)); /// - /// Use this endpoint to retrieve the details for a credit note. + /// Use this endpoint to retrieve the details for an invoice. /// - /// Required parameter: The unique identifier of the credit note. + /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. /// cancellationToken. - /// Returns the Models.CreditNote response from the API call. - public async Task ReadCreditNoteAsync( + /// Returns the Models.Invoice response from the API call. + public async Task ReadInvoiceAsync( string uid, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/credit_notes/{uid}.json") + .Setup(HttpMethod.Get, "/invoices/{uid}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("uid", uid).Required()))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Record an external payment made against a subscription that will pay partially or in full one or more invoices. - /// Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. - /// Excess payment will result in the creation of a prepayment on the Invoice Account. - /// Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// Returns the Models.PaymentResponse response from the API call. - public Models.PaymentResponse RecordPaymentForSubscription( - int subscriptionId, - Models.RecordPaymentRequest body = null) - => CoreHelper.RunTask(RecordPaymentForSubscriptionAsync(subscriptionId, body)); - - /// - /// Record an external payment made against a subscription that will pay partially or in full one or more invoices. - /// Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. - /// Excess payment will result in the creation of a prepayment on the Invoice Account. - /// Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.PaymentResponse response from the API call. - public async Task RecordPaymentForSubscriptionAsync( - int subscriptionId, - Models.RecordPaymentRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/payments.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). - /// Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways:. - /// - Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.). - /// - Recording a payment directly against the invoice. - /// A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. - /// ### Reopening Consolidated Invoices. - /// When reopening a consolidated invoice, all of its canceled segments will also be reopened. + /// This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. + /// Exposed event types are:. + /// + issue_invoice. + /// + apply_credit_note. + /// + apply_payment. + /// + refund_invoice. + /// + void_invoice. + /// + void_remainder. + /// + backport_invoice. + /// + change_invoice_status. + /// + change_invoice_collection_method. + /// + remove_payment. + /// + failed_payment. + /// + apply_debit_note. + /// + create_debit_note. + /// + change_chargeback_status. + /// Invoice events are returned in ascending order. + /// If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. + /// Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. /// - /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. - /// Returns the Models.Invoice response from the API call. - public Models.Invoice ReopenInvoice( - string uid) - => CoreHelper.RunTask(ReopenInvoiceAsync(uid)); + /// Object containing request parameters. + /// Returns the Models.ListInvoiceEventsResponse response from the API call. + public Models.ListInvoiceEventsResponse ListInvoiceEvents( + Models.ListInvoiceEventsInput input) + => CoreHelper.RunTask(ListInvoiceEventsAsync(input)); /// - /// This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). - /// Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways:. - /// - Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.). - /// - Recording a payment directly against the invoice. - /// A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. - /// ### Reopening Consolidated Invoices. - /// When reopening a consolidated invoice, all of its canceled segments will also be reopened. + /// This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. + /// Exposed event types are:. + /// + issue_invoice. + /// + apply_credit_note. + /// + apply_payment. + /// + refund_invoice. + /// + void_invoice. + /// + void_remainder. + /// + backport_invoice. + /// + change_invoice_status. + /// + change_invoice_collection_method. + /// + remove_payment. + /// + failed_payment. + /// + apply_debit_note. + /// + create_debit_note. + /// + change_chargeback_status. + /// Invoice events are returned in ascending order. + /// If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. + /// Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. /// - /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. + /// Object containing request parameters. /// cancellationToken. - /// Returns the Models.Invoice response from the API call. - public async Task ReopenInvoiceAsync( - string uid, + /// Returns the Models.ListInvoiceEventsResponse response from the API call. + public async Task ListInvoiceEventsAsync( + Models.ListInvoiceEventsInput input, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/invoices/{uid}/reopen.json") + .Setup(HttpMethod.Get, "/invoices/events.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("uid", uid).Required()))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .Query(_query => _query.Setup("since_date", input.SinceDate)) + .Query(_query => _query.Setup("since_id", input.SinceId)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("invoice_uid", input.InvoiceUid)) + .Query(_query => _query.Setup("with_change_invoice_status", input.WithChangeInvoiceStatus)) + .Query(_query => _query.Setup("event_types", input.EventTypes?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -561,6 +456,37 @@ public Models.Invoice VoidInvoice( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. + /// The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. + /// + /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. + /// Returns the Models.CustomerChangesPreviewResponse response from the API call. + public Models.CustomerChangesPreviewResponse PreviewCustomerInformationChanges( + string uid) + => CoreHelper.RunTask(PreviewCustomerInformationChangesAsync(uid)); + + /// + /// Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. + /// The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. + /// + /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. + /// cancellationToken. + /// Returns the Models.CustomerChangesPreviewResponse response from the API call. + public async Task PreviewCustomerInformationChangesAsync( + string uid, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/invoices/{uid}/customer_information/preview.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("uid", uid).Required()))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ErrorListResponseException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// Invoice segments returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. /// @@ -841,74 +767,160 @@ public Models.InvoiceResponse CreateInvoice( .Template(_template => _template.Setup("subscription_id", subscriptionId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new NestedErrorResponseException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. - /// Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. - /// On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. + /// This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. + /// You cannot issue a pending child invoice that was created for a member subscription in a group. + /// For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. + /// For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value:. + /// - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. + /// - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. + /// - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). /// /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. /// Optional parameter: Example: . - public void SendInvoice( + /// Returns the Models.Invoice response from the API call. + public Models.Invoice IssueInvoice( string uid, - Models.SendInvoiceRequest body = null) - => CoreHelper.RunVoidTask(SendInvoiceAsync(uid, body)); + Models.IssueInvoiceRequest body = null) + => CoreHelper.RunTask(IssueInvoiceAsync(uid, body)); /// - /// This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. - /// Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. - /// On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. + /// This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. + /// You cannot issue a pending child invoice that was created for a member subscription in a group. + /// For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. + /// For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value:. + /// - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. + /// - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. + /// - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). /// /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the void response from the API call. - public async Task SendInvoiceAsync( + /// Returns the Models.Invoice response from the API call. + public async Task IssueInvoiceAsync( string uid, - Models.SendInvoiceRequest body = null, + Models.IssueInvoiceRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/invoices/{uid}/deliveries.json") + .Setup(HttpMethod.Post, "/invoices/{uid}/issue.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("uid", uid).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. - /// The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. + /// Use this endpoint to retrieve the details for a credit note. + /// + /// Required parameter: The unique identifier of the credit note. + /// Returns the Models.CreditNote response from the API call. + public Models.CreditNote ReadCreditNote( + string uid) + => CoreHelper.RunTask(ReadCreditNoteAsync(uid)); + + /// + /// Use this endpoint to retrieve the details for a credit note. + /// + /// Required parameter: The unique identifier of the credit note. + /// cancellationToken. + /// Returns the Models.CreditNote response from the API call. + public async Task ReadCreditNoteAsync( + string uid, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/credit_notes/{uid}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("uid", uid).Required()))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Record an external payment made against a subscription that will pay partially or in full one or more invoices. + /// Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. + /// Excess payment will result in the creation of a prepayment on the Invoice Account. + /// Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// Returns the Models.PaymentResponse response from the API call. + public Models.PaymentResponse RecordPaymentForSubscription( + int subscriptionId, + Models.RecordPaymentRequest body = null) + => CoreHelper.RunTask(RecordPaymentForSubscriptionAsync(subscriptionId, body)); + + /// + /// Record an external payment made against a subscription that will pay partially or in full one or more invoices. + /// Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. + /// Excess payment will result in the creation of a prepayment on the Invoice Account. + /// Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.PaymentResponse response from the API call. + public async Task RecordPaymentForSubscriptionAsync( + int subscriptionId, + Models.RecordPaymentRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/payments.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). + /// Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways:. + /// - Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.). + /// - Recording a payment directly against the invoice. + /// A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. + /// ### Reopening Consolidated Invoices. + /// When reopening a consolidated invoice, all of its canceled segments will also be reopened. /// /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. - /// Returns the Models.CustomerChangesPreviewResponse response from the API call. - public Models.CustomerChangesPreviewResponse PreviewCustomerInformationChanges( + /// Returns the Models.Invoice response from the API call. + public Models.Invoice ReopenInvoice( string uid) - => CoreHelper.RunTask(PreviewCustomerInformationChangesAsync(uid)); + => CoreHelper.RunTask(ReopenInvoiceAsync(uid)); /// - /// Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. - /// The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. + /// This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). + /// Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways:. + /// - Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.). + /// - Recording a payment directly against the invoice. + /// A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. + /// ### Reopening Consolidated Invoices. + /// When reopening a consolidated invoice, all of its canceled segments will also be reopened. /// /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. /// cancellationToken. - /// Returns the Models.CustomerChangesPreviewResponse response from the API call. - public async Task PreviewCustomerInformationChangesAsync( + /// Returns the Models.Invoice response from the API call. + public async Task ReopenInvoiceAsync( string uid, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/invoices/{uid}/customer_information/preview.json") + .Setup(HttpMethod.Post, "/invoices/{uid}/reopen.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("uid", uid).Required()))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ErrorListResponseException(_reason, _context), true)) + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); @@ -944,49 +956,39 @@ public Models.Invoice UpdateCustomerInformation( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. - /// You cannot issue a pending child invoice that was created for a member subscription in a group. - /// For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. - /// For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value:. - /// - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. - /// - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. - /// - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). + /// This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. + /// Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. + /// On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. /// /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. /// Optional parameter: Example: . - /// Returns the Models.Invoice response from the API call. - public Models.Invoice IssueInvoice( + public void SendInvoice( string uid, - Models.IssueInvoiceRequest body = null) - => CoreHelper.RunTask(IssueInvoiceAsync(uid, body)); + Models.SendInvoiceRequest body = null) + => CoreHelper.RunVoidTask(SendInvoiceAsync(uid, body)); /// - /// This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. - /// You cannot issue a pending child invoice that was created for a member subscription in a group. - /// For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. - /// For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value:. - /// - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. - /// - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. - /// - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). + /// This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. + /// Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. + /// On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. /// /// Required parameter: The unique identifier for the invoice, this does not refer to the public facing invoice number.. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.Invoice response from the API call. - public async Task IssueInvoiceAsync( + /// Returns the void response from the API call. + public async Task SendInvoiceAsync( string uid, - Models.IssueInvoiceRequest body = null, + Models.SendInvoiceRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/invoices/{uid}/issue.json") + .Setup(HttpMethod.Post, "/invoices/{uid}/deliveries.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("uid", uid).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } diff --git a/AdvancedBilling.Standard/Controllers/OffersController.cs b/AdvancedBilling.Standard/Controllers/OffersController.cs index f5107fa..0cf7015 100644 --- a/AdvancedBilling.Standard/Controllers/OffersController.cs +++ b/AdvancedBilling.Standard/Controllers/OffersController.cs @@ -35,95 +35,51 @@ public class OffersController : BaseController internal OffersController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// Create an offer within your Chargify site by sending a POST request. - /// ## Documentation. - /// Offers allow you to package complicated combinations of products, components and coupons into a convenient package which can then be subscribed to just like products. - /// Once an offer is defined it can be used as an alternative to the product when creating subscriptions. - /// Full documentation on how to use offers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407753852059). - /// ## Using a Product Price Point. - /// You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. + /// This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. /// - /// Optional parameter: Example: . + /// Required parameter: The Chargify id of the offer. /// Returns the Models.OfferResponse response from the API call. - public Models.OfferResponse CreateOffer( - Models.CreateOfferRequest body = null) - => CoreHelper.RunTask(CreateOfferAsync(body)); + public Models.OfferResponse ReadOffers( + int offerId) + => CoreHelper.RunTask(ReadOffersAsync(offerId)); /// - /// Create an offer within your Chargify site by sending a POST request. - /// ## Documentation. - /// Offers allow you to package complicated combinations of products, components and coupons into a convenient package which can then be subscribed to just like products. - /// Once an offer is defined it can be used as an alternative to the product when creating subscriptions. - /// Full documentation on how to use offers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407753852059). - /// ## Using a Product Price Point. - /// You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. + /// This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. /// - /// Optional parameter: Example: . + /// Required parameter: The Chargify id of the offer. /// cancellationToken. /// Returns the Models.OfferResponse response from the API call. - public async Task CreateOfferAsync( - Models.CreateOfferRequest body = null, + public async Task ReadOffersAsync( + int offerId, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/offers.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorMapResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This endpoint will list offers for a site. - /// - /// Object containing request parameters. - /// Returns the Models.ListOffersResponse response from the API call. - public Models.ListOffersResponse ListOffers( - Models.ListOffersInput input) - => CoreHelper.RunTask(ListOffersAsync(input)); - - /// - /// This endpoint will list offers for a site. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.ListOffersResponse response from the API call. - public async Task ListOffersAsync( - Models.ListOffersInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/offers.json") + .Setup(HttpMethod.Get, "/offers/{offer_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("include_archived", input.IncludeArchived)))) + .Template(_template => _template.Setup("offer_id", offerId)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. + /// Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. /// /// Required parameter: The Chargify id of the offer. - /// Returns the Models.OfferResponse response from the API call. - public Models.OfferResponse ReadOffers( + public void UnarchiveOffer( int offerId) - => CoreHelper.RunTask(ReadOffersAsync(offerId)); + => CoreHelper.RunVoidTask(UnarchiveOfferAsync(offerId)); /// - /// This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. + /// Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. /// /// Required parameter: The Chargify id of the offer. /// cancellationToken. - /// Returns the Models.OfferResponse response from the API call. - public async Task ReadOffersAsync( + /// Returns the void response from the API call. + public async Task UnarchiveOfferAsync( int offerId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/offers/{offer_id}.json") + .Setup(HttpMethod.Put, "/offers/{offer_id}/unarchive.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("offer_id", offerId)))) @@ -155,28 +111,72 @@ public async Task ArchiveOfferAsync( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. + /// Create an offer within your Chargify site by sending a POST request. + /// ## Documentation. + /// Offers allow you to package complicated combinations of products, components and coupons into a convenient package which can then be subscribed to just like products. + /// Once an offer is defined it can be used as an alternative to the product when creating subscriptions. + /// Full documentation on how to use offers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407753852059). + /// ## Using a Product Price Point. + /// You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. /// - /// Required parameter: The Chargify id of the offer. - public void UnarchiveOffer( - int offerId) - => CoreHelper.RunVoidTask(UnarchiveOfferAsync(offerId)); + /// Optional parameter: Example: . + /// Returns the Models.OfferResponse response from the API call. + public Models.OfferResponse CreateOffer( + Models.CreateOfferRequest body = null) + => CoreHelper.RunTask(CreateOfferAsync(body)); /// - /// Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. + /// Create an offer within your Chargify site by sending a POST request. + /// ## Documentation. + /// Offers allow you to package complicated combinations of products, components and coupons into a convenient package which can then be subscribed to just like products. + /// Once an offer is defined it can be used as an alternative to the product when creating subscriptions. + /// Full documentation on how to use offers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407753852059). + /// ## Using a Product Price Point. + /// You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. /// - /// Required parameter: The Chargify id of the offer. + /// Optional parameter: Example: . /// cancellationToken. - /// Returns the void response from the API call. - public async Task UnarchiveOfferAsync( - int offerId, + /// Returns the Models.OfferResponse response from the API call. + public async Task CreateOfferAsync( + Models.CreateOfferRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/offers/{offer_id}/unarchive.json") + .Setup(HttpMethod.Post, "/offers.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("offer_id", offerId)))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This endpoint will list offers for a site. + /// + /// Object containing request parameters. + /// Returns the Models.ListOffersResponse response from the API call. + public Models.ListOffersResponse ListOffers( + Models.ListOffersInput input) + => CoreHelper.RunTask(ListOffersAsync(input)); + + /// + /// This endpoint will list offers for a site. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.ListOffersResponse response from the API call. + public async Task ListOffersAsync( + Models.ListOffersInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/offers.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("include_archived", input.IncludeArchived)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/PaymentProfilesController.cs b/AdvancedBilling.Standard/Controllers/PaymentProfilesController.cs index 0dba836..b6cf63b 100644 --- a/AdvancedBilling.Standard/Controllers/PaymentProfilesController.cs +++ b/AdvancedBilling.Standard/Controllers/PaymentProfilesController.cs @@ -34,6 +34,153 @@ public class PaymentProfilesController : BaseController /// internal PaymentProfilesController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } + /// + /// ## Partial Card Updates. + /// In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. + /// In this case, the following JSON is acceptable:. + /// ```. + /// {. + /// "payment_profile": {. + /// "first_name": "Kelly",. + /// "last_name": "Test",. + /// "billing_address": "789 Juniper Court",. + /// "billing_city": "Boulder",. + /// "billing_state": "CO",. + /// "billing_zip": "80302",. + /// "billing_country": "US",. + /// "billing_address_2": null. + /// }. + /// }. + /// ```. + /// The result will be that you have updated the billing information for the card, yet retained the original card number data. + /// ## Specific notes on updating payment profiles. + /// - Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. + /// - If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. + /// - A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. + /// - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. + /// - If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + /// + /// Required parameter: The Chargify id of the payment profile. + /// Optional parameter: Example: . + /// Returns the Models.PaymentProfileResponse response from the API call. + public Models.PaymentProfileResponse UpdatePaymentProfile( + int paymentProfileId, + Models.UpdatePaymentProfileRequest body = null) + => CoreHelper.RunTask(UpdatePaymentProfileAsync(paymentProfileId, body)); + + /// + /// ## Partial Card Updates. + /// In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. + /// In this case, the following JSON is acceptable:. + /// ```. + /// {. + /// "payment_profile": {. + /// "first_name": "Kelly",. + /// "last_name": "Test",. + /// "billing_address": "789 Juniper Court",. + /// "billing_city": "Boulder",. + /// "billing_state": "CO",. + /// "billing_zip": "80302",. + /// "billing_country": "US",. + /// "billing_address_2": null. + /// }. + /// }. + /// ```. + /// The result will be that you have updated the billing information for the card, yet retained the original card number data. + /// ## Specific notes on updating payment profiles. + /// - Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. + /// - If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. + /// - A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. + /// - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. + /// - If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + /// + /// Required parameter: The Chargify id of the payment profile. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.PaymentProfileResponse response from the API call. + public async Task UpdatePaymentProfileAsync( + int paymentProfileId, + Models.UpdatePaymentProfileRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/payment_profiles/{payment_profile_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new ApiException(_reason, _context))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorStringMapResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This will delete a Payment Profile belonging to a Subscription Group. + /// **Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. + /// + /// Required parameter: The uid of the subscription group. + /// Required parameter: The Chargify id of the payment profile. + public void DeleteSubscriptionGroupPaymentProfile( + string uid, + int paymentProfileId) + => CoreHelper.RunVoidTask(DeleteSubscriptionGroupPaymentProfileAsync(uid, paymentProfileId)); + + /// + /// This will delete a Payment Profile belonging to a Subscription Group. + /// **Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. + /// + /// Required parameter: The uid of the subscription group. + /// Required parameter: The Chargify id of the payment profile. + /// cancellationToken. + /// Returns the void response from the API call. + public async Task DeleteSubscriptionGroupPaymentProfileAsync( + string uid, + int paymentProfileId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/subscription_groups/{uid}/payment_profiles/{payment_profile_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("uid", uid).Required()) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// You can send a "request payment update" email to the customer associated with the subscription. + /// If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. + /// Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. + /// These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. + /// + /// Required parameter: The Chargify id of the subscription. + public void SendRequestUpdatePaymentEmail( + int subscriptionId) + => CoreHelper.RunVoidTask(SendRequestUpdatePaymentEmailAsync(subscriptionId)); + + /// + /// You can send a "request payment update" email to the customer associated with the subscription. + /// If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. + /// Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. + /// These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. + /// + /// Required parameter: The Chargify id of the subscription. + /// cancellationToken. + /// Returns the void response from the API call. + public async Task SendRequestUpdatePaymentEmailAsync( + int subscriptionId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/request_payment_profiles_update.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// Use this endpoint to create a payment profile for a customer. /// Payment Profiles house the credit card, ACH (Authorize.Net or Stripe only,) or PayPal (Braintree only,) data for a customer. The payment information is attached to the customer within Chargify, as opposed to the Subscription itself. @@ -221,8 +368,8 @@ internal PaymentProfilesController(GlobalConfiguration globalConfiguration) : ba /// 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not. /// /// Optional parameter: When following the IBAN or the Local Bank details examples, a customer, bank account and mandate will be created in your current vault. If the customer, bank account, and mandate already exist in your vault, follow the Import example to link the payment profile into Chargify.. - /// Returns the Models.CreatePaymentProfileResponse response from the API call. - public Models.CreatePaymentProfileResponse CreatePaymentProfile( + /// Returns the Models.PaymentProfileResponse response from the API call. + public Models.PaymentProfileResponse CreatePaymentProfile( Models.CreatePaymentProfileRequest body = null) => CoreHelper.RunTask(CreatePaymentProfileAsync(body)); @@ -414,11 +561,11 @@ public Models.CreatePaymentProfileResponse CreatePaymentProfile( /// /// Optional parameter: When following the IBAN or the Local Bank details examples, a customer, bank account and mandate will be created in your current vault. If the customer, bank account, and mandate already exist in your vault, follow the Import example to link the payment profile into Chargify.. /// cancellationToken. - /// Returns the Models.CreatePaymentProfileResponse response from the API call. - public async Task CreatePaymentProfileAsync( + /// Returns the Models.PaymentProfileResponse response from the API call. + public async Task CreatePaymentProfileAsync( Models.CreatePaymentProfileRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Post, "/payment_profiles.json") .WithAuth("global") @@ -434,8 +581,8 @@ public Models.CreatePaymentProfileResponse CreatePaymentProfile( /// This method will return all of the active `payment_profiles` for a Site, or for one Customer within a site. If no payment profiles are found, this endpoint will return an empty array, not a 404. /// /// Object containing request parameters. - /// Returns the List of Models.ListPaymentProfilesResponse response from the API call. - public List ListPaymentProfiles( + /// Returns the List of Models.PaymentProfileResponse response from the API call. + public List ListPaymentProfiles( Models.ListPaymentProfilesInput input) => CoreHelper.RunTask(ListPaymentProfilesAsync(input)); @@ -444,11 +591,11 @@ public Models.CreatePaymentProfileResponse CreatePaymentProfile( /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.ListPaymentProfilesResponse response from the API call. - public async Task> ListPaymentProfilesAsync( + /// Returns the List of Models.PaymentProfileResponse response from the API call. + public async Task> ListPaymentProfilesAsync( Models.ListPaymentProfilesInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Get, "/payment_profiles.json") .WithAuth("global") @@ -492,9 +639,9 @@ public Models.CreatePaymentProfileResponse CreatePaymentProfile( /// ```. /// /// Required parameter: The Chargify id of the payment profile. - /// Returns the Models.ReadPaymentProfileResponse response from the API call. - public Models.ReadPaymentProfileResponse ReadPaymentProfile( - string paymentProfileId) + /// Returns the Models.PaymentProfileResponse response from the API call. + public Models.PaymentProfileResponse ReadPaymentProfile( + int paymentProfileId) => CoreHelper.RunTask(ReadPaymentProfileAsync(paymentProfileId)); /// @@ -532,157 +679,118 @@ public Models.ReadPaymentProfileResponse ReadPaymentProfile( /// /// Required parameter: The Chargify id of the payment profile. /// cancellationToken. - /// Returns the Models.ReadPaymentProfileResponse response from the API call. - public async Task ReadPaymentProfileAsync( - string paymentProfileId, + /// Returns the Models.PaymentProfileResponse response from the API call. + public async Task ReadPaymentProfileAsync( + int paymentProfileId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Get, "/payment_profiles/{payment_profile_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId).Required()))) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new ApiException(_reason, _context)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// ## Partial Card Updates. - /// In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. - /// In this case, the following JSON is acceptable:. - /// ```. - /// {. - /// "payment_profile": {. - /// "first_name": "Kelly",. - /// "last_name": "Test",. - /// "billing_address": "789 Juniper Court",. - /// "billing_city": "Boulder",. - /// "billing_state": "CO",. - /// "billing_zip": "80302",. - /// "billing_country": "US",. - /// "billing_address_2": null. - /// }. - /// }. - /// ```. - /// The result will be that you have updated the billing information for the card, yet retained the original card number data. - /// ## Specific notes on updating payment profiles. - /// - Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. - /// - If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. - /// - A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. - /// - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. - /// - If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + /// This will delete a payment profile belonging to the customer on the subscription. + /// + If the customer has multiple subscriptions, the payment profile will be removed from all of them. + /// + If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). /// + /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the payment profile. - /// Optional parameter: Example: . - /// Returns the Models.UpdatePaymentProfileResponse response from the API call. - public Models.UpdatePaymentProfileResponse UpdatePaymentProfile( - string paymentProfileId, - Models.UpdatePaymentProfileRequest body = null) - => CoreHelper.RunTask(UpdatePaymentProfileAsync(paymentProfileId, body)); + public void DeleteSubscriptionsPaymentProfile( + int subscriptionId, + int paymentProfileId) + => CoreHelper.RunVoidTask(DeleteSubscriptionsPaymentProfileAsync(subscriptionId, paymentProfileId)); /// - /// ## Partial Card Updates. - /// In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. - /// In this case, the following JSON is acceptable:. - /// ```. - /// {. - /// "payment_profile": {. - /// "first_name": "Kelly",. - /// "last_name": "Test",. - /// "billing_address": "789 Juniper Court",. - /// "billing_city": "Boulder",. - /// "billing_state": "CO",. - /// "billing_zip": "80302",. - /// "billing_country": "US",. - /// "billing_address_2": null. - /// }. - /// }. - /// ```. - /// The result will be that you have updated the billing information for the card, yet retained the original card number data. - /// ## Specific notes on updating payment profiles. - /// - Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. - /// - If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. - /// - A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. - /// - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. - /// - If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + /// This will delete a payment profile belonging to the customer on the subscription. + /// + If the customer has multiple subscriptions, the payment profile will be removed from all of them. + /// + If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). /// + /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the payment profile. - /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.UpdatePaymentProfileResponse response from the API call. - public async Task UpdatePaymentProfileAsync( - string paymentProfileId, - Models.UpdatePaymentProfileRequest body = null, + /// Returns the void response from the API call. + public async Task DeleteSubscriptionsPaymentProfileAsync( + int subscriptionId, + int paymentProfileId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/payment_profiles/{payment_profile_id}.json") + .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/payment_profiles/{payment_profile_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Deletes an unused payment profile. - /// If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. + /// This will change the default payment profile on the subscription to the existing payment profile with the id specified. + /// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. /// + /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the payment profile. - public void DeleteUnusedPaymentProfile( - string paymentProfileId) - => CoreHelper.RunVoidTask(DeleteUnusedPaymentProfileAsync(paymentProfileId)); + /// Returns the Models.PaymentProfileResponse response from the API call. + public Models.PaymentProfileResponse UpdateSubscriptionDefaultPaymentProfile( + int subscriptionId, + int paymentProfileId) + => CoreHelper.RunTask(UpdateSubscriptionDefaultPaymentProfileAsync(subscriptionId, paymentProfileId)); /// - /// Deletes an unused payment profile. - /// If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. + /// This will change the default payment profile on the subscription to the existing payment profile with the id specified. + /// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. /// + /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the payment profile. /// cancellationToken. - /// Returns the void response from the API call. - public async Task DeleteUnusedPaymentProfileAsync( - string paymentProfileId, + /// Returns the Models.PaymentProfileResponse response from the API call. + public async Task UpdateSubscriptionDefaultPaymentProfileAsync( + int subscriptionId, + int paymentProfileId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/payment_profiles/{payment_profile_id}.json") + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/payment_profiles/{payment_profile_id}/change_payment_profile.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId).Required()))) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new ApiException(_reason, _context))) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This will delete a payment profile belonging to the customer on the subscription. - /// + If the customer has multiple subscriptions, the payment profile will be removed from all of them. - /// + If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). + /// Deletes an unused payment profile. + /// If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. /// - /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the payment profile. - public void DeleteSubscriptionsPaymentProfile( - int subscriptionId, - string paymentProfileId) - => CoreHelper.RunVoidTask(DeleteSubscriptionsPaymentProfileAsync(subscriptionId, paymentProfileId)); + public void DeleteUnusedPaymentProfile( + int paymentProfileId) + => CoreHelper.RunVoidTask(DeleteUnusedPaymentProfileAsync(paymentProfileId)); /// - /// This will delete a payment profile belonging to the customer on the subscription. - /// + If the customer has multiple subscriptions, the payment profile will be removed from all of them. - /// + If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). + /// Deletes an unused payment profile. + /// If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. /// - /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the payment profile. /// cancellationToken. /// Returns the void response from the API call. - public async Task DeleteSubscriptionsPaymentProfileAsync( - int subscriptionId, - string paymentProfileId, + public async Task DeleteUnusedPaymentProfileAsync( + int paymentProfileId, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/payment_profiles/{payment_profile_id}.json") + .Setup(HttpMethod.Delete, "/payment_profiles/{payment_profile_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId).Required()))) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new ApiException(_reason, _context))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -720,73 +828,6 @@ public Models.BankAccountResponse VerifyBankAccount( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// This will delete a Payment Profile belonging to a Subscription Group. - /// **Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. - /// - /// Required parameter: The uid of the subscription group. - /// Required parameter: The Chargify id of the payment profile. - public void DeleteSubscriptionGroupPaymentProfile( - string uid, - string paymentProfileId) - => CoreHelper.RunVoidTask(DeleteSubscriptionGroupPaymentProfileAsync(uid, paymentProfileId)); - - /// - /// This will delete a Payment Profile belonging to a Subscription Group. - /// **Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. - /// - /// Required parameter: The uid of the subscription group. - /// Required parameter: The Chargify id of the payment profile. - /// cancellationToken. - /// Returns the void response from the API call. - public async Task DeleteSubscriptionGroupPaymentProfileAsync( - string uid, - string paymentProfileId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscription_groups/{uid}/payment_profiles/{payment_profile_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("uid", uid).Required()) - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId).Required()))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This will change the default payment profile on the subscription to the existing payment profile with the id specified. - /// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the payment profile. - /// Returns the Models.PaymentProfileResponse response from the API call. - public Models.PaymentProfileResponse UpdateSubscriptionDefaultPaymentProfile( - int subscriptionId, - int paymentProfileId) - => CoreHelper.RunTask(UpdateSubscriptionDefaultPaymentProfileAsync(subscriptionId, paymentProfileId)); - - /// - /// This will change the default payment profile on the subscription to the existing payment profile with the id specified. - /// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the payment profile. - /// cancellationToken. - /// Returns the Models.PaymentProfileResponse response from the API call. - public async Task UpdateSubscriptionDefaultPaymentProfileAsync( - int subscriptionId, - int paymentProfileId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/payment_profiles/{payment_profile_id}/change_payment_profile.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This will change the default payment profile on the subscription group to the existing payment profile with the id specified. /// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. @@ -797,7 +838,7 @@ public Models.PaymentProfileResponse UpdateSubscriptionDefaultPaymentProfile( /// Returns the Models.PaymentProfileResponse response from the API call. public Models.PaymentProfileResponse UpdateSubscriptionGroupDefaultPaymentProfile( string uid, - string paymentProfileId) + int paymentProfileId) => CoreHelper.RunTask(UpdateSubscriptionGroupDefaultPaymentProfileAsync(uid, paymentProfileId)); /// @@ -811,7 +852,7 @@ public Models.PaymentProfileResponse UpdateSubscriptionGroupDefaultPaymentProfil /// Returns the Models.PaymentProfileResponse response from the API call. public async Task UpdateSubscriptionGroupDefaultPaymentProfileAsync( string uid, - string paymentProfileId, + int paymentProfileId, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder @@ -819,7 +860,7 @@ public Models.PaymentProfileResponse UpdateSubscriptionGroupDefaultPaymentProfil .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("uid", uid).Required()) - .Template(_template => _template.Setup("payment_profile_id", paymentProfileId).Required()))) + .Template(_template => _template.Setup("payment_profile_id", paymentProfileId)))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); @@ -855,39 +896,5 @@ public Models.GetOneTimeTokenRequest ReadOneTimeToken( .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// You can send a "request payment update" email to the customer associated with the subscription. - /// If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. - /// Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. - /// These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. - /// - /// Required parameter: The Chargify id of the subscription. - public void SendRequestUpdatePaymentEmail( - int subscriptionId) - => CoreHelper.RunVoidTask(SendRequestUpdatePaymentEmailAsync(subscriptionId)); - - /// - /// You can send a "request payment update" email to the customer associated with the subscription. - /// If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. - /// Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. - /// These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. - /// - /// Required parameter: The Chargify id of the subscription. - /// cancellationToken. - /// Returns the void response from the API call. - public async Task SendRequestUpdatePaymentEmailAsync( - int subscriptionId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/request_payment_profiles_update.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/ProductFamiliesController.cs b/AdvancedBilling.Standard/Controllers/ProductFamiliesController.cs index e20637a..be44582 100644 --- a/AdvancedBilling.Standard/Controllers/ProductFamiliesController.cs +++ b/AdvancedBilling.Standard/Controllers/ProductFamiliesController.cs @@ -35,42 +35,33 @@ public class ProductFamiliesController : BaseController internal ProductFamiliesController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// This method allows to retrieve a list of Products belonging to a Product Family. + /// This method allows to retrieve a list of Product Families for a site. /// /// Object containing request parameters. - /// Returns the List of Models.ProductResponse response from the API call. - public List ListProductsForProductFamily( - Models.ListProductsForProductFamilyInput input) - => CoreHelper.RunTask(ListProductsForProductFamilyAsync(input)); + /// Returns the List of Models.ProductFamilyResponse response from the API call. + public List ListProductFamilies( + Models.ListProductFamiliesInput input) + => CoreHelper.RunTask(ListProductFamiliesAsync(input)); /// - /// This method allows to retrieve a list of Products belonging to a Product Family. + /// This method allows to retrieve a list of Product Families for a site. /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.ProductResponse response from the API call. - public async Task> ListProductsForProductFamilyAsync( - Models.ListProductsForProductFamilyInput input, + /// Returns the List of Models.ProductFamilyResponse response from the API call. + public async Task> ListProductFamiliesAsync( + Models.ListProductFamiliesInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/product_families/{product_family_id}/products.json") + .Setup(HttpMethod.Get, "/product_families.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_family_id", input.ProductFamilyId)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) .Query(_query => _query.Setup("start_date", input.StartDate)) .Query(_query => _query.Setup("end_date", input.EndDate)) .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) - .Query(_query => _query.Setup("include_archived", input.IncludeArchived)) - .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[prepaid_product_price_point][product_price_point_id]", (input.FilterPrepaidProductPricePointProductPricePointId.HasValue) ? ApiHelper.JsonSerialize(input.FilterPrepaidProductPricePointProductPricePointId.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new ApiException(_reason, _context)))) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -105,33 +96,42 @@ public Models.ProductFamilyResponse CreateProductFamily( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method allows to retrieve a list of Product Families for a site. + /// This method allows to retrieve a list of Products belonging to a Product Family. /// /// Object containing request parameters. - /// Returns the List of Models.ProductFamilyResponse response from the API call. - public List ListProductFamilies( - Models.ListProductFamiliesInput input) - => CoreHelper.RunTask(ListProductFamiliesAsync(input)); + /// Returns the List of Models.ProductResponse response from the API call. + public List ListProductsForProductFamily( + Models.ListProductsForProductFamilyInput input) + => CoreHelper.RunTask(ListProductsForProductFamilyAsync(input)); /// - /// This method allows to retrieve a list of Product Families for a site. + /// This method allows to retrieve a list of Products belonging to a Product Family. /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.ProductFamilyResponse response from the API call. - public async Task> ListProductFamiliesAsync( - Models.ListProductFamiliesInput input, + /// Returns the List of Models.ProductResponse response from the API call. + public async Task> ListProductsForProductFamilyAsync( + Models.ListProductsForProductFamilyInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/product_families.json") + .Setup(HttpMethod.Get, "/product_families/{product_family_id}/products.json") .WithAuth("global") .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("product_family_id", input.ProductFamilyId)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) .Query(_query => _query.Setup("start_date", input.StartDate)) .Query(_query => _query.Setup("end_date", input.EndDate)) .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)))) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) + .Query(_query => _query.Setup("include_archived", input.IncludeArchived)) + .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[prepaid_product_price_point][product_price_point_id]", (input.FilterPrepaidProductPricePointProductPricePointId.HasValue) ? ApiHelper.JsonSerialize(input.FilterPrepaidProductPricePointProductPricePointId.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found", (_reason, _context) => new ApiException(_reason, _context)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// diff --git a/AdvancedBilling.Standard/Controllers/ProductPricePointsController.cs b/AdvancedBilling.Standard/Controllers/ProductPricePointsController.cs index 511dc9e..9516b78 100644 --- a/AdvancedBilling.Standard/Controllers/ProductPricePointsController.cs +++ b/AdvancedBilling.Standard/Controllers/ProductPricePointsController.cs @@ -69,111 +69,6 @@ public Models.ProductPricePointResponse CreateProductPricePoint( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ProductPricePointErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// Use this endpoint to retrieve a list of product price points. - /// - /// Object containing request parameters. - /// Returns the Models.ListProductPricePointsResponse response from the API call. - public Models.ListProductPricePointsResponse ListProductPricePoints( - Models.ListProductPricePointsInput input) - => CoreHelper.RunTask(ListProductPricePointsAsync(input)); - - /// - /// Use this endpoint to retrieve a list of product price points. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.ListProductPricePointsResponse response from the API call. - public async Task ListProductPricePointsAsync( - Models.ListProductPricePointsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/products/{product_id}/price_points.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_id", input.ProductId).Required()) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("currency_prices", input.CurrencyPrices)) - .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to update a product price point. - /// Note: Custom product price points are not able to be updated. - /// - /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. - /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. - /// Optional parameter: Example: . - /// Returns the Models.ProductPricePointResponse response from the API call. - public Models.ProductPricePointResponse UpdateProductPricePoint( - UpdateProductPricePointProductId productId, - UpdateProductPricePointPricePointId pricePointId, - Models.UpdateProductPricePointRequest body = null) - => CoreHelper.RunTask(UpdateProductPricePointAsync(productId, pricePointId, body)); - - /// - /// Use this endpoint to update a product price point. - /// Note: Custom product price points are not able to be updated. - /// - /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. - /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.ProductPricePointResponse response from the API call. - public async Task UpdateProductPricePointAsync( - UpdateProductPricePointProductId productId, - UpdateProductPricePointPricePointId pricePointId, - Models.UpdateProductPricePointRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/products/{product_id}/price_points/{price_point_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("product_id", productId).Required()) - .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to retrieve details for a specific product price point. - /// - /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. - /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. - /// Optional parameter: When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency.. - /// Returns the Models.ProductPricePointResponse response from the API call. - public Models.ProductPricePointResponse ReadProductPricePoint( - ReadProductPricePointProductId productId, - ReadProductPricePointPricePointId pricePointId, - bool? currencyPrices = null) - => CoreHelper.RunTask(ReadProductPricePointAsync(productId, pricePointId, currencyPrices)); - - /// - /// Use this endpoint to retrieve details for a specific product price point. - /// - /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. - /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. - /// Optional parameter: When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency.. - /// cancellationToken. - /// Returns the Models.ProductPricePointResponse response from the API call. - public async Task ReadProductPricePointAsync( - ReadProductPricePointProductId productId, - ReadProductPricePointPricePointId pricePointId, - bool? currencyPrices = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/products/{product_id}/price_points/{price_point_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_id", productId).Required()) - .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) - .Query(_query => _query.Setup("currency_prices", currencyPrices)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// Use this endpoint to archive a product price point. /// @@ -238,6 +133,83 @@ public Models.ProductPricePointResponse UnarchiveProductPricePoint( .Template(_template => _template.Setup("price_point_id", pricePointId)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// This method allows retrieval of a list of Products Price Points belonging to a Site. + /// + /// Object containing request parameters. + /// Returns the Models.ListProductPricePointsResponse response from the API call. + public Models.ListProductPricePointsResponse ListAllProductPricePoints( + Models.ListAllProductPricePointsInput input) + => CoreHelper.RunTask(ListAllProductPricePointsAsync(input)); + + /// + /// This method allows retrieval of a list of Products Price Points belonging to a Site. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.ListProductPricePointsResponse response from the API call. + public async Task ListAllProductPricePointsAsync( + Models.ListAllProductPricePointsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/products_price_points.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[archived_at]", (input.FilterArchivedAt.HasValue) ? ApiHelper.JsonSerialize(input.FilterArchivedAt.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[date_field]", (input.FilterDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterDateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[end_date]", input.FilterEndDate.HasValue ? input.FilterEndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("filter[end_datetime]", input.FilterEndDatetime.HasValue ? input.FilterEndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) + .Query(_query => _query.Setup("filter[start_date]", input.FilterStartDate.HasValue ? input.FilterStartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("filter[start_datetime]", input.FilterStartDatetime.HasValue ? input.FilterStartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())) + .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. + /// When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. + /// Note: Currency Prices are not able to be updated for custom product price points. + /// + /// Required parameter: The Chargify id of the product price point. + /// Optional parameter: Example: . + /// Returns the Models.CurrencyPricesResponse response from the API call. + public Models.CurrencyPricesResponse UpdateProductCurrencyPrices( + int productPricePointId, + Models.UpdateCurrencyPricesRequest body = null) + => CoreHelper.RunTask(UpdateProductCurrencyPricesAsync(productPricePointId, body)); + + /// + /// This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. + /// When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. + /// Note: Currency Prices are not able to be updated for custom product price points. + /// + /// Required parameter: The Chargify id of the product price point. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.CurrencyPricesResponse response from the API call. + public async Task UpdateProductCurrencyPricesAsync( + int productPricePointId, + Models.UpdateCurrencyPricesRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/product_price_points/{product_price_point_id}/currency_prices.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_price_point_id", productPricePointId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// Use this endpoint to make a product price point the default for the product. /// Note: Custom product price points are not able to be set as the default for a product. @@ -312,8 +284,8 @@ public Models.BulkCreateProductPricePointsResponse CreateProductPricePoints( /// /// Required parameter: The Chargify id of the product price point. /// Optional parameter: Example: . - /// Returns the Models.ProductPricePointCurrencyPrice response from the API call. - public Models.ProductPricePointCurrencyPrice CreateProductCurrencyPrices( + /// Returns the Models.CurrencyPricesResponse response from the API call. + public Models.CurrencyPricesResponse CreateProductCurrencyPrices( int productPricePointId, Models.CreateProductCurrencyPricesRequest body = null) => CoreHelper.RunTask(CreateProductCurrencyPricesAsync(productPricePointId, body)); @@ -326,12 +298,12 @@ public Models.ProductPricePointCurrencyPrice CreateProductCurrencyPrices( /// Required parameter: The Chargify id of the product price point. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.ProductPricePointCurrencyPrice response from the API call. - public async Task CreateProductCurrencyPricesAsync( + /// Returns the Models.CurrencyPricesResponse response from the API call. + public async Task CreateProductCurrencyPricesAsync( int productPricePointId, Models.CreateProductCurrencyPricesRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder .Setup(HttpMethod.Post, "/product_price_points/{product_price_point_id}/currency_prices.json") .WithAuth("global") @@ -340,84 +312,112 @@ public Models.ProductPricePointCurrencyPrice CreateProductCurrencyPrices( .Template(_template => _template.Setup("product_price_point_id", productPricePointId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorMapResponseException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. - /// When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. - /// Note: Currency Prices are not able to be updated for custom product price points. + /// Use this endpoint to retrieve a list of product price points. /// - /// Required parameter: The Chargify id of the product price point. + /// Object containing request parameters. + /// Returns the Models.ListProductPricePointsResponse response from the API call. + public Models.ListProductPricePointsResponse ListProductPricePoints( + Models.ListProductPricePointsInput input) + => CoreHelper.RunTask(ListProductPricePointsAsync(input)); + + /// + /// Use this endpoint to retrieve a list of product price points. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.ListProductPricePointsResponse response from the API call. + public async Task ListProductPricePointsAsync( + Models.ListProductPricePointsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/products/{product_id}/price_points.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("product_id", input.ProductId).Required()) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("currency_prices", input.CurrencyPrices)) + .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to update a product price point. + /// Note: Custom product price points are not able to be updated. + /// + /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. + /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. /// Optional parameter: Example: . - /// Returns the Models.ProductPricePointCurrencyPrice response from the API call. - public Models.ProductPricePointCurrencyPrice UpdateProductCurrencyPrices( - int productPricePointId, - Models.UpdateCurrencyPricesRequest body = null) - => CoreHelper.RunTask(UpdateProductCurrencyPricesAsync(productPricePointId, body)); + /// Returns the Models.ProductPricePointResponse response from the API call. + public Models.ProductPricePointResponse UpdateProductPricePoint( + UpdateProductPricePointProductId productId, + UpdateProductPricePointPricePointId pricePointId, + Models.UpdateProductPricePointRequest body = null) + => CoreHelper.RunTask(UpdateProductPricePointAsync(productId, pricePointId, body)); /// - /// This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. - /// When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. - /// Note: Currency Prices are not able to be updated for custom product price points. + /// Use this endpoint to update a product price point. + /// Note: Custom product price points are not able to be updated. /// - /// Required parameter: The Chargify id of the product price point. + /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. + /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.ProductPricePointCurrencyPrice response from the API call. - public async Task UpdateProductCurrencyPricesAsync( - int productPricePointId, - Models.UpdateCurrencyPricesRequest body = null, + /// Returns the Models.ProductPricePointResponse response from the API call. + public async Task UpdateProductPricePointAsync( + UpdateProductPricePointProductId productId, + UpdateProductPricePointPricePointId pricePointId, + Models.UpdateProductPricePointRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/product_price_points/{product_price_point_id}/currency_prices.json") + .Setup(HttpMethod.Put, "/products/{product_id}/price_points/{price_point_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("product_price_point_id", productPricePointId)) + .Template(_template => _template.Setup("product_id", productId).Required()) + .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorMapResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method allows retrieval of a list of Products Price Points belonging to a Site. + /// Use this endpoint to retrieve details for a specific product price point. /// - /// Object containing request parameters. - /// Returns the Models.ListProductPricePointsResponse response from the API call. - public Models.ListProductPricePointsResponse ListAllProductPricePoints( - Models.ListAllProductPricePointsInput input) - => CoreHelper.RunTask(ListAllProductPricePointsAsync(input)); + /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. + /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. + /// Optional parameter: When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency.. + /// Returns the Models.ProductPricePointResponse response from the API call. + public Models.ProductPricePointResponse ReadProductPricePoint( + ReadProductPricePointProductId productId, + ReadProductPricePointPricePointId pricePointId, + bool? currencyPrices = null) + => CoreHelper.RunTask(ReadProductPricePointAsync(productId, pricePointId, currencyPrices)); /// - /// This method allows retrieval of a list of Products Price Points belonging to a Site. + /// Use this endpoint to retrieve details for a specific product price point. /// - /// Object containing request parameters. + /// Required parameter: The id or handle of the product. When using the handle, it must be prefixed with `handle:`. + /// Required parameter: The id or handle of the price point. When using the handle, it must be prefixed with `handle:`. + /// Optional parameter: When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency.. /// cancellationToken. - /// Returns the Models.ListProductPricePointsResponse response from the API call. - public async Task ListAllProductPricePointsAsync( - Models.ListAllProductPricePointsInput input, + /// Returns the Models.ProductPricePointResponse response from the API call. + public async Task ReadProductPricePointAsync( + ReadProductPricePointProductId productId, + ReadProductPricePointPricePointId pricePointId, + bool? currencyPrices = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/products_price_points.json") + .Setup(HttpMethod.Get, "/products/{product_id}/price_points/{price_point_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[archived_at]", (input.FilterArchivedAt.HasValue) ? ApiHelper.JsonSerialize(input.FilterArchivedAt.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[date_field]", (input.FilterDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterDateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[end_date]", input.FilterEndDate.HasValue ? input.FilterEndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("filter[end_datetime]", input.FilterEndDatetime.HasValue ? input.FilterEndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("filter[ids]", input.FilterIds)) - .Query(_query => _query.Setup("filter[start_date]", input.FilterStartDate.HasValue ? input.FilterStartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("filter[start_datetime]", input.FilterStartDatetime.HasValue ? input.FilterStartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("filter[type]", input.FilterType?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())) - .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .Template(_template => _template.Setup("product_id", productId).Required()) + .Template(_template => _template.Setup("price_point_id", pricePointId).Required()) + .Query(_query => _query.Setup("currency_prices", currencyPrices)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/ProductsController.cs b/AdvancedBilling.Standard/Controllers/ProductsController.cs index 4a10ce9..86f196a 100644 --- a/AdvancedBilling.Standard/Controllers/ProductsController.cs +++ b/AdvancedBilling.Standard/Controllers/ProductsController.cs @@ -35,43 +35,97 @@ public class ProductsController : BaseController internal ProductsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// Use this method to create a product within your Chargify site. - /// + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709). - /// + [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations). + /// Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. + /// This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. /// - /// Required parameter: The Chargify id of the product family to which the product belongs. - /// Optional parameter: Example: . + /// Required parameter: The Chargify id of the product. /// Returns the Models.ProductResponse response from the API call. - public Models.ProductResponse CreateProduct( - int productFamilyId, - Models.CreateOrUpdateProductRequest body = null) - => CoreHelper.RunTask(CreateProductAsync(productFamilyId, body)); + public Models.ProductResponse ArchiveProduct( + int productId) + => CoreHelper.RunTask(ArchiveProductAsync(productId)); /// - /// Use this method to create a product within your Chargify site. - /// + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709). - /// + [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations). + /// Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. + /// This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. /// - /// Required parameter: The Chargify id of the product family to which the product belongs. - /// Optional parameter: Example: . + /// Required parameter: The Chargify id of the product. /// cancellationToken. /// Returns the Models.ProductResponse response from the API call. - public async Task CreateProductAsync( - int productFamilyId, - Models.CreateOrUpdateProductRequest body = null, + public async Task ArchiveProductAsync( + int productId, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/product_families/{product_family_id}/products.json") + .Setup(HttpMethod.Delete, "/products/{product_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("product_family_id", productFamilyId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Template(_template => _template.Setup("product_id", productId)))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// This method allows to retrieve a Product object by its `api_handle`. + /// + /// Required parameter: The handle of the product. + /// Returns the Models.ProductResponse response from the API call. + public Models.ProductResponse ReadProductByHandle( + string apiHandle) + => CoreHelper.RunTask(ReadProductByHandleAsync(apiHandle)); + + /// + /// This method allows to retrieve a Product object by its `api_handle`. + /// + /// Required parameter: The handle of the product. + /// cancellationToken. + /// Returns the Models.ProductResponse response from the API call. + public async Task ReadProductByHandleAsync( + string apiHandle, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/products/handle/{api_handle}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("api_handle", apiHandle).Required()))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This method allows to retrieve a list of Products belonging to a Site. + /// + /// Object containing request parameters. + /// Returns the List of Models.ProductResponse response from the API call. + public List ListProducts( + Models.ListProductsInput input) + => CoreHelper.RunTask(ListProductsAsync(input)); + + /// + /// This method allows to retrieve a list of Products belonging to a Site. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the List of Models.ProductResponse response from the API call. + public async Task> ListProductsAsync( + Models.ListProductsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/products.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("end_date", input.EndDate.HasValue ? input.EndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime.HasValue ? input.EndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("start_date", input.StartDate.HasValue ? input.StartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime.HasValue ? input.StartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("include_archived", input.IncludeArchived)) + .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[prepaid_product_price_point][product_price_point_id]", (input.FilterPrepaidProductPricePointProductPricePointId.HasValue) ? ApiHelper.JsonSerialize(input.FilterPrepaidProductPricePointProductPricePointId.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// This endpoint allows you to read the current details of a product that you've created in Chargify. /// @@ -141,95 +195,41 @@ public Models.ProductResponse UpdateProduct( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. - /// This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. + /// Use this method to create a product within your Chargify site. + /// + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709). + /// + [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations). /// - /// Required parameter: The Chargify id of the product. + /// Required parameter: The Chargify id of the product family to which the product belongs. + /// Optional parameter: Example: . /// Returns the Models.ProductResponse response from the API call. - public Models.ProductResponse ArchiveProduct( - int productId) - => CoreHelper.RunTask(ArchiveProductAsync(productId)); + public Models.ProductResponse CreateProduct( + int productFamilyId, + Models.CreateOrUpdateProductRequest body = null) + => CoreHelper.RunTask(CreateProductAsync(productFamilyId, body)); /// - /// Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. - /// This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. + /// Use this method to create a product within your Chargify site. + /// + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709). + /// + [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations). /// - /// Required parameter: The Chargify id of the product. + /// Required parameter: The Chargify id of the product family to which the product belongs. + /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ProductResponse response from the API call. - public async Task ArchiveProductAsync( - int productId, + public async Task CreateProductAsync( + int productFamilyId, + Models.CreateOrUpdateProductRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/products/{product_id}.json") + .Setup(HttpMethod.Post, "/product_families/{product_family_id}/products.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("product_id", productId)))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("product_family_id", productFamilyId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This method allows to retrieve a Product object by its `api_handle`. - /// - /// Required parameter: The handle of the product. - /// Returns the Models.ProductResponse response from the API call. - public Models.ProductResponse ReadProductByHandle( - string apiHandle) - => CoreHelper.RunTask(ReadProductByHandleAsync(apiHandle)); - - /// - /// This method allows to retrieve a Product object by its `api_handle`. - /// - /// Required parameter: The handle of the product. - /// cancellationToken. - /// Returns the Models.ProductResponse response from the API call. - public async Task ReadProductByHandleAsync( - string apiHandle, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/products/handle/{api_handle}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("api_handle", apiHandle).Required()))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This method allows to retrieve a list of Products belonging to a Site. - /// - /// Object containing request parameters. - /// Returns the List of Models.ProductResponse response from the API call. - public List ListProducts( - Models.ListProductsInput input) - => CoreHelper.RunTask(ListProductsAsync(input)); - - /// - /// This method allows to retrieve a list of Products belonging to a Site. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the List of Models.ProductResponse response from the API call. - public async Task> ListProductsAsync( - Models.ListProductsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/products.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("end_date", input.EndDate.HasValue ? input.EndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime.HasValue ? input.EndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("start_date", input.StartDate.HasValue ? input.StartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime.HasValue ? input.StartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("include_archived", input.IncludeArchived)) - .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[prepaid_product_price_point][product_price_point_id]", (input.FilterPrepaidProductPricePointProductPricePointId.HasValue) ? ApiHelper.JsonSerialize(input.FilterPrepaidProductPricePointProductPricePointId.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/ProformaInvoicesController.cs b/AdvancedBilling.Standard/Controllers/ProformaInvoicesController.cs index 7b2ccb4..65abc58 100644 --- a/AdvancedBilling.Standard/Controllers/ProformaInvoicesController.cs +++ b/AdvancedBilling.Standard/Controllers/ProformaInvoicesController.cs @@ -35,96 +35,110 @@ public class ProformaInvoicesController : BaseController internal ProformaInvoicesController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. - /// If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. + /// This endpoint will void a proforma invoice that has the status "draft". /// ## Restrictions. - /// Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. + /// Proforma invoices are only available on Relationship Invoicing sites. + /// Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. + /// A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. /// - /// Required parameter: The uid of the subscription group. - public void CreateConsolidatedProformaInvoice( - string uid) - => CoreHelper.RunVoidTask(CreateConsolidatedProformaInvoiceAsync(uid)); + /// Required parameter: The uid of the proforma invoice. + /// Optional parameter: Example: . + /// Returns the Models.ProformaInvoice response from the API call. + public Models.ProformaInvoice VoidProformaInvoice( + string proformaInvoiceUid, + Models.VoidInvoiceRequest body = null) + => CoreHelper.RunTask(VoidProformaInvoiceAsync(proformaInvoiceUid, body)); /// - /// This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. - /// If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. + /// This endpoint will void a proforma invoice that has the status "draft". /// ## Restrictions. - /// Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. + /// Proforma invoices are only available on Relationship Invoicing sites. + /// Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. + /// A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. /// - /// Required parameter: The uid of the subscription group. + /// Required parameter: The uid of the proforma invoice. + /// Optional parameter: Example: . /// cancellationToken. - /// Returns the void response from the API call. - public async Task CreateConsolidatedProformaInvoiceAsync( - string uid, + /// Returns the Models.ProformaInvoice response from the API call. + public async Task VoidProformaInvoiceAsync( + string proformaInvoiceUid, + Models.VoidInvoiceRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscription_groups/{uid}/proforma_invoices.json") + .Setup(HttpMethod.Post, "/proforma_invoices/{proforma_invoice_uid}/void.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("uid", uid).Required()))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("proforma_invoice_uid", proformaInvoiceUid).Required()) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Only proforma invoices with a `consolidation_level` of parent are returned. - /// By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. + /// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. + /// Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. + /// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. + /// A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. /// - /// Required parameter: The uid of the subscription group. + /// Optional parameter: Example: . /// Returns the Models.ProformaInvoice response from the API call. - public Models.ProformaInvoice ListSubscriptionGroupProformaInvoices( - string uid) - => CoreHelper.RunTask(ListSubscriptionGroupProformaInvoicesAsync(uid)); + public Models.ProformaInvoice CreateSignupProformaInvoice( + Models.CreateSubscriptionRequest body = null) + => CoreHelper.RunTask(CreateSignupProformaInvoiceAsync(body)); /// - /// Only proforma invoices with a `consolidation_level` of parent are returned. - /// By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. + /// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. + /// Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. + /// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. + /// A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. /// - /// Required parameter: The uid of the subscription group. + /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ProformaInvoice response from the API call. - public async Task ListSubscriptionGroupProformaInvoicesAsync( - string uid, + public async Task CreateSignupProformaInvoiceAsync( + Models.CreateSubscriptionRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscription_groups/{uid}/proforma_invoices.json") + .Setup(HttpMethod.Post, "/subscriptions/proforma_invoices.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("uid", uid).Required()))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ProformaBadRequestErrorResponseException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to read the details of an existing proforma invoice. - /// ## Restrictions. - /// Proforma invoices are only available on Relationship Invoicing sites. + /// Only proforma invoices with a `consolidation_level` of parent are returned. + /// By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. /// - /// Required parameter: The uid of the proforma invoice. + /// Required parameter: The uid of the subscription group. /// Returns the Models.ProformaInvoice response from the API call. - public Models.ProformaInvoice ReadProformaInvoice( - int proformaInvoiceUid) - => CoreHelper.RunTask(ReadProformaInvoiceAsync(proformaInvoiceUid)); + public Models.ProformaInvoice ListSubscriptionGroupProformaInvoices( + string uid) + => CoreHelper.RunTask(ListSubscriptionGroupProformaInvoicesAsync(uid)); /// - /// Use this endpoint to read the details of an existing proforma invoice. - /// ## Restrictions. - /// Proforma invoices are only available on Relationship Invoicing sites. + /// Only proforma invoices with a `consolidation_level` of parent are returned. + /// By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. /// - /// Required parameter: The uid of the proforma invoice. + /// Required parameter: The uid of the subscription group. /// cancellationToken. /// Returns the Models.ProformaInvoice response from the API call. - public async Task ReadProformaInvoiceAsync( - int proformaInvoiceUid, + public async Task ListSubscriptionGroupProformaInvoicesAsync( + string uid, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/proforma_invoices/{proforma_invoice_uid}.json") + .Setup(HttpMethod.Get, "/subscription_groups/{uid}/proforma_invoices.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("proforma_invoice_uid", proformaInvoiceUid)))) + .Template(_template => _template.Setup("uid", uid).Required()))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); @@ -163,6 +177,38 @@ public Models.ProformaInvoice CreateProformaInvoice( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// Use this endpoint to read the details of an existing proforma invoice. + /// ## Restrictions. + /// Proforma invoices are only available on Relationship Invoicing sites. + /// + /// Required parameter: The uid of the proforma invoice. + /// Returns the Models.ProformaInvoice response from the API call. + public Models.ProformaInvoice ReadProformaInvoice( + int proformaInvoiceUid) + => CoreHelper.RunTask(ReadProformaInvoiceAsync(proformaInvoiceUid)); + + /// + /// Use this endpoint to read the details of an existing proforma invoice. + /// ## Restrictions. + /// Proforma invoices are only available on Relationship Invoicing sites. + /// + /// Required parameter: The uid of the proforma invoice. + /// cancellationToken. + /// Returns the Models.ProformaInvoice response from the API call. + public async Task ReadProformaInvoiceAsync( + int proformaInvoiceUid, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/proforma_invoices/{proforma_invoice_uid}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("proforma_invoice_uid", proformaInvoiceUid)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. /// @@ -202,45 +248,35 @@ public Models.ProformaInvoice CreateProformaInvoice( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint will void a proforma invoice that has the status "draft". + /// This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. + /// If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. /// ## Restrictions. - /// Proforma invoices are only available on Relationship Invoicing sites. - /// Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. - /// A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. + /// Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. /// - /// Required parameter: The uid of the proforma invoice. - /// Optional parameter: Example: . - /// Returns the Models.ProformaInvoice response from the API call. - public Models.ProformaInvoice VoidProformaInvoice( - string proformaInvoiceUid, - Models.VoidInvoiceRequest body = null) - => CoreHelper.RunTask(VoidProformaInvoiceAsync(proformaInvoiceUid, body)); + /// Required parameter: The uid of the subscription group. + public void CreateConsolidatedProformaInvoice( + string uid) + => CoreHelper.RunVoidTask(CreateConsolidatedProformaInvoiceAsync(uid)); /// - /// This endpoint will void a proforma invoice that has the status "draft". + /// This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. + /// If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. /// ## Restrictions. - /// Proforma invoices are only available on Relationship Invoicing sites. - /// Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. - /// A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. + /// Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. /// - /// Required parameter: The uid of the proforma invoice. - /// Optional parameter: Example: . + /// Required parameter: The uid of the subscription group. /// cancellationToken. - /// Returns the Models.ProformaInvoice response from the API call. - public async Task VoidProformaInvoiceAsync( - string proformaInvoiceUid, - Models.VoidInvoiceRequest body = null, + /// Returns the void response from the API call. + public async Task CreateConsolidatedProformaInvoiceAsync( + string uid, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/proforma_invoices/{proforma_invoice_uid}/void.json") + .Setup(HttpMethod.Post, "/subscription_groups/{uid}/proforma_invoices.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("proforma_invoice_uid", proformaInvoiceUid).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Template(_template => _template.Setup("uid", uid).Required()))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); @@ -279,42 +315,6 @@ public Models.ProformaInvoicePreview PreviewProformaInvoice( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. - /// Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. - /// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. - /// A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. - /// - /// Optional parameter: Example: . - /// Returns the Models.ProformaInvoice response from the API call. - public Models.ProformaInvoice CreateSignupProformaInvoice( - Models.CreateSubscriptionRequest body = null) - => CoreHelper.RunTask(CreateSignupProformaInvoiceAsync(body)); - - /// - /// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. - /// Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. - /// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. - /// A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. - /// - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.ProformaInvoice response from the API call. - public async Task CreateSignupProformaInvoiceAsync( - Models.CreateSubscriptionRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/proforma_invoices.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ProformaBadRequestErrorResponseException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorMapResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoice previews or preview prepaid subscriptions. /// Create a signup preview in the format of a proforma invoice to preview costs before a subscription's signup. You have the option of optionally previewing the first renewal's costs as well. The proforma invoice preview will not be persisted. @@ -353,7 +353,7 @@ public Models.SignupProformaPreviewResponse PreviewSignupProformaInvoice( .Query(_query => _query.Setup("include=next_proforma_invoice", includeNextProformaInvoice)))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ProformaBadRequestErrorResponseException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorMapResponseException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/ReasonCodesController.cs b/AdvancedBilling.Standard/Controllers/ReasonCodesController.cs index 7336950..bb8bc37 100644 --- a/AdvancedBilling.Standard/Controllers/ReasonCodesController.cs +++ b/AdvancedBilling.Standard/Controllers/ReasonCodesController.cs @@ -35,46 +35,37 @@ public class ReasonCodesController : BaseController internal ReasonCodesController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// # Reason Codes Intro. - /// ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. - /// Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. - /// ## Reason Code Documentation. - /// Full documentation on how Reason Codes operate within Chargify can be located under the following links. - /// [Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes). - /// ## Create Reason Code. - /// This method gives a merchant the option to create a reason codes for a given Site. + /// This method gives a merchant the option to update an existing reason code for a given site. /// + /// Required parameter: The Chargify id of the reason code. /// Optional parameter: Example: . /// Returns the Models.ReasonCodeResponse response from the API call. - public Models.ReasonCodeResponse CreateReasonCode( - Models.CreateReasonCodeRequest body = null) - => CoreHelper.RunTask(CreateReasonCodeAsync(body)); + public Models.ReasonCodeResponse UpdateReasonCode( + int reasonCodeId, + Models.UpdateReasonCodeRequest body = null) + => CoreHelper.RunTask(UpdateReasonCodeAsync(reasonCodeId, body)); /// - /// # Reason Codes Intro. - /// ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. - /// Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. - /// ## Reason Code Documentation. - /// Full documentation on how Reason Codes operate within Chargify can be located under the following links. - /// [Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes). - /// ## Create Reason Code. - /// This method gives a merchant the option to create a reason codes for a given Site. + /// This method gives a merchant the option to update an existing reason code for a given site. /// + /// Required parameter: The Chargify id of the reason code. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ReasonCodeResponse response from the API call. - public async Task CreateReasonCodeAsync( - Models.CreateReasonCodeRequest body = null, + public async Task UpdateReasonCodeAsync( + int reasonCodeId, + Models.UpdateReasonCodeRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/reason_codes.json") + .Setup(HttpMethod.Put, "/reason_codes/{reason_code_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("reason_code_id", reasonCodeId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -105,63 +96,72 @@ public Models.ReasonCodeResponse CreateReasonCode( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. + /// # Reason Codes Intro. + /// ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. + /// Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. + /// ## Reason Code Documentation. + /// Full documentation on how Reason Codes operate within Chargify can be located under the following links. + /// [Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes). + /// ## Create Reason Code. + /// This method gives a merchant the option to create a reason codes for a given Site. /// - /// Required parameter: The Chargify id of the reason code. + /// Optional parameter: Example: . /// Returns the Models.ReasonCodeResponse response from the API call. - public Models.ReasonCodeResponse ReadReasonCode( - int reasonCodeId) - => CoreHelper.RunTask(ReadReasonCodeAsync(reasonCodeId)); + public Models.ReasonCodeResponse CreateReasonCode( + Models.CreateReasonCodeRequest body = null) + => CoreHelper.RunTask(CreateReasonCodeAsync(body)); /// - /// This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. + /// # Reason Codes Intro. + /// ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. + /// Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. + /// ## Reason Code Documentation. + /// Full documentation on how Reason Codes operate within Chargify can be located under the following links. + /// [Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes). + /// ## Create Reason Code. + /// This method gives a merchant the option to create a reason codes for a given Site. /// - /// Required parameter: The Chargify id of the reason code. + /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ReasonCodeResponse response from the API call. - public async Task ReadReasonCodeAsync( - int reasonCodeId, + public async Task CreateReasonCodeAsync( + Models.CreateReasonCodeRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/reason_codes/{reason_code_id}.json") + .Setup(HttpMethod.Post, "/reason_codes.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("reason_code_id", reasonCodeId)))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This method gives a merchant the option to update an existing reason code for a given site. + /// This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. /// /// Required parameter: The Chargify id of the reason code. - /// Optional parameter: Example: . /// Returns the Models.ReasonCodeResponse response from the API call. - public Models.ReasonCodeResponse UpdateReasonCode( - int reasonCodeId, - Models.UpdateReasonCodeRequest body = null) - => CoreHelper.RunTask(UpdateReasonCodeAsync(reasonCodeId, body)); + public Models.ReasonCodeResponse ReadReasonCode( + int reasonCodeId) + => CoreHelper.RunTask(ReadReasonCodeAsync(reasonCodeId)); /// - /// This method gives a merchant the option to update an existing reason code for a given site. + /// This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. /// /// Required parameter: The Chargify id of the reason code. - /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.ReasonCodeResponse response from the API call. - public async Task UpdateReasonCodeAsync( + public async Task ReadReasonCodeAsync( int reasonCodeId, - Models.UpdateReasonCodeRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/reason_codes/{reason_code_id}.json") + .Setup(HttpMethod.Get, "/reason_codes/{reason_code_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("reason_code_id", reasonCodeId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Template(_template => _template.Setup("reason_code_id", reasonCodeId)))) .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); diff --git a/AdvancedBilling.Standard/Controllers/SalesCommissionsController.cs b/AdvancedBilling.Standard/Controllers/SalesCommissionsController.cs index 0f9150b..8f40504 100644 --- a/AdvancedBilling.Standard/Controllers/SalesCommissionsController.cs +++ b/AdvancedBilling.Standard/Controllers/SalesCommissionsController.cs @@ -34,20 +34,20 @@ public class SalesCommissionsController : BaseController internal SalesCommissionsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// Endpoint returns subscriptions with associated sales reps. + /// Endpoint returns sales rep list with details. /// ## Modified Authentication Process. /// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). /// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. /// > Note: The request is at seller level, it means `<>` variable will be replaced by `app`. /// /// Object containing request parameters. - /// Returns the List of Models.SaleRepSettings response from the API call. - public List ListSalesCommissionSettings( - Models.ListSalesCommissionSettingsInput input) - => CoreHelper.RunTask(ListSalesCommissionSettingsAsync(input)); + /// Returns the List of Models.ListSaleRepItem response from the API call. + public List ListSalesReps( + Models.ListSalesRepsInput input) + => CoreHelper.RunTask(ListSalesRepsAsync(input)); /// - /// Endpoint returns subscriptions with associated sales reps. + /// Endpoint returns sales rep list with details. /// ## Modified Authentication Process. /// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). /// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. @@ -55,13 +55,13 @@ internal SalesCommissionsController(GlobalConfiguration globalConfiguration) : b /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.SaleRepSettings response from the API call. - public async Task> ListSalesCommissionSettingsAsync( - Models.ListSalesCommissionSettingsInput input, + /// Returns the List of Models.ListSaleRepItem response from the API call. + public async Task> ListSalesRepsAsync( + Models.ListSalesRepsInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/sellers/{seller_id}/sales_commission_settings.json") + .Setup(HttpMethod.Get, "/sellers/{seller_id}/sales_reps.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("seller_id", input.SellerId).Required()) @@ -72,20 +72,20 @@ internal SalesCommissionsController(GlobalConfiguration globalConfiguration) : b .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Endpoint returns sales rep list with details. + /// Endpoint returns subscriptions with associated sales reps. /// ## Modified Authentication Process. /// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). /// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. /// > Note: The request is at seller level, it means `<>` variable will be replaced by `app`. /// /// Object containing request parameters. - /// Returns the List of Models.ListSaleRepItem response from the API call. - public List ListSalesReps( - Models.ListSalesRepsInput input) - => CoreHelper.RunTask(ListSalesRepsAsync(input)); + /// Returns the List of Models.SaleRepSettings response from the API call. + public List ListSalesCommissionSettings( + Models.ListSalesCommissionSettingsInput input) + => CoreHelper.RunTask(ListSalesCommissionSettingsAsync(input)); /// - /// Endpoint returns sales rep list with details. + /// Endpoint returns subscriptions with associated sales reps. /// ## Modified Authentication Process. /// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). /// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. @@ -93,13 +93,13 @@ internal SalesCommissionsController(GlobalConfiguration globalConfiguration) : b /// /// Object containing request parameters. /// cancellationToken. - /// Returns the List of Models.ListSaleRepItem response from the API call. - public async Task> ListSalesRepsAsync( - Models.ListSalesRepsInput input, + /// Returns the List of Models.SaleRepSettings response from the API call. + public async Task> ListSalesCommissionSettingsAsync( + Models.ListSalesCommissionSettingsInput input, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/sellers/{seller_id}/sales_reps.json") + .Setup(HttpMethod.Get, "/sellers/{seller_id}/sales_commission_settings.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("seller_id", input.SellerId).Required()) diff --git a/AdvancedBilling.Standard/Controllers/SitesController.cs b/AdvancedBilling.Standard/Controllers/SitesController.cs index c5ed41a..700a558 100644 --- a/AdvancedBilling.Standard/Controllers/SitesController.cs +++ b/AdvancedBilling.Standard/Controllers/SitesController.cs @@ -34,40 +34,30 @@ public class SitesController : BaseController internal SitesController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// This endpoint allows you to fetch some site data. - /// Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). - /// Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. - /// #### Relationship invoicing enabled. - /// If site has RI enabled then you will see more settings like:. - /// "customer_hierarchy_enabled": true,. - /// "whopays_enabled": true,. - /// "whopays_default_payer": "self". - /// You can read more about these settings here:. - /// [Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291). + /// This endpoint returns public keys used for Chargify.js. /// - /// Returns the Models.SiteResponse response from the API call. - public Models.SiteResponse ReadSite() - => CoreHelper.RunTask(ReadSiteAsync()); + /// Object containing request parameters. + /// Returns the Models.ListPublicKeysResponse response from the API call. + public Models.ListPublicKeysResponse ListChargifyJsPublicKeys( + Models.ListChargifyJsPublicKeysInput input) + => CoreHelper.RunTask(ListChargifyJsPublicKeysAsync(input)); /// - /// This endpoint allows you to fetch some site data. - /// Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). - /// Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. - /// #### Relationship invoicing enabled. - /// If site has RI enabled then you will see more settings like:. - /// "customer_hierarchy_enabled": true,. - /// "whopays_enabled": true,. - /// "whopays_default_payer": "self". - /// You can read more about these settings here:. - /// [Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291). + /// This endpoint returns public keys used for Chargify.js. /// + /// Object containing request parameters. /// cancellationToken. - /// Returns the Models.SiteResponse response from the API call. - public async Task ReadSiteAsync(CancellationToken cancellationToken = default) - => await CreateApiCall() + /// Returns the Models.ListPublicKeysResponse response from the API call. + public async Task ListChargifyJsPublicKeysAsync( + Models.ListChargifyJsPublicKeysInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/site.json") - .WithAuth("global")) + .Setup(HttpMethod.Get, "/chargify_js_keys.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -98,30 +88,40 @@ public async Task ClearSiteAsync( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint returns public keys used for Chargify.js. + /// This endpoint allows you to fetch some site data. + /// Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). + /// Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. + /// #### Relationship invoicing enabled. + /// If site has RI enabled then you will see more settings like:. + /// "customer_hierarchy_enabled": true,. + /// "whopays_enabled": true,. + /// "whopays_default_payer": "self". + /// You can read more about these settings here:. + /// [Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291). /// - /// Object containing request parameters. - /// Returns the Models.ListPublicKeysResponse response from the API call. - public Models.ListPublicKeysResponse ListChargifyJsPublicKeys( - Models.ListChargifyJsPublicKeysInput input) - => CoreHelper.RunTask(ListChargifyJsPublicKeysAsync(input)); + /// Returns the Models.SiteResponse response from the API call. + public Models.SiteResponse ReadSite() + => CoreHelper.RunTask(ReadSiteAsync()); /// - /// This endpoint returns public keys used for Chargify.js. + /// This endpoint allows you to fetch some site data. + /// Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). + /// Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. + /// #### Relationship invoicing enabled. + /// If site has RI enabled then you will see more settings like:. + /// "customer_hierarchy_enabled": true,. + /// "whopays_enabled": true,. + /// "whopays_default_payer": "self". + /// You can read more about these settings here:. + /// [Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291). /// - /// Object containing request parameters. /// cancellationToken. - /// Returns the Models.ListPublicKeysResponse response from the API call. - public async Task ListChargifyJsPublicKeysAsync( - Models.ListChargifyJsPublicKeysInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() + /// Returns the Models.SiteResponse response from the API call. + public async Task ReadSiteAsync(CancellationToken cancellationToken = default) + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/chargify_js_keys.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)))) + .Setup(HttpMethod.Get, "/site.json") + .WithAuth("global")) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionComponentsController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionComponentsController.cs index 4c8fe35..b5e4b98 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionComponentsController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionComponentsController.cs @@ -35,81 +35,6 @@ public class SubscriptionComponentsController : BaseController /// internal SubscriptionComponentsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } - /// - /// This request will list information regarding a specific component owned by a subscription. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:`. - /// Returns the Models.SubscriptionComponentResponse response from the API call. - public Models.SubscriptionComponentResponse ReadSubscriptionComponent( - int subscriptionId, - int componentId) - => CoreHelper.RunTask(ReadSubscriptionComponentAsync(subscriptionId, componentId)); - - /// - /// This request will list information regarding a specific component owned by a subscription. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:`. - /// cancellationToken. - /// Returns the Models.SubscriptionComponentResponse response from the API call. - public async Task ReadSubscriptionComponentAsync( - int subscriptionId, - int componentId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/components/{component_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Template(_template => _template.Setup("component_id", componentId)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This request will list a subscription's applied components. - /// ## Archived Components. - /// When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. - /// - /// Object containing request parameters. - /// Returns the List of Models.SubscriptionComponentResponse response from the API call. - public List ListSubscriptionComponents( - Models.ListSubscriptionComponentsInput input) - => CoreHelper.RunTask(ListSubscriptionComponentsAsync(input)); - - /// - /// This request will list a subscription's applied components. - /// ## Archived Components. - /// When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the List of Models.SubscriptionComponentResponse response from the API call. - public async Task> ListSubscriptionComponentsAsync( - Models.ListSubscriptionComponentsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/components.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", input.SubscriptionId)) - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("end_date", input.EndDate)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) - .Query(_query => _query.Setup("price_point_ids", (input.PricePointIds.HasValue) ? ApiHelper.JsonSerialize(input.PricePointIds.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("product_family_ids", input.ProductFamilyIds)) - .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("start_date", input.StartDate)) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)) - .Query(_query => _query.Setup("filter[currencies]", input.FilterCurrencies)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// Updates the price points on one or more of a subscription's components. /// The `price_point` key can take either a:. @@ -152,34 +77,6 @@ public Models.BulkComponentSPricePointAssignment UpdateSubscriptionComponentsPri .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ComponentPricePointErrorException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// Resets all of a subscription's components to use the current default. - /// **Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. - /// - /// Required parameter: The Chargify id of the subscription. - /// Returns the Models.SubscriptionResponse response from the API call. - public Models.SubscriptionResponse ResetSubscriptionComponentsPricePoints( - int subscriptionId) - => CoreHelper.RunTask(ResetSubscriptionComponentsPricePointsAsync(subscriptionId)); - - /// - /// Resets all of a subscription's components to use the current default. - /// **Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. - /// - /// Required parameter: The Chargify id of the subscription. - /// cancellationToken. - /// Returns the Models.SubscriptionResponse response from the API call. - public async Task ResetSubscriptionComponentsPricePointsAsync( - int subscriptionId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/price_points/reset.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This endpoint creates a new allocation, setting the current allocated quantity for the Component and recording a memo. /// **Notice**: Allocations can only be updated for Quantity, On/Off, and Prepaid Components. @@ -284,68 +181,119 @@ public Models.AllocationResponse AllocateComponent( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint returns the 50 most recent Allocations, ordered by most recent first. - /// ## On/Off Components. - /// When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. - /// ## Querying data via Chargify gem. - /// You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares). - /// ```# First way. - /// component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}). - /// puts component.allocated_quantity. - /// # => 23. - /// # Second way. - /// component = Chargify::Subscription.find(7).component(1). - /// puts component.allocated_quantity. - /// # => 23. - /// ```. + /// When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. + /// In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. + /// ## Limitations. + /// A few limitations exist when changing an allocation's expiration date:. + /// - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. + /// - An expiration date can be changed towards the future with no limitations. + /// - An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. /// /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the component. - /// Optional parameter: Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. Use in query `page=1`.. - /// Returns the List of Models.AllocationResponse response from the API call. - public List ListAllocations( + /// Required parameter: The Chargify id of the allocation. + /// Optional parameter: Example: . + public void UpdatePrepaidUsageAllocation( int subscriptionId, int componentId, - int? page = 1) - => CoreHelper.RunTask(ListAllocationsAsync(subscriptionId, componentId, page)); + int allocationId, + Models.UpdateAllocationExpirationDate body = null) + => CoreHelper.RunVoidTask(UpdatePrepaidUsageAllocationAsync(subscriptionId, componentId, allocationId, body)); /// - /// This endpoint returns the 50 most recent Allocations, ordered by most recent first. - /// ## On/Off Components. - /// When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. - /// ## Querying data via Chargify gem. - /// You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares). - /// ```# First way. - /// component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}). - /// puts component.allocated_quantity. - /// # => 23. - /// # Second way. - /// component = Chargify::Subscription.find(7).component(1). - /// puts component.allocated_quantity. - /// # => 23. - /// ```. + /// When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. + /// In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. + /// ## Limitations. + /// A few limitations exist when changing an allocation's expiration date:. + /// - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. + /// - An expiration date can be changed towards the future with no limitations. + /// - An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. /// /// Required parameter: The Chargify id of the subscription. /// Required parameter: The Chargify id of the component. - /// Optional parameter: Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. Use in query `page=1`.. + /// Required parameter: The Chargify id of the allocation. + /// Optional parameter: Example: . /// cancellationToken. - /// Returns the List of Models.AllocationResponse response from the API call. - public async Task> ListAllocationsAsync( + /// Returns the void response from the API call. + public async Task UpdatePrepaidUsageAllocationAsync( int subscriptionId, int componentId, - int? page = 1, + int allocationId, + Models.UpdateAllocationExpirationDate body = null, CancellationToken cancellationToken = default) - => await CreateApiCall>() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/components/{component_id}/allocations.json") + .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}/components/{component_id}/allocations/{allocation_id}.json") .WithAuth("global") .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("subscription_id", subscriptionId)) .Template(_template => _template.Setup("component_id", componentId)) - .Query(_query => _query.Setup("page", (page != null) ? page : 1)))) + .Template(_template => _template.Setup("allocation_id", allocationId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionComponentAllocationErrorException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// ## Documentation. + /// Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. + /// These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. + /// This API allows you to stream events into the Chargify data ingestion engine. + /// Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). + /// ## Record Event. + /// Use this endpoint to record a single event. + /// *Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:*. + /// ```. + /// https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle. + /// ```. + /// + /// Required parameter: Your site's subdomain. + /// Required parameter: Identifies the Stream for which the event should be published.. + /// Optional parameter: If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store.. + /// Optional parameter: Example: . + public void RecordEvent( + string subdomain, + string apiHandle, + string storeUid = null, + Models.EBBEvent body = null) + => CoreHelper.RunVoidTask(RecordEventAsync(subdomain, apiHandle, storeUid, body)); + + /// + /// ## Documentation. + /// Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. + /// These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. + /// This API allows you to stream events into the Chargify data ingestion engine. + /// Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). + /// ## Record Event. + /// Use this endpoint to record a single event. + /// *Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:*. + /// ```. + /// https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle. + /// ```. + /// + /// Required parameter: Your site's subdomain. + /// Required parameter: Identifies the Stream for which the event should be published.. + /// Optional parameter: If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store.. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the void response from the API call. + public async Task RecordEventAsync( + string subdomain, + string apiHandle, + string storeUid = null, + Models.EBBEvent body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/{subdomain}/events/{api_handle}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subdomain", subdomain).Required()) + .Template(_template => _template.Setup("api_handle", apiHandle).Required()) + .Header(_header => _header.Setup("Content-Type", "application/json")) + .Query(_query => _query.Setup("store_uid", storeUid)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -428,58 +376,356 @@ public Models.AllocationPreviewResponse PreviewAllocations( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. - /// In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. - /// ## Limitations. - /// A few limitations exist when changing an allocation's expiration date:. - /// - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. - /// - An expiration date can be changed towards the future with no limitations. - /// - An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the component. - /// Required parameter: The Chargify id of the allocation. - /// Optional parameter: Example: . - public void UpdatePrepaidUsageAllocation( - int subscriptionId, - int componentId, - int allocationId, - Models.UpdateAllocationExpirationDate body = null) - => CoreHelper.RunVoidTask(UpdatePrepaidUsageAllocationAsync(subscriptionId, componentId, allocationId, body)); + /// ## Documentation. + /// Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources:. + /// + [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage). + /// + [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status). + /// You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. + /// ## Create Usage for Subscription. + /// This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. + /// ## Price Point ID usage. + /// If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. + /// You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. + /// If an invalid `price_point_id` is submitted, the endpoint will return an error. + /// ## Deducting Usage. + /// In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. + /// Example:. + /// Previously recorded:. + /// ```json. + /// {. + /// "usage": {. + /// "quantity": 5000,. + /// "memo": "Recording 5000 units". + /// }. + /// }. + /// ```. + /// At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload:. + /// ```json. + /// {. + /// "usage": {. + /// "quantity": -5000,. + /// "memo": "Deducting 5000 units". + /// }. + /// }. + /// ```. + /// The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. + /// ## FAQ. + /// Q. Is it possible to record metered usage for more than one component at a time?. + /// A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: Either the Chargify id for the component or the component's handle prefixed by `handle:`. + /// Optional parameter: Example: . + /// Returns the Models.UsageResponse response from the API call. + public Models.UsageResponse CreateUsage( + int subscriptionId, + CreateUsageComponentId componentId, + Models.CreateUsageRequest body = null) + => CoreHelper.RunTask(CreateUsageAsync(subscriptionId, componentId, body)); /// - /// When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. - /// In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. - /// ## Limitations. - /// A few limitations exist when changing an allocation's expiration date:. - /// - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. - /// - An expiration date can be changed towards the future with no limitations. - /// - An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. + /// ## Documentation. + /// Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources:. + /// + [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage). + /// + [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status). + /// You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. + /// ## Create Usage for Subscription. + /// This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. + /// ## Price Point ID usage. + /// If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. + /// You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. + /// If an invalid `price_point_id` is submitted, the endpoint will return an error. + /// ## Deducting Usage. + /// In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. + /// Example:. + /// Previously recorded:. + /// ```json. + /// {. + /// "usage": {. + /// "quantity": 5000,. + /// "memo": "Recording 5000 units". + /// }. + /// }. + /// ```. + /// At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload:. + /// ```json. + /// {. + /// "usage": {. + /// "quantity": -5000,. + /// "memo": "Deducting 5000 units". + /// }. + /// }. + /// ```. + /// The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. + /// ## FAQ. + /// Q. Is it possible to record metered usage for more than one component at a time?. + /// A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. /// /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the component. - /// Required parameter: The Chargify id of the allocation. + /// Required parameter: Either the Chargify id for the component or the component's handle prefixed by `handle:`. /// Optional parameter: Example: . /// cancellationToken. + /// Returns the Models.UsageResponse response from the API call. + public async Task CreateUsageAsync( + int subscriptionId, + CreateUsageComponentId componentId, + Models.CreateUsageRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/components/{component_id}/usages.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("component_id", componentId).Required()) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will list information regarding a specific component owned by a subscription. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:`. + /// Returns the Models.SubscriptionComponentResponse response from the API call. + public Models.SubscriptionComponentResponse ReadSubscriptionComponent( + int subscriptionId, + int componentId) + => CoreHelper.RunTask(ReadSubscriptionComponentAsync(subscriptionId, componentId)); + + /// + /// This request will list information regarding a specific component owned by a subscription. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:`. + /// cancellationToken. + /// Returns the Models.SubscriptionComponentResponse response from the API call. + public async Task ReadSubscriptionComponentAsync( + int subscriptionId, + int componentId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/components/{component_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("component_id", componentId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will list a subscription's applied components. + /// ## Archived Components. + /// When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. + /// + /// Object containing request parameters. + /// Returns the List of Models.SubscriptionComponentResponse response from the API call. + public List ListSubscriptionComponents( + Models.ListSubscriptionComponentsInput input) + => CoreHelper.RunTask(ListSubscriptionComponentsAsync(input)); + + /// + /// This request will list a subscription's applied components. + /// ## Archived Components. + /// When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the List of Models.SubscriptionComponentResponse response from the API call. + public async Task> ListSubscriptionComponentsAsync( + Models.ListSubscriptionComponentsInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", input.SubscriptionId)) + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("end_date", input.EndDate)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) + .Query(_query => _query.Setup("price_point_ids", (input.PricePointIds.HasValue) ? ApiHelper.JsonSerialize(input.PricePointIds.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("product_family_ids", input.ProductFamilyIds)) + .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("start_date", input.StartDate)) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) + .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)) + .Query(_query => _query.Setup("filter[currencies]", input.FilterCurrencies)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the component. + public void DeactivateEventBasedComponent( + int subscriptionId, + int componentId) + => CoreHelper.RunVoidTask(DeactivateEventBasedComponentAsync(subscriptionId, componentId)); + + /// + /// Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the component. + /// cancellationToken. /// Returns the void response from the API call. - public async Task UpdatePrepaidUsageAllocationAsync( + public async Task DeactivateEventBasedComponentAsync( int subscriptionId, int componentId, - int allocationId, - Models.UpdateAllocationExpirationDate body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}/components/{component_id}/allocations/{allocation_id}.json") + .Setup(HttpMethod.Post, "/event_based_billing/subscriptions/{subscription_id}/components/{component_id}/deactivate.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("component_id", componentId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This request will list components applied to each subscription. + /// + /// Object containing request parameters. + /// Returns the Models.ListSubscriptionComponentsResponse response from the API call. + public Models.ListSubscriptionComponentsResponse ListSubscriptionComponentsForSite( + Models.ListSubscriptionComponentsForSiteInput input) + => CoreHelper.RunTask(ListSubscriptionComponentsForSiteAsync(input)); + + /// + /// This request will list components applied to each subscription. + /// + /// Object containing request parameters. + /// cancellationToken. + /// Returns the Models.ListSubscriptionComponentsResponse response from the API call. + public async Task ListSubscriptionComponentsForSiteAsync( + Models.ListSubscriptionComponentsForSiteInput input, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions_components.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("start_date", input.StartDate)) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) + .Query(_query => _query.Setup("end_date", input.EndDate)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) + .Query(_query => _query.Setup("subscription_ids", input.SubscriptionIds)) + .Query(_query => _query.Setup("price_point_ids", (input.PricePointIds.HasValue) ? ApiHelper.JsonSerialize(input.PricePointIds.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("product_family_ids", input.ProductFamilyIds)) + .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)) + .Query(_query => _query.Setup("filter[currencies]", input.FilterCurrencies)) + .Query(_query => _query.Setup("filter[subscription][states]", input.FilterSubscriptionStates?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())) + .Query(_query => _query.Setup("filter[subscription][date_field]", (input.FilterSubscriptionDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterSubscriptionDateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("filter[subscription][start_date]", input.FilterSubscriptionStartDate)) + .Query(_query => _query.Setup("filter[subscription][start_datetime]", input.FilterSubscriptionStartDatetime)) + .Query(_query => _query.Setup("filter[subscription][end_date]", input.FilterSubscriptionEndDate)) + .Query(_query => _query.Setup("filter[subscription][end_datetime]", input.FilterSubscriptionEndDatetime)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Resets all of a subscription's components to use the current default. + /// **Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. + /// + /// Required parameter: The Chargify id of the subscription. + /// Returns the Models.SubscriptionResponse response from the API call. + public Models.SubscriptionResponse ResetSubscriptionComponentsPricePoints( + int subscriptionId) + => CoreHelper.RunTask(ResetSubscriptionComponentsPricePointsAsync(subscriptionId)); + + /// + /// Resets all of a subscription's components to use the current default. + /// **Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. + /// + /// Required parameter: The Chargify id of the subscription. + /// cancellationToken. + /// Returns the Models.SubscriptionResponse response from the API call. + public async Task ResetSubscriptionComponentsPricePointsAsync( + int subscriptionId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/price_points/reset.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This endpoint returns the 50 most recent Allocations, ordered by most recent first. + /// ## On/Off Components. + /// When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. + /// ## Querying data via Chargify gem. + /// You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares). + /// ```# First way. + /// component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}). + /// puts component.allocated_quantity. + /// # => 23. + /// # Second way. + /// component = Chargify::Subscription.find(7).component(1). + /// puts component.allocated_quantity. + /// # => 23. + /// ```. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the component. + /// Optional parameter: Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. Use in query `page=1`.. + /// Returns the List of Models.AllocationResponse response from the API call. + public List ListAllocations( + int subscriptionId, + int componentId, + int? page = 1) + => CoreHelper.RunTask(ListAllocationsAsync(subscriptionId, componentId, page)); + + /// + /// This endpoint returns the 50 most recent Allocations, ordered by most recent first. + /// ## On/Off Components. + /// When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. + /// ## Querying data via Chargify gem. + /// You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares). + /// ```# First way. + /// component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}). + /// puts component.allocated_quantity. + /// # => 23. + /// # Second way. + /// component = Chargify::Subscription.find(7).component(1). + /// puts component.allocated_quantity. + /// # => 23. + /// ```. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the component. + /// Optional parameter: Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. Use in query `page=1`.. + /// cancellationToken. + /// Returns the List of Models.AllocationResponse response from the API call. + public async Task> ListAllocationsAsync( + int subscriptionId, + int componentId, + int? page = 1, + CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/components/{component_id}/allocations.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) .Template(_template => _template.Setup("subscription_id", subscriptionId)) .Template(_template => _template.Setup("component_id", componentId)) - .Template(_template => _template.Setup("allocation_id", allocationId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Query(_query => _query.Setup("page", (page != null) ? page : 1)))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionComponentAllocationErrorException(_reason, _context), true))) + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -535,115 +781,6 @@ public async Task DeletePrepaidUsageAllocationAsync( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionComponentAllocationErrorException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// ## Documentation. - /// Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources:. - /// + [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage). - /// + [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status). - /// You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. - /// ## Create Usage for Subscription. - /// This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. - /// ## Price Point ID usage. - /// If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. - /// You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. - /// If an invalid `price_point_id` is submitted, the endpoint will return an error. - /// ## Deducting Usage. - /// In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. - /// Example:. - /// Previously recorded:. - /// ```json. - /// {. - /// "usage": {. - /// "quantity": 5000,. - /// "memo": "Recording 5000 units". - /// }. - /// }. - /// ```. - /// At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload:. - /// ```json. - /// {. - /// "usage": {. - /// "quantity": -5000,. - /// "memo": "Deducting 5000 units". - /// }. - /// }. - /// ```. - /// The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. - /// ## FAQ. - /// Q. Is it possible to record metered usage for more than one component at a time?. - /// A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: Either the Chargify id for the component or the component's handle prefixed by `handle:`. - /// Optional parameter: Example: . - /// Returns the Models.UsageResponse response from the API call. - public Models.UsageResponse CreateUsage( - int subscriptionId, - CreateUsageComponentId componentId, - Models.CreateUsageRequest body = null) - => CoreHelper.RunTask(CreateUsageAsync(subscriptionId, componentId, body)); - - /// - /// ## Documentation. - /// Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources:. - /// + [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage). - /// + [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status). - /// You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. - /// ## Create Usage for Subscription. - /// This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. - /// ## Price Point ID usage. - /// If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. - /// You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. - /// If an invalid `price_point_id` is submitted, the endpoint will return an error. - /// ## Deducting Usage. - /// In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. - /// Example:. - /// Previously recorded:. - /// ```json. - /// {. - /// "usage": {. - /// "quantity": 5000,. - /// "memo": "Recording 5000 units". - /// }. - /// }. - /// ```. - /// At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload:. - /// ```json. - /// {. - /// "usage": {. - /// "quantity": -5000,. - /// "memo": "Deducting 5000 units". - /// }. - /// }. - /// ```. - /// The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. - /// ## FAQ. - /// Q. Is it possible to record metered usage for more than one component at a time?. - /// A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: Either the Chargify id for the component or the component's handle prefixed by `handle:`. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.UsageResponse response from the API call. - public async Task CreateUsageAsync( - int subscriptionId, - CreateUsageComponentId componentId, - Models.CreateUsageRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/components/{component_id}/usages.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Template(_template => _template.Setup("component_id", componentId).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This request will return a list of the usages associated with a subscription for a particular metered component. This will display the previously recorded components for a subscription. /// This endpoint is not compatible with quantity-based components. @@ -729,97 +866,6 @@ public async Task ActivateEventBasedComponentAsync( .Template(_template => _template.Setup("component_id", componentId)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the component. - public void DeactivateEventBasedComponent( - int subscriptionId, - int componentId) - => CoreHelper.RunVoidTask(DeactivateEventBasedComponentAsync(subscriptionId, componentId)); - - /// - /// Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the component. - /// cancellationToken. - /// Returns the void response from the API call. - public async Task DeactivateEventBasedComponentAsync( - int subscriptionId, - int componentId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/event_based_billing/subscriptions/{subscription_id}/components/{component_id}/deactivate.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Template(_template => _template.Setup("component_id", componentId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// ## Documentation. - /// Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. - /// These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. - /// This API allows you to stream events into the Chargify data ingestion engine. - /// Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). - /// ## Record Event. - /// Use this endpoint to record a single event. - /// *Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:*. - /// ```. - /// https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle. - /// ```. - /// - /// Required parameter: Your site's subdomain. - /// Required parameter: Identifies the Stream for which the event should be published.. - /// Optional parameter: If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store.. - /// Optional parameter: Example: . - public void RecordEvent( - string subdomain, - string apiHandle, - string storeUid = null, - Models.EBBEvent body = null) - => CoreHelper.RunVoidTask(RecordEventAsync(subdomain, apiHandle, storeUid, body)); - - /// - /// ## Documentation. - /// Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. - /// These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. - /// This API allows you to stream events into the Chargify data ingestion engine. - /// Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). - /// ## Record Event. - /// Use this endpoint to record a single event. - /// *Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:*. - /// ```. - /// https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle. - /// ```. - /// - /// Required parameter: Your site's subdomain. - /// Required parameter: Identifies the Stream for which the event should be published.. - /// Optional parameter: If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store.. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the void response from the API call. - public async Task RecordEventAsync( - string subdomain, - string apiHandle, - string storeUid = null, - Models.EBBEvent body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/{subdomain}/events/{api_handle}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subdomain", subdomain).Required()) - .Template(_template => _template.Setup("api_handle", apiHandle).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")) - .Query(_query => _query.Setup("store_uid", storeUid)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// Use this endpoint to record a collection of events. /// *Note: this endpoint differs from the standard Chargify endpoints in that the subdomain will be `events` and your site subdomain will be included in the URL path.*. @@ -864,51 +910,5 @@ public async Task RecordEventsAsync( .Header(_header => _header.Setup("Content-Type", "application/json")) .Query(_query => _query.Setup("store_uid", storeUid)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This request will list components applied to each subscription. - /// - /// Object containing request parameters. - /// Returns the Models.ListSubscriptionComponentsResponse response from the API call. - public Models.ListSubscriptionComponentsResponse ListSubscriptionComponentsForSite( - Models.ListSubscriptionComponentsForSiteInput input) - => CoreHelper.RunTask(ListSubscriptionComponentsForSiteAsync(input)); - - /// - /// This request will list components applied to each subscription. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the Models.ListSubscriptionComponentsResponse response from the API call. - public async Task ListSubscriptionComponentsForSiteAsync( - Models.ListSubscriptionComponentsForSiteInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions_components.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("start_date", input.StartDate)) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime)) - .Query(_query => _query.Setup("end_date", input.EndDate)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime)) - .Query(_query => _query.Setup("subscription_ids", input.SubscriptionIds)) - .Query(_query => _query.Setup("price_point_ids", (input.PricePointIds.HasValue) ? ApiHelper.JsonSerialize(input.PricePointIds.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("product_family_ids", input.ProductFamilyIds)) - .Query(_query => _query.Setup("include", (input.Include.HasValue) ? ApiHelper.JsonSerialize(input.Include.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[use_site_exchange_rate]", input.FilterUseSiteExchangeRate)) - .Query(_query => _query.Setup("filter[currencies]", input.FilterCurrencies)) - .Query(_query => _query.Setup("filter[subscription][states]", input.FilterSubscriptionStates?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())) - .Query(_query => _query.Setup("filter[subscription][date_field]", (input.FilterSubscriptionDateField.HasValue) ? ApiHelper.JsonSerialize(input.FilterSubscriptionDateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("filter[subscription][start_date]", input.FilterSubscriptionStartDate)) - .Query(_query => _query.Setup("filter[subscription][start_datetime]", input.FilterSubscriptionStartDatetime)) - .Query(_query => _query.Setup("filter[subscription][end_date]", input.FilterSubscriptionEndDate)) - .Query(_query => _query.Setup("filter[subscription][end_datetime]", input.FilterSubscriptionEndDatetime)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionGroupInvoiceAccountController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionGroupInvoiceAccountController.cs index e43cc38..db43389 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionGroupInvoiceAccountController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionGroupInvoiceAccountController.cs @@ -34,40 +34,6 @@ public class SubscriptionGroupInvoiceAccountController : BaseController /// internal SubscriptionGroupInvoiceAccountController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } - /// - /// A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. - /// - /// Required parameter: The uid of the subscription group. - /// Optional parameter: Example: . - /// Returns the Models.SubscriptionGroupPrepaymentResponse response from the API call. - public Models.SubscriptionGroupPrepaymentResponse CreateSubscriptionGroupPrepayment( - string uid, - Models.SubscriptionGroupPrepaymentRequest body = null) - => CoreHelper.RunTask(CreateSubscriptionGroupPrepaymentAsync(uid, body)); - - /// - /// A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. - /// - /// Required parameter: The uid of the subscription group. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.SubscriptionGroupPrepaymentResponse response from the API call. - public async Task CreateSubscriptionGroupPrepaymentAsync( - string uid, - Models.SubscriptionGroupPrepaymentRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscription_groups/{uid}/prepayments.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("uid", uid).Required()) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// This request will list a subscription group's prepayments. /// @@ -102,30 +68,30 @@ public Models.ListSubscriptionGroupPrepaymentResponse ListPrepaymentsForSubscrip .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. + /// A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. /// /// Required parameter: The uid of the subscription group. /// Optional parameter: Example: . - /// Returns the Models.ServiceCreditResponse response from the API call. - public Models.ServiceCreditResponse IssueSubscriptionGroupServiceCredits( + /// Returns the Models.SubscriptionGroupPrepaymentResponse response from the API call. + public Models.SubscriptionGroupPrepaymentResponse CreateSubscriptionGroupPrepayment( string uid, - Models.IssueServiceCreditRequest body = null) - => CoreHelper.RunTask(IssueSubscriptionGroupServiceCreditsAsync(uid, body)); + Models.SubscriptionGroupPrepaymentRequest body = null) + => CoreHelper.RunTask(CreateSubscriptionGroupPrepaymentAsync(uid, body)); /// - /// Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. + /// A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. /// /// Required parameter: The uid of the subscription group. /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.ServiceCreditResponse response from the API call. - public async Task IssueSubscriptionGroupServiceCreditsAsync( + /// Returns the Models.SubscriptionGroupPrepaymentResponse response from the API call. + public async Task CreateSubscriptionGroupPrepaymentAsync( string uid, - Models.IssueServiceCreditRequest body = null, + Models.SubscriptionGroupPrepaymentRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscription_groups/{uid}/service_credits.json") + .Setup(HttpMethod.Post, "/subscription_groups/{uid}/prepayments.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) @@ -168,5 +134,39 @@ public Models.ServiceCredit DeductSubscriptionGroupServiceCredits( .ResponseHandler(_responseHandler => _responseHandler .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. + /// + /// Required parameter: The uid of the subscription group. + /// Optional parameter: Example: . + /// Returns the Models.ServiceCreditResponse response from the API call. + public Models.ServiceCreditResponse IssueSubscriptionGroupServiceCredits( + string uid, + Models.IssueServiceCreditRequest body = null) + => CoreHelper.RunTask(IssueSubscriptionGroupServiceCreditsAsync(uid, body)); + + /// + /// Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. + /// + /// Required parameter: The uid of the subscription group. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ServiceCreditResponse response from the API call. + public async Task IssueSubscriptionGroupServiceCreditsAsync( + string uid, + Models.IssueServiceCreditRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscription_groups/{uid}/service_credits.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("uid", uid).Required()) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionGroupStatusController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionGroupStatusController.cs index f1ad892..81a591f 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionGroupStatusController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionGroupStatusController.cs @@ -70,27 +70,25 @@ public async Task CancelSubscriptionsInGroupAsync( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. - /// All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. + /// Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. /// /// Required parameter: The uid of the subscription group. - public void InitiateDelayedCancellationForGroup( + public void StopDelayedCancellationForGroup( string uid) - => CoreHelper.RunVoidTask(InitiateDelayedCancellationForGroupAsync(uid)); + => CoreHelper.RunVoidTask(StopDelayedCancellationForGroupAsync(uid)); /// - /// This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. - /// All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. + /// Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. /// /// Required parameter: The uid of the subscription group. /// cancellationToken. /// Returns the void response from the API call. - public async Task InitiateDelayedCancellationForGroupAsync( + public async Task StopDelayedCancellationForGroupAsync( string uid, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscription_groups/{uid}/delayed_cancel.json") + .Setup(HttpMethod.Delete, "/subscription_groups/{uid}/delayed_cancel.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("uid", uid).Required()))) @@ -99,25 +97,27 @@ public async Task InitiateDelayedCancellationForGroupAsync( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. + /// This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. + /// All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. /// /// Required parameter: The uid of the subscription group. - public void StopDelayedCancellationForGroup( + public void InitiateDelayedCancellationForGroup( string uid) - => CoreHelper.RunVoidTask(StopDelayedCancellationForGroupAsync(uid)); + => CoreHelper.RunVoidTask(InitiateDelayedCancellationForGroupAsync(uid)); /// - /// Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. + /// This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. + /// All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. /// /// Required parameter: The uid of the subscription group. /// cancellationToken. /// Returns the void response from the API call. - public async Task StopDelayedCancellationForGroupAsync( + public async Task InitiateDelayedCancellationForGroupAsync( string uid, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscription_groups/{uid}/delayed_cancel.json") + .Setup(HttpMethod.Post, "/subscription_groups/{uid}/delayed_cancel.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("uid", uid).Required()))) diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionGroupsController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionGroupsController.cs index 8a032da..5873f67 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionGroupsController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionGroupsController.cs @@ -72,32 +72,33 @@ public Models.SubscriptionGroupSignupResponse SignupWithSubscriptionGroup( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Creates a subscription group with given members. + /// Use this endpoint to find subscription group associated with subscription. + /// If the subscription is not in a group endpoint will return 404 code. /// - /// Optional parameter: Example: . - /// Returns the Models.SubscriptionGroupResponse response from the API call. - public Models.SubscriptionGroupResponse CreateSubscriptionGroup( - Models.CreateSubscriptionGroupRequest body = null) - => CoreHelper.RunTask(CreateSubscriptionGroupAsync(body)); + /// Required parameter: The Chargify id of the subscription associated with the subscription group. + /// Returns the Models.FullSubscriptionGroupResponse response from the API call. + public Models.FullSubscriptionGroupResponse ReadSubscriptionGroupBySubscriptionId( + string subscriptionId) + => CoreHelper.RunTask(ReadSubscriptionGroupBySubscriptionIdAsync(subscriptionId)); /// - /// Creates a subscription group with given members. + /// Use this endpoint to find subscription group associated with subscription. + /// If the subscription is not in a group endpoint will return 404 code. /// - /// Optional parameter: Example: . + /// Required parameter: The Chargify id of the subscription associated with the subscription group. /// cancellationToken. - /// Returns the Models.SubscriptionGroupResponse response from the API call. - public async Task CreateSubscriptionGroupAsync( - Models.CreateSubscriptionGroupRequest body = null, + /// Returns the Models.FullSubscriptionGroupResponse response from the API call. + public async Task ReadSubscriptionGroupBySubscriptionIdAsync( + string subscriptionId, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscription_groups.json") + .Setup(HttpMethod.Get, "/subscription_groups/lookup.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) + .Query(_query => _query.Setup("subscription_id", subscriptionId).Required()))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleStringErrorResponseException(_reason, _context), true))) + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -133,177 +134,176 @@ public Models.ListSubscriptionGroupsResponse ListSubscriptionGroups( .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to find subscription group details. - /// #### Current Billing Amount in Cents. - /// Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. + /// Use this endpoint to delete subscription group. + /// Only groups without members can be deleted. /// /// Required parameter: The uid of the subscription group. - /// Returns the Models.FullSubscriptionGroupResponse response from the API call. - public Models.FullSubscriptionGroupResponse ReadSubscriptionGroup( + /// Returns the Models.DeleteSubscriptionGroupResponse response from the API call. + public Models.DeleteSubscriptionGroupResponse DeleteSubscriptionGroup( string uid) - => CoreHelper.RunTask(ReadSubscriptionGroupAsync(uid)); + => CoreHelper.RunTask(DeleteSubscriptionGroupAsync(uid)); /// - /// Use this endpoint to find subscription group details. - /// #### Current Billing Amount in Cents. - /// Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. + /// Use this endpoint to delete subscription group. + /// Only groups without members can be deleted. /// /// Required parameter: The uid of the subscription group. /// cancellationToken. - /// Returns the Models.FullSubscriptionGroupResponse response from the API call. - public async Task ReadSubscriptionGroupAsync( + /// Returns the Models.DeleteSubscriptionGroupResponse response from the API call. + public async Task DeleteSubscriptionGroupAsync( string uid, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscription_groups/{uid}.json") + .Setup(HttpMethod.Delete, "/subscription_groups/{uid}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Template(_template => _template.Setup("uid", uid).Required()))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to update subscription group members. - /// `"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. + /// For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. + /// Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. + /// **Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. + /// Rather than specifying a customer, the `target` parameter could instead simply have a value of. + /// * `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer,. + /// * `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or. + /// * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. + /// To create a new subscription into a subscription group, please reference the following:. + /// [Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group). /// - /// Required parameter: The uid of the subscription group. + /// Required parameter: The Chargify id of the subscription. /// Optional parameter: Example: . /// Returns the Models.SubscriptionGroupResponse response from the API call. - public Models.SubscriptionGroupResponse UpdateSubscriptionGroupMembers( - string uid, - Models.UpdateSubscriptionGroupRequest body = null) - => CoreHelper.RunTask(UpdateSubscriptionGroupMembersAsync(uid, body)); + public Models.SubscriptionGroupResponse CreateSubscriptionGroupHierarchy( + int subscriptionId, + Models.AddSubscriptionToAGroup body = null) + => CoreHelper.RunTask(CreateSubscriptionGroupHierarchyAsync(subscriptionId, body)); /// - /// Use this endpoint to update subscription group members. - /// `"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. + /// For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. + /// Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. + /// **Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. + /// Rather than specifying a customer, the `target` parameter could instead simply have a value of. + /// * `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer,. + /// * `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or. + /// * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. + /// To create a new subscription into a subscription group, please reference the following:. + /// [Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group). /// - /// Required parameter: The uid of the subscription group. + /// Required parameter: The Chargify id of the subscription. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.SubscriptionGroupResponse response from the API call. - public async Task UpdateSubscriptionGroupMembersAsync( - string uid, - Models.UpdateSubscriptionGroupRequest body = null, + public async Task CreateSubscriptionGroupHierarchyAsync( + int subscriptionId, + Models.AddSubscriptionToAGroup body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/subscription_groups/{uid}.json") + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/group.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("uid", uid).Required()) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionGroupUpdateErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to delete subscription group. - /// Only groups without members can be deleted. + /// Creates a subscription group with given members. /// - /// Required parameter: The uid of the subscription group. - /// Returns the Models.DeleteSubscriptionGroupResponse response from the API call. - public Models.DeleteSubscriptionGroupResponse DeleteSubscriptionGroup( - string uid) - => CoreHelper.RunTask(DeleteSubscriptionGroupAsync(uid)); + /// Optional parameter: Example: . + /// Returns the Models.SubscriptionGroupResponse response from the API call. + public Models.SubscriptionGroupResponse CreateSubscriptionGroup( + Models.CreateSubscriptionGroupRequest body = null) + => CoreHelper.RunTask(CreateSubscriptionGroupAsync(body)); /// - /// Use this endpoint to delete subscription group. - /// Only groups without members can be deleted. + /// Creates a subscription group with given members. /// - /// Required parameter: The uid of the subscription group. + /// Optional parameter: Example: . /// cancellationToken. - /// Returns the Models.DeleteSubscriptionGroupResponse response from the API call. - public async Task DeleteSubscriptionGroupAsync( - string uid, + /// Returns the Models.SubscriptionGroupResponse response from the API call. + public async Task CreateSubscriptionGroupAsync( + Models.CreateSubscriptionGroupRequest body = null, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscription_groups/{uid}.json") + .Setup(HttpMethod.Post, "/subscription_groups.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("uid", uid).Required()))) + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleStringErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to find subscription group associated with subscription. - /// If the subscription is not in a group endpoint will return 404 code. + /// Use this endpoint to find subscription group details. + /// #### Current Billing Amount in Cents. + /// Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. /// - /// Required parameter: The Chargify id of the subscription associated with the subscription group. + /// Required parameter: The uid of the subscription group. /// Returns the Models.FullSubscriptionGroupResponse response from the API call. - public Models.FullSubscriptionGroupResponse ReadSubscriptionGroupBySubscriptionId( - string subscriptionId) - => CoreHelper.RunTask(ReadSubscriptionGroupBySubscriptionIdAsync(subscriptionId)); + public Models.FullSubscriptionGroupResponse ReadSubscriptionGroup( + string uid) + => CoreHelper.RunTask(ReadSubscriptionGroupAsync(uid)); /// - /// Use this endpoint to find subscription group associated with subscription. - /// If the subscription is not in a group endpoint will return 404 code. + /// Use this endpoint to find subscription group details. + /// #### Current Billing Amount in Cents. + /// Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. /// - /// Required parameter: The Chargify id of the subscription associated with the subscription group. + /// Required parameter: The uid of the subscription group. /// cancellationToken. /// Returns the Models.FullSubscriptionGroupResponse response from the API call. - public async Task ReadSubscriptionGroupBySubscriptionIdAsync( - string subscriptionId, + public async Task ReadSubscriptionGroupAsync( + string uid, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscription_groups/lookup.json") + .Setup(HttpMethod.Get, "/subscription_groups/{uid}.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("subscription_id", subscriptionId).Required()))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .Template(_template => _template.Setup("uid", uid).Required()))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. - /// Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. - /// **Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. - /// Rather than specifying a customer, the `target` parameter could instead simply have a value of. - /// * `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer,. - /// * `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or. - /// * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. - /// To create a new subscription into a subscription group, please reference the following:. - /// [Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group). + /// Use this endpoint to update subscription group members. + /// `"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. /// - /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The uid of the subscription group. /// Optional parameter: Example: . /// Returns the Models.SubscriptionGroupResponse response from the API call. - public Models.SubscriptionGroupResponse CreateSubscriptionGroupHierarchy( - int subscriptionId, - Models.AddSubscriptionToAGroup body = null) - => CoreHelper.RunTask(CreateSubscriptionGroupHierarchyAsync(subscriptionId, body)); + public Models.SubscriptionGroupResponse UpdateSubscriptionGroupMembers( + string uid, + Models.UpdateSubscriptionGroupRequest body = null) + => CoreHelper.RunTask(UpdateSubscriptionGroupMembersAsync(uid, body)); /// - /// For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. - /// Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. - /// **Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. - /// Rather than specifying a customer, the `target` parameter could instead simply have a value of. - /// * `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer,. - /// * `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or. - /// * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. - /// To create a new subscription into a subscription group, please reference the following:. - /// [Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group). + /// Use this endpoint to update subscription group members. + /// `"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. /// - /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The uid of the subscription group. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.SubscriptionGroupResponse response from the API call. - public async Task CreateSubscriptionGroupHierarchyAsync( - int subscriptionId, - Models.AddSubscriptionToAGroup body = null, + public async Task UpdateSubscriptionGroupMembersAsync( + string uid, + Models.UpdateSubscriptionGroupRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/group.json") + .Setup(HttpMethod.Put, "/subscription_groups/{uid}.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("uid", uid).Required()) .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionGroupUpdateErrorResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionInvoiceAccountController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionInvoiceAccountController.cs index 8af220e..7087001 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionInvoiceAccountController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionInvoiceAccountController.cs @@ -34,32 +34,6 @@ public class SubscriptionInvoiceAccountController : BaseController /// internal SubscriptionInvoiceAccountController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } - /// - /// Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. - /// - /// Required parameter: The Chargify id of the subscription. - /// Returns the Models.AccountBalances response from the API call. - public Models.AccountBalances ReadAccountBalances( - int subscriptionId) - => CoreHelper.RunTask(ReadAccountBalancesAsync(subscriptionId)); - - /// - /// Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. - /// - /// Required parameter: The Chargify id of the subscription. - /// cancellationToken. - /// Returns the Models.AccountBalances response from the API call. - public async Task ReadAccountBalancesAsync( - int subscriptionId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/account_balances.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// ## Create Prepayment. /// In order to specify a prepayment made against a subscription, specify the `amount, memo, details, method`. @@ -98,6 +72,32 @@ public Models.CreatePrepaymentResponse CreatePrepayment( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. + /// + /// Required parameter: The Chargify id of the subscription. + /// Returns the Models.AccountBalances response from the API call. + public Models.AccountBalances ReadAccountBalances( + int subscriptionId) + => CoreHelper.RunTask(ReadAccountBalancesAsync(subscriptionId)); + + /// + /// Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. + /// + /// Required parameter: The Chargify id of the subscription. + /// cancellationToken. + /// Returns the Models.AccountBalances response from the API call. + public async Task ReadAccountBalancesAsync( + int subscriptionId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}/account_balances.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// This request will list a subscription's prepayments. /// diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionNotesController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionNotesController.cs index 75d73dd..9c930a2 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionNotesController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionNotesController.cs @@ -73,6 +73,36 @@ public Models.SubscriptionNoteResponse CreateSubscriptionNote( .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// Use the following method to delete a note for a Subscription. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the note. + public void DeleteSubscriptionNote( + int subscriptionId, + int noteId) + => CoreHelper.RunVoidTask(DeleteSubscriptionNoteAsync(subscriptionId, noteId)); + + /// + /// Use the following method to delete a note for a Subscription. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: The Chargify id of the note. + /// cancellationToken. + /// Returns the void response from the API call. + public async Task DeleteSubscriptionNoteAsync( + int subscriptionId, + int noteId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/notes/{note_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Template(_template => _template.Setup("note_id", noteId)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// Use this method to retrieve a list of Notes associated with a Subscription. The response will be an array of Notes. /// @@ -168,35 +198,5 @@ public Models.SubscriptionNoteResponse UpdateSubscriptionNote( .Template(_template => _template.Setup("note_id", noteId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use the following method to delete a note for a Subscription. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the note. - public void DeleteSubscriptionNote( - int subscriptionId, - int noteId) - => CoreHelper.RunVoidTask(DeleteSubscriptionNoteAsync(subscriptionId, noteId)); - - /// - /// Use the following method to delete a note for a Subscription. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: The Chargify id of the note. - /// cancellationToken. - /// Returns the void response from the API call. - public async Task DeleteSubscriptionNoteAsync( - int subscriptionId, - int noteId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/notes/{note_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Template(_template => _template.Setup("note_id", noteId)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionStatusController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionStatusController.cs index f6fc8ef..8210fa6 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionStatusController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionStatusController.cs @@ -34,42 +34,6 @@ public class SubscriptionStatusController : BaseController /// internal SubscriptionStatusController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } - /// - /// Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. - /// ## Successful Reactivation. - /// The response will be `200 OK` with the updated Subscription. - /// ## Failed Reactivation. - /// The response will be `422 "Unprocessable Entity`. - /// - /// Required parameter: The Chargify id of the subscription. - /// Returns the Models.SubscriptionResponse response from the API call. - public Models.SubscriptionResponse RetrySubscription( - int subscriptionId) - => CoreHelper.RunTask(RetrySubscriptionAsync(subscriptionId)); - - /// - /// Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. - /// ## Successful Reactivation. - /// The response will be `200 OK` with the updated Subscription. - /// ## Failed Reactivation. - /// The response will be `422 "Unprocessable Entity`. - /// - /// Required parameter: The Chargify id of the subscription. - /// cancellationToken. - /// Returns the Models.SubscriptionResponse response from the API call. - public async Task RetrySubscriptionAsync( - int subscriptionId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}/retry.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// The DELETE action causes the cancellation of the Subscription. This means, the method sets the Subscription state to "canceled". /// @@ -176,6 +140,110 @@ public Models.SubscriptionResponse PauseSubscription( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// + /// Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. + /// Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. + /// Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// Returns the Models.DelayedCancellationResponse response from the API call. + public Models.DelayedCancellationResponse InitiateDelayedCancellation( + int subscriptionId, + Models.CancellationRequest body = null) + => CoreHelper.RunTask(InitiateDelayedCancellationAsync(subscriptionId, body)); + + /// + /// Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. + /// Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. + /// Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.DelayedCancellationResponse response from the API call. + public async Task InitiateDelayedCancellationAsync( + int subscriptionId, + Models.CancellationRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/delayed_cancel.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. + /// This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. + /// + /// Required parameter: The Chargify id of the subscription. + /// Returns the Models.DelayedCancellationResponse response from the API call. + public Models.DelayedCancellationResponse StopDelayedCancellation( + int subscriptionId) + => CoreHelper.RunTask(StopDelayedCancellationAsync(subscriptionId)); + + /// + /// Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. + /// This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. + /// + /// Required parameter: The Chargify id of the subscription. + /// cancellationToken. + /// Returns the Models.DelayedCancellationResponse response from the API call. + public async Task StopDelayedCancellationAsync( + int subscriptionId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/delayed_cancel.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. + /// ## Successful Reactivation. + /// The response will be `200 OK` with the updated Subscription. + /// ## Failed Reactivation. + /// The response will be `422 "Unprocessable Entity`. + /// + /// Required parameter: The Chargify id of the subscription. + /// Returns the Models.SubscriptionResponse response from the API call. + public Models.SubscriptionResponse RetrySubscription( + int subscriptionId) + => CoreHelper.RunTask(RetrySubscriptionAsync(subscriptionId)); + + /// + /// Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. + /// ## Successful Reactivation. + /// The response will be `200 OK` with the updated Subscription. + /// ## Failed Reactivation. + /// The response will be `422 "Unprocessable Entity`. + /// + /// Required parameter: The Chargify id of the subscription. + /// cancellationToken. + /// Returns the Models.SubscriptionResponse response from the API call. + public async Task RetrySubscriptionAsync( + int subscriptionId, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}/retry.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + /// /// Once a subscription has been paused / put on hold, you can update the date which was specified to automatically resume the subscription. /// To update a subscription's resume date, use this method to change or update the `automatically_resume_at` date. @@ -444,74 +512,6 @@ public Models.SubscriptionResponse ReactivateSubscription( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. - /// Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. - /// Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// Returns the Models.DelayedCancellationResponse response from the API call. - public Models.DelayedCancellationResponse InitiateDelayedCancellation( - int subscriptionId, - Models.CancellationRequest body = null) - => CoreHelper.RunTask(InitiateDelayedCancellationAsync(subscriptionId, body)); - - /// - /// Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. - /// Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. - /// Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.DelayedCancellationResponse response from the API call. - public async Task InitiateDelayedCancellationAsync( - int subscriptionId, - Models.CancellationRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/delayed_cancel.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. - /// This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. - /// - /// Required parameter: The Chargify id of the subscription. - /// Returns the Models.DelayedCancellationResponse response from the API call. - public Models.DelayedCancellationResponse StopDelayedCancellation( - int subscriptionId) - => CoreHelper.RunTask(StopDelayedCancellationAsync(subscriptionId)); - - /// - /// Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. - /// This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. - /// - /// Required parameter: The Chargify id of the subscription. - /// cancellationToken. - /// Returns the Models.DelayedCancellationResponse response from the API call. - public async Task StopDelayedCancellationAsync( - int subscriptionId, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/delayed_cancel.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// If a subscription is currently in dunning, the subscription will be set to active and the active Dunner will be resolved. /// diff --git a/AdvancedBilling.Standard/Controllers/SubscriptionsController.cs b/AdvancedBilling.Standard/Controllers/SubscriptionsController.cs index 39e842c..76635d0 100644 --- a/AdvancedBilling.Standard/Controllers/SubscriptionsController.cs +++ b/AdvancedBilling.Standard/Controllers/SubscriptionsController.cs @@ -18,6 +18,7 @@ namespace AdvancedBilling.Standard.Controllers using AdvancedBilling.Standard.Http.Client; using AdvancedBilling.Standard.Utilities; using APIMatic.Core; + using APIMatic.Core.Http.Configuration; using APIMatic.Core.Types; using APIMatic.Core.Utilities; using APIMatic.Core.Utilities.Date.Xml; @@ -35,72 +36,433 @@ public class SubscriptionsController : BaseController internal SubscriptionsController(GlobalConfiguration globalConfiguration) : base(globalConfiguration) { } /// - /// Full documentation on how subscriptions operate within Chargify can be located under the following topics:. - /// + [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction). - /// + [Subscriptions Actions](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions). - /// + [Subscription Cancellation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions#initiate-cancellation). - /// + [Subscription Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021-Reactivating-and-Resuming). - /// + [Subscription Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821-Imports). - /// When creating a subscription, you must specify a product and a customer. Credit card details may be required, depending on the options for the Product being subscribed ([see Product Options](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221#payment-method-settings)). - /// The product may be specified by `product_id` or by `product_handle` (API Handle). In similar fashion, to pass a particular product price point, you may either use `product_price_point_handle` or `product_price_point_id`. - /// An existing customer may be specified by a `customer_id` (ID within Chargify) or a `customer_reference` (unique value within your app that you have shared with Chargify via the reference attribute on a customer). You may also pass in an existing payment profile for that customer with `payment_profile_id`. A new customer may be created by providing `customer_attributes`. - /// Credit card details may be required, depending on the options for the product being subscribed. The product can be specified by `product_id` or by `product_handle` (API Handle). - /// If you are creating a subscription with a payment profile, the attribute to send will be `credit_card_attributes` or `bank_account_attributes` for ACH and Direct Debit. That said, when you read the subscription after creation, we return the profile details under `credit_card` or `bank_account`. + /// Use this endpoint to find a subscription by its reference. + /// + /// Optional parameter: Subscription reference. + /// Returns the Models.SubscriptionResponse response from the API call. + public Models.SubscriptionResponse ReadSubscriptionByReference( + string reference = null) + => CoreHelper.RunTask(ReadSubscriptionByReferenceAsync(reference)); + + /// + /// Use this endpoint to find a subscription by its reference. + /// + /// Optional parameter: Subscription reference. + /// cancellationToken. + /// Returns the Models.SubscriptionResponse response from the API call. + public async Task ReadSubscriptionByReferenceAsync( + string reference = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions/lookup.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Query(_query => _query.Setup("reference", reference)))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons). + /// ## Query Parameters vs Request Body Parameters. + /// Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. + /// For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: A code for the coupon that would be applied to a subscription. + /// Optional parameter: Example: . + /// Returns the Models.SubscriptionResponse response from the API call. + public Models.SubscriptionResponse ApplyCouponToSubscription( + int subscriptionId, + string code = null, + Models.AddCouponsRequest body = null) + => CoreHelper.RunTask(ApplyCouponToSubscriptionAsync(subscriptionId, code, body)); + + /// + /// An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons). + /// ## Query Parameters vs Request Body Parameters. + /// Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. + /// For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: A code for the coupon that would be applied to a subscription. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.SubscriptionResponse response from the API call. + public async Task ApplyCouponToSubscriptionAsync( + int subscriptionId, + string code = null, + Models.AddCouponsRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/add_coupon.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")) + .Query(_query => _query.Setup("code", code)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionAddCouponErrorException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. + /// ## Update Subscription Payment Method. + /// Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. + /// Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. + /// You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. + /// ## Product Change. + /// This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. + /// To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. + /// ### Delayed Product Change. + /// This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. + /// This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. + /// You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle`. + /// **Note: To cancel a delayed product change, set `next_product_id` to an empty string.**. + /// ## Billing Date Changes. + /// ### Regular Billing Date Changes. + /// Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. + /// Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. + /// The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. + /// ### Snap Day Changes. + /// For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. + /// Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// Returns the Models.SubscriptionResponse response from the API call. + public Models.SubscriptionResponse UpdateSubscription( + int subscriptionId, + Models.UpdateSubscriptionRequest body = null) + => CoreHelper.RunTask(UpdateSubscriptionAsync(subscriptionId, body)); + + /// + /// The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. + /// ## Update Subscription Payment Method. + /// Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. + /// Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. + /// You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. + /// ## Product Change. + /// This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. + /// To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. + /// ### Delayed Product Change. + /// This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. + /// This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. + /// You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle`. + /// **Note: To cancel a delayed product change, set `next_product_id` to an empty string.**. + /// ## Billing Date Changes. + /// ### Regular Billing Date Changes. + /// Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. + /// Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. + /// The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. + /// ### Snap Day Changes. + /// For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. + /// Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.SubscriptionResponse response from the API call. + public async Task UpdateSubscriptionAsync( + int subscriptionId, + Models.UpdateSubscriptionRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// For sites in test mode, you may purge individual subscriptions. + /// Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer`. + /// If you need to remove subscriptions from a live site, please contact support to discuss your use case. + /// ### Delete customer and payment profile. + /// The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile`. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: id of the customer.. + /// Optional parameter: Options are "customer" or "payment_profile". Use in query: `cascade[]=customer&cascade[]=payment_profile`.. + public void PurgeSubscription( + int subscriptionId, + int ack, + List cascade = null) + => CoreHelper.RunVoidTask(PurgeSubscriptionAsync(subscriptionId, ack, cascade)); + + /// + /// For sites in test mode, you may purge individual subscriptions. + /// Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer`. + /// If you need to remove subscriptions from a live site, please contact support to discuss your use case. + /// ### Delete customer and payment profile. + /// The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile`. + /// + /// Required parameter: The Chargify id of the subscription. + /// Required parameter: id of the customer.. + /// Optional parameter: Options are "customer" or "payment_profile". Use in query: `cascade[]=customer&cascade[]=payment_profile`.. + /// cancellationToken. + /// Returns the void response from the API call. + public async Task PurgeSubscriptionAsync( + int subscriptionId, + int ack, + List cascade = null, + CancellationToken cancellationToken = default) + => await CreateApiCall(ArraySerialization.Plain) + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/purge.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Query(_query => _query.Setup("ack", ack)) + .Query(_query => _query.Setup("cascade[]", cascade?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. + /// The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). + /// ## Side effects. + /// A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. /// ## Taxable Subscriptions. - /// If your intent is to charge your subscribers tax via [Avalara Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405275711885-Avalara-VAT-Tax) or [Custom Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405069041549-Custom-Taxes), there are a few considerations to be made regarding collecting subscription data. - /// For subscribers to be eligible to be taxed, the following information for the `customer` object or `payment_profile` object must by supplied:. - /// + A subscription to a [taxable product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221-Product-Editing#tax-settings). - /// + [Full valid billing or shipping address](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#full-address-required-for-taxable-subscriptions) to identify the tax locale. - /// + The portion of the address that houses the [state information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-state-format-for-taxable-subscriptions) of either adddress must adhere to the ISO standard of a 2-3 character limit/format. - /// + The portion of the address that houses the [country information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-country-format-for-taxable-subscriptions) must adhere to the ISO standard of a 2 character limit/format. - /// ## Subscription Request Examples. - /// The subscription examples below will be split into two sections. - /// The first section, "Subscription Customization", will focus on passing different information with a subscription, such as components, calendar billing, and custom fields. These examples will presume you are using a secure `chargify_token` generated by Chargify.js. - /// The second section, "Passing Payment Information", will focus on passing payment information into Chargify. Please be aware that collecting and sending Chargify raw card details requires PCI compliance on your end; these examples are provided as guidance. If your business is not PCI compliant, we recommend using Chargify.js to collect credit cards or bank accounts. - /// # Subscription Customization. - /// ## With Components. - /// Different components require slightly different data. For example, quantity-based and on/off components accept `allocated_quantity`, while metered components accept `unit_balance`. - /// When creating a subscription with a component, a `price_point_id` can be passed in along with the `component_id` to specify which price point to use. If not passed in, the default price point will be used. - /// Note: if an invalid `price_point_id` is used, the subscription will still proceed but will use the component's default price point. - /// Components and their price points may be added by ID or by handle. See the example request body labeled "Components By Handle (Quantity-Based)"; the format will be the same for other component types. - /// ## With Coupon(s). - /// Pass an array of `coupon_codes`. See the example request body "With Coupon". - /// ## With Manual Invoice Collection. - /// The `invoice` collection method works only on legacy Statement Architecture. - /// On Relationship Invoicing Architecture use the `remittance` collection method. - /// ## Prepaid Subscription. - /// A prepaid subscription can be created with the usual subscription creation parameters, specifying `prepaid` as the `payment_collection_method` and including a nested `prepaid_configuration`. - /// After a prepaid subscription has been created, additional funds can be manually added to the prepayment account through the [Create Prepayment Endpoint](https://developers.chargify.com/docs/api-docs/7ec482de77ba7-create-prepayment). - /// Prepaid subscriptions do not work on legacy Statement Architecture. - /// ## With Metafields. - /// Metafields can either attach to subscriptions or customers. Metafields are popuplated with the supplied metadata to the resource specified. - /// If the metafield doesn't exist yet, it will be created on-the-fly. - /// ## With Custom Pricing. - /// Custom pricing is pricing specific to the subscription in question. - /// Create a subscription with custom pricing by passing pricing information instead of a price point. - /// For a custom priced product, pass the custom_price object in place of `product_price_point_id`. For a custom priced component, pass the `custom_price` object within the component object. - /// Custom prices and price points can exist in harmony on a subscription. - /// # Passing Payment Information. - /// ## Subscription with Chargify.js token. - /// The `chargify_token` can be obtained using [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). The token represents payment profile attributes that were provided by the customer in their browser and stored at the payment gateway. - /// The `payment_type` attribute may either be `credit_card` or `bank_account`, depending on the type of payment method being added. If a bank account is being passed, the payment attributes should be changed to `bank_account_attributes`. - /// ```json. - /// {. - /// "subscription": {. - /// "product_handle": "pro-plan",. - /// "customer_attributes": {. - /// "first_name": "Joe",. - /// "last_name": "Smith",. - /// "email": "j.smith@example.com". - /// },. - /// "credit_card_attributes": {. - /// "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn",. - /// "payment_type": "credit_card". - /// }. - /// }. - /// }. - /// ```. - /// ## Subscription with vault token. + /// This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met:. + /// + Taxes must be configured on the subscription. + /// + The preview must be for the purchase of a taxable product or component, or combination of the two. + /// + The subscription payload must contain a full billing or shipping address in order to calculate tax. + /// For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions). + /// You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. + /// You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. + /// ## Non-taxable Subscriptions. + /// If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. + /// + /// Optional parameter: Example: . + /// Returns the Models.SubscriptionPreviewResponse response from the API call. + public Models.SubscriptionPreviewResponse PreviewSubscription( + Models.CreateSubscriptionRequest body = null) + => CoreHelper.RunTask(PreviewSubscriptionAsync(body)); + + /// + /// The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. + /// The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). + /// ## Side effects. + /// A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. + /// ## Taxable Subscriptions. + /// This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met:. + /// + Taxes must be configured on the subscription. + /// + The preview must be for the purchase of a taxable product or component, or combination of the two. + /// + The subscription payload must contain a full billing or shipping address in order to calculate tax. + /// For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions). + /// You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. + /// You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. + /// ## Non-taxable Subscriptions. + /// If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. + /// + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.SubscriptionPreviewResponse response from the API call. + public async Task PreviewSubscriptionAsync( + Models.CreateSubscriptionRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/preview.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to find subscription details. + /// ## Self-Service Page token. + /// Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`.. + /// Returns the Models.SubscriptionResponse response from the API call. + public Models.SubscriptionResponse ReadSubscription( + int subscriptionId, + List include = null) + => CoreHelper.RunTask(ReadSubscriptionAsync(subscriptionId, include)); + + /// + /// Use this endpoint to find subscription details. + /// ## Self-Service Page token. + /// Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`.. + /// cancellationToken. + /// Returns the Models.SubscriptionResponse response from the API call. + public async Task ReadSubscriptionAsync( + int subscriptionId, + List include = null, + CancellationToken cancellationToken = default) + => await CreateApiCall(ArraySerialization.Plain) + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Query(_query => _query.Setup("include[]", include?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. + /// This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. + /// Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.**. + /// Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. + /// If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. + /// ## Limitations. + /// When passing `current_period_starts_at` some validations are made:. + /// 1. The subscription needs to be unbilled (no statements or invoices). + /// 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. + /// 3. The value passed must be before the current date/time. + /// If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Only these fields are available to be set.. + public void OverrideSubscription( + int subscriptionId, + Models.OverrideSubscriptionRequest body = null) + => CoreHelper.RunVoidTask(OverrideSubscriptionAsync(subscriptionId, body)); + + /// + /// This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. + /// This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. + /// Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.**. + /// Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. + /// If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. + /// ## Limitations. + /// When passing `current_period_starts_at` some validations are made:. + /// 1. The subscription needs to be unbilled (no statements or invoices). + /// 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. + /// 3. The value passed must be before the current date/time. + /// If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Only these fields are available to be set.. + /// cancellationToken. + /// Returns the void response from the API call. + public async Task OverrideSubscriptionAsync( + int subscriptionId, + Models.OverrideSubscriptionRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}/override.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to update a subscription's prepaid configuration. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// Returns the Models.PrepaidConfigurationResponse response from the API call. + public Models.PrepaidConfigurationResponse CreatePrepaidSubscription( + int subscriptionId, + Models.UpsertPrepaidConfigurationRequest body = null) + => CoreHelper.RunTask(CreatePrepaidSubscriptionAsync(subscriptionId, body)); + + /// + /// Use this endpoint to update a subscription's prepaid configuration. + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.PrepaidConfigurationResponse response from the API call. + public async Task CreatePrepaidSubscriptionAsync( + int subscriptionId, + Models.UpsertPrepaidConfigurationRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/prepaid_configurations.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Full documentation on how subscriptions operate within Chargify can be located under the following topics:. + /// + [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction). + /// + [Subscriptions Actions](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions). + /// + [Subscription Cancellation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions#initiate-cancellation). + /// + [Subscription Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021-Reactivating-and-Resuming). + /// + [Subscription Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821-Imports). + /// When creating a subscription, you must specify a product and a customer. Credit card details may be required, depending on the options for the Product being subscribed ([see Product Options](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221#payment-method-settings)). + /// The product may be specified by `product_id` or by `product_handle` (API Handle). In similar fashion, to pass a particular product price point, you may either use `product_price_point_handle` or `product_price_point_id`. + /// An existing customer may be specified by a `customer_id` (ID within Chargify) or a `customer_reference` (unique value within your app that you have shared with Chargify via the reference attribute on a customer). You may also pass in an existing payment profile for that customer with `payment_profile_id`. A new customer may be created by providing `customer_attributes`. + /// Credit card details may be required, depending on the options for the product being subscribed. The product can be specified by `product_id` or by `product_handle` (API Handle). + /// If you are creating a subscription with a payment profile, the attribute to send will be `credit_card_attributes` or `bank_account_attributes` for ACH and Direct Debit. That said, when you read the subscription after creation, we return the profile details under `credit_card` or `bank_account`. + /// ## Taxable Subscriptions. + /// If your intent is to charge your subscribers tax via [Avalara Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405275711885-Avalara-VAT-Tax) or [Custom Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405069041549-Custom-Taxes), there are a few considerations to be made regarding collecting subscription data. + /// For subscribers to be eligible to be taxed, the following information for the `customer` object or `payment_profile` object must by supplied:. + /// + A subscription to a [taxable product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221-Product-Editing#tax-settings). + /// + [Full valid billing or shipping address](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#full-address-required-for-taxable-subscriptions) to identify the tax locale. + /// + The portion of the address that houses the [state information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-state-format-for-taxable-subscriptions) of either adddress must adhere to the ISO standard of a 2-3 character limit/format. + /// + The portion of the address that houses the [country information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-country-format-for-taxable-subscriptions) must adhere to the ISO standard of a 2 character limit/format. + /// ## Subscription Request Examples. + /// The subscription examples below will be split into two sections. + /// The first section, "Subscription Customization", will focus on passing different information with a subscription, such as components, calendar billing, and custom fields. These examples will presume you are using a secure `chargify_token` generated by Chargify.js. + /// The second section, "Passing Payment Information", will focus on passing payment information into Chargify. Please be aware that collecting and sending Chargify raw card details requires PCI compliance on your end; these examples are provided as guidance. If your business is not PCI compliant, we recommend using Chargify.js to collect credit cards or bank accounts. + /// # Subscription Customization. + /// ## With Components. + /// Different components require slightly different data. For example, quantity-based and on/off components accept `allocated_quantity`, while metered components accept `unit_balance`. + /// When creating a subscription with a component, a `price_point_id` can be passed in along with the `component_id` to specify which price point to use. If not passed in, the default price point will be used. + /// Note: if an invalid `price_point_id` is used, the subscription will still proceed but will use the component's default price point. + /// Components and their price points may be added by ID or by handle. See the example request body labeled "Components By Handle (Quantity-Based)"; the format will be the same for other component types. + /// ## With Coupon(s). + /// Pass an array of `coupon_codes`. See the example request body "With Coupon". + /// ## With Manual Invoice Collection. + /// The `invoice` collection method works only on legacy Statement Architecture. + /// On Relationship Invoicing Architecture use the `remittance` collection method. + /// ## Prepaid Subscription. + /// A prepaid subscription can be created with the usual subscription creation parameters, specifying `prepaid` as the `payment_collection_method` and including a nested `prepaid_configuration`. + /// After a prepaid subscription has been created, additional funds can be manually added to the prepayment account through the [Create Prepayment Endpoint](https://developers.chargify.com/docs/api-docs/7ec482de77ba7-create-prepayment). + /// Prepaid subscriptions do not work on legacy Statement Architecture. + /// ## With Metafields. + /// Metafields can either attach to subscriptions or customers. Metafields are popuplated with the supplied metadata to the resource specified. + /// If the metafield doesn't exist yet, it will be created on-the-fly. + /// ## With Custom Pricing. + /// Custom pricing is pricing specific to the subscription in question. + /// Create a subscription with custom pricing by passing pricing information instead of a price point. + /// For a custom priced product, pass the custom_price object in place of `product_price_point_id`. For a custom priced component, pass the `custom_price` object within the component object. + /// Custom prices and price points can exist in harmony on a subscription. + /// # Passing Payment Information. + /// ## Subscription with Chargify.js token. + /// The `chargify_token` can be obtained using [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). The token represents payment profile attributes that were provided by the customer in their browser and stored at the payment gateway. + /// The `payment_type` attribute may either be `credit_card` or `bank_account`, depending on the type of payment method being added. If a bank account is being passed, the payment attributes should be changed to `bank_account_attributes`. + /// ```json. + /// {. + /// "subscription": {. + /// "product_handle": "pro-plan",. + /// "customer_attributes": {. + /// "first_name": "Joe",. + /// "last_name": "Smith",. + /// "email": "j.smith@example.com". + /// },. + /// "credit_card_attributes": {. + /// "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn",. + /// "payment_type": "credit_card". + /// }. + /// }. + /// }. + /// ```. + /// ## Subscription with vault token. /// If you already have a customer and card stored in your payment gateway, you may create a subscription with a `vault_token`. Providing the last_four, card type and expiration date will allow the card to be displayed properly in the Chargify UI. /// ```json. /// {. @@ -815,612 +1177,216 @@ public Models.SubscriptionResponse CreateSubscription( /// ## 3D Secure - Checkout. /// It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response:. /// ```json. - /// {. - /// "errors": [. - /// "Your card was declined. This transaction requires 3D secure authentication.". - /// ],. - /// "gateway_payment_id": "pay_6gjofv7dlyrkpizlolsuspvtiu",. - /// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.",. - /// "action_link": "http://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123". - /// }. - /// ```. - /// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. - /// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information:. - /// - whether the authentication was successful (`success`). - /// - the gateway ID for the payment (`gateway_payment_id`). - /// - the subscription ID (`subscription_id`). - /// Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. - /// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. - /// The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com`. - /// ### Example Redirect Flow. - /// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference:. - /// 1. Create a subscription via API; it requires 3DS. - /// 2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. - /// 3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id. - /// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to. - /// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied. - /// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. - /// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known. - /// 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not. - /// ## Subscriptions Import. - /// Subscriptions can be “imported” via the API to handle the following scenarios:. - /// + You already have existing subscriptions with specific start and renewal dates that you would like to import to Chargify. - /// + You already have credit cards stored in your provider’s vault and you would like to create subscriptions using those tokens. - /// Before importing, you should have already set up your products to match your offerings. Then, you can create Subscriptions via the API just like you normally would, but using a few special attributes. - /// Full documentation on how import Subscriptions using the **import tool** in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#imports-0-0). - /// ### Important Notices and Disclaimers regarding Imports. - /// Before performing a bulk import of subscriptions via the API, we suggest reading the [Subscriptions Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#important-notices-and-disclaimers) instructions to understand the repurcussions of a large import. - /// ### Subscription Input Attributes. - /// The following _additional_ attributes to the subscription input attributes make imports possible: `next_billing_at`, `previous_billing_at`, and `import_mrr`. - /// ### Current Vault. - /// If you are using a Legacy gateway such as "eWAY Rapid (Legacy)" or "Stripe (Legacy)" then please contact Support for further instructions on subscription imports. - /// ### Braintree Blue (Braintree v2) Imports. - /// Braintree Blue is Braintree’s newer (version 2) API. For this gateway, please provide the `vault_token` parameter with the value from Braintree’s “Customer ID” rather than the “Payment Profile Token”. At this time we do not use `current_vault_token` with the Braintree Blue gateway, and we only support a single payment profile per Braintree Customer. - /// When importing PayPal type payment profiles, please set `payment_type` to `paypal_account`. - /// ### Stripe ACH Imports. - /// If the bank account has already been verified, currently you will need to create the customer, create the payment profile in Chargify - setting verified=true, then create a subscription using the customer_id and payment_profile_id. - /// ### Webhooks During Import. - /// If no `next_billing_at` is provided, webhooks will be fired as normal. If you do set a future `next_billing_at`, only a subset of the webhooks are fired when the subscription is created. Keep reading for more information as to what webhooks will be fired under which scenarios. - /// #### Successful creation with Billing Date. - /// Scenario: If `next_billing_at` provided. - /// + `signup_success`. - /// + `billing_date_change`. - /// #### Successful creation without Billing Date. - /// Scenario: If no `next_billing_at` provided. - /// + `signup_success`. - /// + `payment_success`. - /// #### Unsuccessful creation. - /// Scenario: If card can’t be charged, and no `next_billing_at` provided. - /// + signup_failure. - /// #### Webhooks fired when next_billing_at is reached:. - /// + `renewal_success or renewal_failure`. - /// + `payment_success or payment_failure`. - /// ### Date and Time Formats. - /// We will attempt to parse any string you send as the value of next_billing_at in to a date or time. For best results, use a known format like described in “Date and Time Specification” of RFC 2822 or ISO 8601 . - /// The following are all equivalent and will work as input to `next_billing_at`:. - /// ```. - /// Aug 06 2030 11:34:00 -0400. - /// Aug 06 2030 11:34 -0400. - /// 2030-08-06T11:34:00-04:00. - /// 8/6/2030 11:34:00 EDT. - /// 8/6/2030 8:34:00 PDT. - /// 2030-08-06T15:34:00Z. - /// ```. - /// You may also pass just a date, in which case we will assume the time to be noon. - /// ```. - /// 2010-08-06. - /// ```. - /// ## Subscription Hierarchies & WhoPays. - /// When subscription groups were first added to our Relationship Invoicing architecture, to group together invoices for related subscriptions and allow for complex customer hierarchies and WhoPays scenarios, they were designed to consist of a primary and a collection of group members. The primary would control many aspects of the group, such as when the consolidated invoice is generated. As of today, groups still function this way. - /// In the future, the concept of a "primary" will be removed in order to offer more flexibility into group management and reduce confusion concerning what actions must be done on a primary level, rather than a member level. - /// We have introduced a two scheme system as a bridge between these two group organizations. Scheme 1, which is relevant to all subscription groups today, marks the group as being "ruled" by a primary. - /// When reading a subscription via API, they will return a top-level attribute called `group`, which will denote which scheme is being used. At this time, the `scheme` attribute will always be 1. - /// ### Subscription in a Customer Hierarchy. - /// For sites making use of the [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) and [Customer Hierarchy](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404900384141) features, it is possible to create subscriptions within a customer hierarchy. This can be achieved through the API by passing group parameters in the **Create Subscription** request. - /// + The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. - /// When the `target` parameter specifies a customer that is already part of a hierarchy, the new subscription will become a member of the customer hierarchy as well. If the target customer is not part of a hierarchy, a new customer hierarchy will be created and both the target customer and the new subscription will become part of the hierarchy with the specified target customer set as the responsible payer for the hierarchy's subscriptions. - /// Rather than specifying a customer, the `target` parameter could instead simply have a value of `self` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer. This will be true whether the customer is being created new, is already part of a hierarchy, or already exists outside a hierarchy. A valid payment method must also be specified in the subscription parameters. - /// Note that when creating subscriptions in a customer hierarchy, if the customer hierarchy does not already have a payment method, passing valid credit card attributes in the subscription parameters will also result in the payment method being established as the default payment method for the customer hierarchy irrespective of the responsible payer. - /// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the default subscription group in the customer hierarchy. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the default subscription group in the customer hierarchy also. - /// ### Subscription in a Subscription Group. - /// For sites making use of [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) it may be desireable to create a subscription as part of a [subscription group](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577356173) in order to rely on [invoice consolidation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404980119949). This can be achieved through the API by passing group parameters in the Create Subscription request. The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. - /// The `target` parameters specify an existing subscription with which the newly created subscription should be grouped. If the target subscription is already part of a group, the new subscription will become a member of the group as well. If the target subscription is not part of a group, a new group will be created and both the target and the new subscription will become part of the group with the target as the group's primary subscription. - /// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the target subscription. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the target subscription also. - /// ## Providing Agreement Acceptance Params. - /// It is possible to provide a proof of customer's acceptance of terms and policies. - /// We will be storing this proof in case it might be required (i.e. chargeback). - /// Currently, we already keep it for subscriptions created via Public Signup Pages. - /// In order to create a subscription with the proof of agreement acceptance, you must provide additional parameters `agreement acceptance` with `ip_address` and at least one url to the policy that was accepted: `terms_url` or `privacy_policy_url`. Additional urls that can be provided: `return_refund_policy_url`, `delivery_policy_url` and. - /// `secure_checkout_policy_url`. - /// ```json. - /// "subscription": {. - /// "product_handle": "gold-product",. - /// "customer_attributes": {. - /// "first_name": "Jane",. - /// "last_name": "Doe",. - /// "email": "jd@chargify.test". - /// },. - /// "agreement_acceptance": {. - /// "ip_address": "1.2.3.4",. - /// "terms_url": "https://terms.url",. - /// "privacy_policy_url": "https://privacy_policy.url",. - /// "return_refund_policy_url": "https://return_refund_policy.url",. - /// "delivery_policy_url": "https://delivery_policy.url",. - /// "secure_checkout_policy_url": "https://secure_checkout_policy.url". - /// }. - /// }. - /// }. - /// ```. - /// **For Maxio Payments subscriptions, the agreement acceptance params are required, with at least terms_url provided.**. - /// ## Providing ACH Agreement params. - /// It is also possible to provide a proof that a customer authorized ACH agreement terms. - /// The proof will be stored and the email will be sent to the customer with a copy of the terms (if enabled). - /// In order to create a subscription with the proof of authorized ACH agreement terms, you must provide the additional parameter `ach_agreement` with the following nested parameters: `agreement_terms`, `authorizer_first_name`, `authorizer_last_name` and `ip_address`. - /// Each of them is required. - /// ```json. - /// "subscription": {. - /// "product_handle": "gold-product",. - /// "customer_attributes": {. - /// "first_name": "Jane",. - /// "last_name": "Doe",. - /// "email": "jd@chargify.test". - /// },. - /// "bank_account_attributes": {. - /// "bank_name": "Test Bank",. - /// "bank_routing_number": "021000089",. - /// "bank_account_number": "111111111111",. - /// "bank_account_type": "checking",. - /// "bank_account_holder_type": "business",. - /// "payment_type": "bank_account". - /// },. - /// "ach_agreement": {. - /// "agreement_terms": "ACH agreement terms",. - /// "authorizer_first_name": "Jane",. - /// "authorizer_last_name": "Doe",. - /// "ip_address": "1.2.3.4". - /// }. - /// }. - /// ```. - /// - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.SubscriptionResponse response from the API call. - public async Task CreateSubscriptionAsync( - Models.CreateSubscriptionRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. - /// ## Search for a subscription. - /// Use the query strings below to search for a subscription using the criteria available. The return value will be an array. - /// ## Self-Service Page token. - /// Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. - /// - /// Object containing request parameters. - /// Returns the List of Models.SubscriptionResponse response from the API call. - public List ListSubscriptions( - Models.ListSubscriptionsInput input) - => CoreHelper.RunTask(ListSubscriptionsAsync(input)); - - /// - /// This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. - /// ## Search for a subscription. - /// Use the query strings below to search for a subscription using the criteria available. The return value will be an array. - /// ## Self-Service Page token. - /// Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. - /// - /// Object containing request parameters. - /// cancellationToken. - /// Returns the List of Models.SubscriptionResponse response from the API call. - public async Task> ListSubscriptionsAsync( - Models.ListSubscriptionsInput input, - CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("page", input.Page)) - .Query(_query => _query.Setup("per_page", input.PerPage)) - .Query(_query => _query.Setup("state", (input.State.HasValue) ? ApiHelper.JsonSerialize(input.State.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("product", input.Product)) - .Query(_query => _query.Setup("product_price_point_id", input.ProductPricePointId)) - .Query(_query => _query.Setup("coupon", input.Coupon)) - .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("start_date", input.StartDate.HasValue ? input.StartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("end_date", input.EndDate.HasValue ? input.EndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) - .Query(_query => _query.Setup("start_datetime", input.StartDatetime.HasValue ? input.StartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("end_datetime", input.EndDatetime.HasValue ? input.EndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) - .Query(_query => _query.Setup("metadata", input.Metadata)) - .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) - .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : "signup_date")) - .Query(_query => _query.Setup("include[]", input.Include?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. - /// ## Update Subscription Payment Method. - /// Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. - /// Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. - /// You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. - /// ## Product Change. - /// This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. - /// To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. - /// ### Delayed Product Change. - /// This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. - /// This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. - /// You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle`. - /// **Note: To cancel a delayed product change, set `next_product_id` to an empty string.**. - /// ## Billing Date Changes. - /// ### Regular Billing Date Changes. - /// Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. - /// Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. - /// The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. - /// ### Snap Day Changes. - /// For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. - /// Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// Returns the Models.SubscriptionResponse response from the API call. - public Models.SubscriptionResponse UpdateSubscription( - int subscriptionId, - Models.UpdateSubscriptionRequest body = null) - => CoreHelper.RunTask(UpdateSubscriptionAsync(subscriptionId, body)); - - /// - /// The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. - /// ## Update Subscription Payment Method. - /// Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. - /// Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. - /// You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. - /// ## Product Change. - /// This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. - /// To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. - /// ### Delayed Product Change. - /// This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. - /// This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. - /// You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle`. - /// **Note: To cancel a delayed product change, set `next_product_id` to an empty string.**. - /// ## Billing Date Changes. - /// ### Regular Billing Date Changes. - /// Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. - /// Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. - /// The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. - /// ### Snap Day Changes. - /// For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. - /// Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.SubscriptionResponse response from the API call. - public async Task UpdateSubscriptionAsync( - int subscriptionId, - Models.UpdateSubscriptionRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to find subscription details. - /// ## Self-Service Page token. - /// Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`.. - /// Returns the Models.SubscriptionResponse response from the API call. - public Models.SubscriptionResponse ReadSubscription( - int subscriptionId, - List include = null) - => CoreHelper.RunTask(ReadSubscriptionAsync(subscriptionId, include)); - - /// - /// Use this endpoint to find subscription details. - /// ## Self-Service Page token. - /// Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`.. - /// cancellationToken. - /// Returns the Models.SubscriptionResponse response from the API call. - public async Task ReadSubscriptionAsync( - int subscriptionId, - List include = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/{subscription_id}.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Query(_query => _query.Setup("include[]", include?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. - /// This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. - /// Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.**. - /// Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. - /// If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. - /// ## Limitations. - /// When passing `current_period_starts_at` some validations are made:. - /// 1. The subscription needs to be unbilled (no statements or invoices). - /// 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. - /// 3. The value passed must be before the current date/time. - /// If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Only these fields are available to be set.. - public void OverrideSubscription( - int subscriptionId, - Models.OverrideSubscriptionRequest body = null) - => CoreHelper.RunVoidTask(OverrideSubscriptionAsync(subscriptionId, body)); - - /// - /// This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. - /// This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. - /// Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.**. - /// Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. - /// If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. - /// ## Limitations. - /// When passing `current_period_starts_at` some validations are made:. - /// 1. The subscription needs to be unbilled (no statements or invoices). - /// 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. - /// 3. The value passed must be before the current date/time. - /// If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Only these fields are available to be set.. - /// cancellationToken. - /// Returns the void response from the API call. - public async Task OverrideSubscriptionAsync( - int subscriptionId, - Models.OverrideSubscriptionRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/subscriptions/{subscription_id}/override.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SingleErrorResponseException(_reason, _context), true))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to find a subscription by its reference. - /// - /// Optional parameter: Subscription reference. - /// Returns the Models.SubscriptionResponse response from the API call. - public Models.SubscriptionResponse ReadSubscriptionByReference( - string reference = null) - => CoreHelper.RunTask(ReadSubscriptionByReferenceAsync(reference)); - - /// - /// Use this endpoint to find a subscription by its reference. - /// - /// Optional parameter: Subscription reference. - /// cancellationToken. - /// Returns the Models.SubscriptionResponse response from the API call. - public async Task ReadSubscriptionByReferenceAsync( - string reference = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/subscriptions/lookup.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Query(_query => _query.Setup("reference", reference)))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// For sites in test mode, you may purge individual subscriptions. - /// Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer`. - /// If you need to remove subscriptions from a live site, please contact support to discuss your use case. - /// ### Delete customer and payment profile. - /// The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile`. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: id of the customer.. - /// Optional parameter: Options are "customer" or "payment_profile". Use in query: `cascade[]=customer&cascade[]=payment_profile`.. - public void PurgeSubscription( - int subscriptionId, - int ack, - List cascade = null) - => CoreHelper.RunVoidTask(PurgeSubscriptionAsync(subscriptionId, ack, cascade)); - - /// - /// For sites in test mode, you may purge individual subscriptions. - /// Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer`. - /// If you need to remove subscriptions from a live site, please contact support to discuss your use case. - /// ### Delete customer and payment profile. - /// The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile`. - /// - /// Required parameter: The Chargify id of the subscription. - /// Required parameter: id of the customer.. - /// Optional parameter: Options are "customer" or "payment_profile". Use in query: `cascade[]=customer&cascade[]=payment_profile`.. - /// cancellationToken. - /// Returns the void response from the API call. - public async Task PurgeSubscriptionAsync( - int subscriptionId, - int ack, - List cascade = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/purge.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Query(_query => _query.Setup("ack", ack)) - .Query(_query => _query.Setup("cascade[]", cascade?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Use this endpoint to update a subscription's prepaid configuration. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// Returns the Models.PrepaidConfigurationResponse response from the API call. - public Models.PrepaidConfigurationResponse CreatePrepaidSubscription( - int subscriptionId, - Models.UpsertPrepaidConfigurationRequest body = null) - => CoreHelper.RunTask(CreatePrepaidSubscriptionAsync(subscriptionId, body)); - - /// - /// Use this endpoint to update a subscription's prepaid configuration. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.PrepaidConfigurationResponse response from the API call. - public async Task CreatePrepaidSubscriptionAsync( - int subscriptionId, - Models.UpsertPrepaidConfigurationRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/prepaid_configurations.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. - /// The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). - /// ## Side effects. - /// A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. - /// ## Taxable Subscriptions. - /// This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met:. - /// + Taxes must be configured on the subscription. - /// + The preview must be for the purchase of a taxable product or component, or combination of the two. - /// + The subscription payload must contain a full billing or shipping address in order to calculate tax. - /// For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions). - /// You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. - /// You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. - /// ## Non-taxable Subscriptions. - /// If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. - /// - /// Optional parameter: Example: . - /// Returns the Models.SubscriptionPreviewResponse response from the API call. - public Models.SubscriptionPreviewResponse PreviewSubscription( - Models.CreateSubscriptionRequest body = null) - => CoreHelper.RunTask(PreviewSubscriptionAsync(body)); - - /// - /// The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. - /// The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). - /// ## Side effects. - /// A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. - /// ## Taxable Subscriptions. - /// This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met:. - /// + Taxes must be configured on the subscription. - /// + The preview must be for the purchase of a taxable product or component, or combination of the two. - /// + The subscription payload must contain a full billing or shipping address in order to calculate tax. - /// For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions). - /// You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. - /// You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. - /// ## Non-taxable Subscriptions. - /// If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. - /// - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.SubscriptionPreviewResponse response from the API call. - public async Task PreviewSubscriptionAsync( - Models.CreateSubscriptionRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/preview.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons). - /// ## Query Parameters vs Request Body Parameters. - /// Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. - /// For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. - /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: A code for the coupon that would be applied to a subscription. - /// Optional parameter: Example: . - /// Returns the Models.SubscriptionResponse response from the API call. - public Models.SubscriptionResponse ApplyCouponToSubscription( - int subscriptionId, - string code = null, - Models.AddCouponsRequest body = null) - => CoreHelper.RunTask(ApplyCouponToSubscriptionAsync(subscriptionId, code, body)); - - /// - /// An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons). - /// ## Query Parameters vs Request Body Parameters. - /// Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. - /// For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. + /// {. + /// "errors": [. + /// "Your card was declined. This transaction requires 3D secure authentication.". + /// ],. + /// "gateway_payment_id": "pay_6gjofv7dlyrkpizlolsuspvtiu",. + /// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.",. + /// "action_link": "http://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123". + /// }. + /// ```. + /// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. + /// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information:. + /// - whether the authentication was successful (`success`). + /// - the gateway ID for the payment (`gateway_payment_id`). + /// - the subscription ID (`subscription_id`). + /// Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. + /// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. + /// The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com`. + /// ### Example Redirect Flow. + /// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference:. + /// 1. Create a subscription via API; it requires 3DS. + /// 2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. + /// 3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id. + /// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to. + /// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied. + /// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. + /// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known. + /// 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not. + /// ## Subscriptions Import. + /// Subscriptions can be “imported” via the API to handle the following scenarios:. + /// + You already have existing subscriptions with specific start and renewal dates that you would like to import to Chargify. + /// + You already have credit cards stored in your provider’s vault and you would like to create subscriptions using those tokens. + /// Before importing, you should have already set up your products to match your offerings. Then, you can create Subscriptions via the API just like you normally would, but using a few special attributes. + /// Full documentation on how import Subscriptions using the **import tool** in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#imports-0-0). + /// ### Important Notices and Disclaimers regarding Imports. + /// Before performing a bulk import of subscriptions via the API, we suggest reading the [Subscriptions Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#important-notices-and-disclaimers) instructions to understand the repurcussions of a large import. + /// ### Subscription Input Attributes. + /// The following _additional_ attributes to the subscription input attributes make imports possible: `next_billing_at`, `previous_billing_at`, and `import_mrr`. + /// ### Current Vault. + /// If you are using a Legacy gateway such as "eWAY Rapid (Legacy)" or "Stripe (Legacy)" then please contact Support for further instructions on subscription imports. + /// ### Braintree Blue (Braintree v2) Imports. + /// Braintree Blue is Braintree’s newer (version 2) API. For this gateway, please provide the `vault_token` parameter with the value from Braintree’s “Customer ID” rather than the “Payment Profile Token”. At this time we do not use `current_vault_token` with the Braintree Blue gateway, and we only support a single payment profile per Braintree Customer. + /// When importing PayPal type payment profiles, please set `payment_type` to `paypal_account`. + /// ### Stripe ACH Imports. + /// If the bank account has already been verified, currently you will need to create the customer, create the payment profile in Chargify - setting verified=true, then create a subscription using the customer_id and payment_profile_id. + /// ### Webhooks During Import. + /// If no `next_billing_at` is provided, webhooks will be fired as normal. If you do set a future `next_billing_at`, only a subset of the webhooks are fired when the subscription is created. Keep reading for more information as to what webhooks will be fired under which scenarios. + /// #### Successful creation with Billing Date. + /// Scenario: If `next_billing_at` provided. + /// + `signup_success`. + /// + `billing_date_change`. + /// #### Successful creation without Billing Date. + /// Scenario: If no `next_billing_at` provided. + /// + `signup_success`. + /// + `payment_success`. + /// #### Unsuccessful creation. + /// Scenario: If card can’t be charged, and no `next_billing_at` provided. + /// + signup_failure. + /// #### Webhooks fired when next_billing_at is reached:. + /// + `renewal_success or renewal_failure`. + /// + `payment_success or payment_failure`. + /// ### Date and Time Formats. + /// We will attempt to parse any string you send as the value of next_billing_at in to a date or time. For best results, use a known format like described in “Date and Time Specification” of RFC 2822 or ISO 8601 . + /// The following are all equivalent and will work as input to `next_billing_at`:. + /// ```. + /// Aug 06 2030 11:34:00 -0400. + /// Aug 06 2030 11:34 -0400. + /// 2030-08-06T11:34:00-04:00. + /// 8/6/2030 11:34:00 EDT. + /// 8/6/2030 8:34:00 PDT. + /// 2030-08-06T15:34:00Z. + /// ```. + /// You may also pass just a date, in which case we will assume the time to be noon. + /// ```. + /// 2010-08-06. + /// ```. + /// ## Subscription Hierarchies & WhoPays. + /// When subscription groups were first added to our Relationship Invoicing architecture, to group together invoices for related subscriptions and allow for complex customer hierarchies and WhoPays scenarios, they were designed to consist of a primary and a collection of group members. The primary would control many aspects of the group, such as when the consolidated invoice is generated. As of today, groups still function this way. + /// In the future, the concept of a "primary" will be removed in order to offer more flexibility into group management and reduce confusion concerning what actions must be done on a primary level, rather than a member level. + /// We have introduced a two scheme system as a bridge between these two group organizations. Scheme 1, which is relevant to all subscription groups today, marks the group as being "ruled" by a primary. + /// When reading a subscription via API, they will return a top-level attribute called `group`, which will denote which scheme is being used. At this time, the `scheme` attribute will always be 1. + /// ### Subscription in a Customer Hierarchy. + /// For sites making use of the [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) and [Customer Hierarchy](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404900384141) features, it is possible to create subscriptions within a customer hierarchy. This can be achieved through the API by passing group parameters in the **Create Subscription** request. + /// + The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. + /// When the `target` parameter specifies a customer that is already part of a hierarchy, the new subscription will become a member of the customer hierarchy as well. If the target customer is not part of a hierarchy, a new customer hierarchy will be created and both the target customer and the new subscription will become part of the hierarchy with the specified target customer set as the responsible payer for the hierarchy's subscriptions. + /// Rather than specifying a customer, the `target` parameter could instead simply have a value of `self` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer. This will be true whether the customer is being created new, is already part of a hierarchy, or already exists outside a hierarchy. A valid payment method must also be specified in the subscription parameters. + /// Note that when creating subscriptions in a customer hierarchy, if the customer hierarchy does not already have a payment method, passing valid credit card attributes in the subscription parameters will also result in the payment method being established as the default payment method for the customer hierarchy irrespective of the responsible payer. + /// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the default subscription group in the customer hierarchy. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the default subscription group in the customer hierarchy also. + /// ### Subscription in a Subscription Group. + /// For sites making use of [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) it may be desireable to create a subscription as part of a [subscription group](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577356173) in order to rely on [invoice consolidation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404980119949). This can be achieved through the API by passing group parameters in the Create Subscription request. The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. + /// The `target` parameters specify an existing subscription with which the newly created subscription should be grouped. If the target subscription is already part of a group, the new subscription will become a member of the group as well. If the target subscription is not part of a group, a new group will be created and both the target and the new subscription will become part of the group with the target as the group's primary subscription. + /// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the target subscription. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the target subscription also. + /// ## Providing Agreement Acceptance Params. + /// It is possible to provide a proof of customer's acceptance of terms and policies. + /// We will be storing this proof in case it might be required (i.e. chargeback). + /// Currently, we already keep it for subscriptions created via Public Signup Pages. + /// In order to create a subscription with the proof of agreement acceptance, you must provide additional parameters `agreement acceptance` with `ip_address` and at least one url to the policy that was accepted: `terms_url` or `privacy_policy_url`. Additional urls that can be provided: `return_refund_policy_url`, `delivery_policy_url` and. + /// `secure_checkout_policy_url`. + /// ```json. + /// "subscription": {. + /// "product_handle": "gold-product",. + /// "customer_attributes": {. + /// "first_name": "Jane",. + /// "last_name": "Doe",. + /// "email": "jd@chargify.test". + /// },. + /// "agreement_acceptance": {. + /// "ip_address": "1.2.3.4",. + /// "terms_url": "https://terms.url",. + /// "privacy_policy_url": "https://privacy_policy.url",. + /// "return_refund_policy_url": "https://return_refund_policy.url",. + /// "delivery_policy_url": "https://delivery_policy.url",. + /// "secure_checkout_policy_url": "https://secure_checkout_policy.url". + /// }. + /// }. + /// }. + /// ```. + /// **For Maxio Payments subscriptions, the agreement acceptance params are required, with at least terms_url provided.**. + /// ## Providing ACH Agreement params. + /// It is also possible to provide a proof that a customer authorized ACH agreement terms. + /// The proof will be stored and the email will be sent to the customer with a copy of the terms (if enabled). + /// In order to create a subscription with the proof of authorized ACH agreement terms, you must provide the additional parameter `ach_agreement` with the following nested parameters: `agreement_terms`, `authorizer_first_name`, `authorizer_last_name` and `ip_address`. + /// Each of them is required. + /// ```json. + /// "subscription": {. + /// "product_handle": "gold-product",. + /// "customer_attributes": {. + /// "first_name": "Jane",. + /// "last_name": "Doe",. + /// "email": "jd@chargify.test". + /// },. + /// "bank_account_attributes": {. + /// "bank_name": "Test Bank",. + /// "bank_routing_number": "021000089",. + /// "bank_account_number": "111111111111",. + /// "bank_account_type": "checking",. + /// "bank_account_holder_type": "business",. + /// "payment_type": "bank_account". + /// },. + /// "ach_agreement": {. + /// "agreement_terms": "ACH agreement terms",. + /// "authorizer_first_name": "Jane",. + /// "authorizer_last_name": "Doe",. + /// "ip_address": "1.2.3.4". + /// }. + /// }. + /// ```. /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: A code for the coupon that would be applied to a subscription. /// Optional parameter: Example: . /// cancellationToken. /// Returns the Models.SubscriptionResponse response from the API call. - public async Task ApplyCouponToSubscriptionAsync( - int subscriptionId, - string code = null, - Models.AddCouponsRequest body = null, + public async Task CreateSubscriptionAsync( + Models.CreateSubscriptionRequest body = null, CancellationToken cancellationToken = default) => await CreateApiCall() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/subscriptions/{subscription_id}/add_coupon.json") + .Setup(HttpMethod.Post, "/subscriptions.json") .WithAuth("global") .Parameters(_parameters => _parameters .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Header(_header => _header.Setup("Content-Type", "application/json")) - .Query(_query => _query.Setup("code", code)))) + .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionAddCouponErrorException(_reason, _context), true))) + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// - /// Use this endpoint to remove a coupon from an existing subscription. - /// For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon). + /// This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. + /// ## Search for a subscription. + /// Use the query strings below to search for a subscription using the criteria available. The return value will be an array. + /// ## Self-Service Page token. + /// Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: The coupon code. - /// Returns the string response from the API call. - public string DeleteCouponFromSubscription( - int subscriptionId, - string couponCode = null) - => CoreHelper.RunTask(DeleteCouponFromSubscriptionAsync(subscriptionId, couponCode)); + /// Object containing request parameters. + /// Returns the List of Models.SubscriptionResponse response from the API call. + public List ListSubscriptions( + Models.ListSubscriptionsInput input) + => CoreHelper.RunTask(ListSubscriptionsAsync(input)); /// - /// Use this endpoint to remove a coupon from an existing subscription. - /// For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon). + /// This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. + /// ## Search for a subscription. + /// Use the query strings below to search for a subscription using the criteria available. The return value will be an array. + /// ## Self-Service Page token. + /// Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. /// - /// Required parameter: The Chargify id of the subscription. - /// Optional parameter: The coupon code. + /// Object containing request parameters. /// cancellationToken. - /// Returns the string response from the API call. - public async Task DeleteCouponFromSubscriptionAsync( - int subscriptionId, - string couponCode = null, + /// Returns the List of Models.SubscriptionResponse response from the API call. + public async Task> ListSubscriptionsAsync( + Models.ListSubscriptionsInput input, CancellationToken cancellationToken = default) - => await CreateApiCall() + => await CreateApiCall>() .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/remove_coupon.json") + .Setup(HttpMethod.Get, "/subscriptions.json") .WithAuth("global") .Parameters(_parameters => _parameters - .Template(_template => _template.Setup("subscription_id", subscriptionId)) - .Query(_query => _query.Setup("coupon_code", couponCode)))) - .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionRemoveCouponErrorsException(_reason, _context), true))) + .Query(_query => _query.Setup("page", input.Page)) + .Query(_query => _query.Setup("per_page", input.PerPage)) + .Query(_query => _query.Setup("state", (input.State.HasValue) ? ApiHelper.JsonSerialize(input.State.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("product", input.Product)) + .Query(_query => _query.Setup("product_price_point_id", input.ProductPricePointId)) + .Query(_query => _query.Setup("coupon", input.Coupon)) + .Query(_query => _query.Setup("date_field", (input.DateField.HasValue) ? ApiHelper.JsonSerialize(input.DateField.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("start_date", input.StartDate.HasValue ? input.StartDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("end_date", input.EndDate.HasValue ? input.EndDate.Value.ToString("yyyy'-'MM'-'dd") : null)) + .Query(_query => _query.Setup("start_datetime", input.StartDatetime.HasValue ? input.StartDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("end_datetime", input.EndDatetime.HasValue ? input.EndDatetime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null)) + .Query(_query => _query.Setup("metadata", input.Metadata)) + .Query(_query => _query.Setup("direction", (input.Direction.HasValue) ? ApiHelper.JsonSerialize(input.Direction.Value).Trim('\"') : null)) + .Query(_query => _query.Setup("sort", (input.Sort.HasValue) ? ApiHelper.JsonSerialize(input.Sort.Value).Trim('\"') : "signup_date")) + .Query(_query => _query.Setup("include[]", input.Include?.Select(a => ApiHelper.JsonSerialize(a).Trim('\"')).ToList())))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); /// @@ -1514,7 +1480,42 @@ public Models.SubscriptionResponse ActivateSubscription( .Template(_template => _template.Setup("subscription_id", subscriptionId)) .Header(_header => _header.Setup("Content-Type", "application/json")))) .ResponseHandler(_responseHandler => _responseHandler - .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new NestedErrorResponseException(_reason, _context), true))) + .ErrorCase("400", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorArrayMapResponseException(_reason, _context), true))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Use this endpoint to remove a coupon from an existing subscription. + /// For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon). + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: The coupon code. + /// Returns the string response from the API call. + public string DeleteCouponFromSubscription( + int subscriptionId, + string couponCode = null) + => CoreHelper.RunTask(DeleteCouponFromSubscriptionAsync(subscriptionId, couponCode)); + + /// + /// Use this endpoint to remove a coupon from an existing subscription. + /// For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon). + /// + /// Required parameter: The Chargify id of the subscription. + /// Optional parameter: The coupon code. + /// cancellationToken. + /// Returns the string response from the API call. + public async Task DeleteCouponFromSubscriptionAsync( + int subscriptionId, + string couponCode = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Delete, "/subscriptions/{subscription_id}/remove_coupon.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Template(_template => _template.Setup("subscription_id", subscriptionId)) + .Query(_query => _query.Setup("coupon_code", couponCode)))) + .ResponseHandler(_responseHandler => _responseHandler + .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new SubscriptionRemoveCouponErrorsException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Controllers/WebhooksController.cs b/AdvancedBilling.Standard/Controllers/WebhooksController.cs index 66ade9a..22776f9 100644 --- a/AdvancedBilling.Standard/Controllers/WebhooksController.cs +++ b/AdvancedBilling.Standard/Controllers/WebhooksController.cs @@ -82,62 +82,6 @@ internal WebhooksController(GlobalConfiguration globalConfiguration) : base(glob .Query(_query => _query.Setup("subscription", input.Subscription)))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// This method allows you to enable webhooks via API for your site. - /// - /// Optional parameter: Example: . - /// Returns the Models.EnableWebhooksResponse response from the API call. - public Models.EnableWebhooksResponse EnableWebhooks( - Models.EnableWebhooksRequest body = null) - => CoreHelper.RunTask(EnableWebhooksAsync(body)); - - /// - /// This method allows you to enable webhooks via API for your site. - /// - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.EnableWebhooksResponse response from the API call. - public async Task EnableWebhooksAsync( - Models.EnableWebhooksRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Put, "/webhooks/settings.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - - /// - /// Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. - /// You may submit an array of up to 1000 webhook IDs to replay in the request. - /// - /// Optional parameter: Example: . - /// Returns the Models.ReplayWebhooksResponse response from the API call. - public Models.ReplayWebhooksResponse ReplayWebhooks( - Models.ReplayWebhooksRequest body = null) - => CoreHelper.RunTask(ReplayWebhooksAsync(body)); - - /// - /// Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. - /// You may submit an array of up to 1000 webhook IDs to replay in the request. - /// - /// Optional parameter: Example: . - /// cancellationToken. - /// Returns the Models.ReplayWebhooksResponse response from the API call. - public async Task ReplayWebhooksAsync( - Models.ReplayWebhooksRequest body = null, - CancellationToken cancellationToken = default) - => await CreateApiCall() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Post, "/webhooks/replay.json") - .WithAuth("global") - .Parameters(_parameters => _parameters - .Body(_bodyParameter => _bodyParameter.Setup(body)) - .Header(_header => _header.Setup("Content-Type", "application/json")))) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// The Chargify API allows you to create an endpoint and assign a list of webhooks subscriptions (events) to it. /// You can check available events here. @@ -171,25 +115,6 @@ public Models.EndpointResponse CreateEndpoint( .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// - /// This method returns created endpoints for site. - /// - /// Returns the List of Models.Endpoint response from the API call. - public List ListEndpoints() - => CoreHelper.RunTask(ListEndpointsAsync()); - - /// - /// This method returns created endpoints for site. - /// - /// cancellationToken. - /// Returns the List of Models.Endpoint response from the API call. - public async Task> ListEndpointsAsync(CancellationToken cancellationToken = default) - => await CreateApiCall>() - .RequestBuilder(_requestBuilder => _requestBuilder - .Setup(HttpMethod.Get, "/endpoints.json") - .WithAuth("global")) - .ExecuteAsync(cancellationToken).ConfigureAwait(false); - /// /// You can update an Endpoint via the API with a PUT request to the resource endpoint. /// You can change the `url` of your endpoint which consumes webhooks or list of `webhook_subscriptions`. @@ -234,5 +159,80 @@ public Models.EndpointResponse UpdateEndpoint( .ErrorCase("404", CreateErrorCase("Not Found:'{$response.body}'", (_reason, _context) => new ApiException(_reason, _context), true)) .ErrorCase("422", CreateErrorCase("HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", (_reason, _context) => new ErrorListResponseException(_reason, _context), true))) .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This method returns created endpoints for site. + /// + /// Returns the List of Models.Endpoint response from the API call. + public List ListEndpoints() + => CoreHelper.RunTask(ListEndpointsAsync()); + + /// + /// This method returns created endpoints for site. + /// + /// cancellationToken. + /// Returns the List of Models.Endpoint response from the API call. + public async Task> ListEndpointsAsync(CancellationToken cancellationToken = default) + => await CreateApiCall>() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Get, "/endpoints.json") + .WithAuth("global")) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// This method allows you to enable webhooks via API for your site. + /// + /// Optional parameter: Example: . + /// Returns the Models.EnableWebhooksResponse response from the API call. + public Models.EnableWebhooksResponse EnableWebhooks( + Models.EnableWebhooksRequest body = null) + => CoreHelper.RunTask(EnableWebhooksAsync(body)); + + /// + /// This method allows you to enable webhooks via API for your site. + /// + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.EnableWebhooksResponse response from the API call. + public async Task EnableWebhooksAsync( + Models.EnableWebhooksRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Put, "/webhooks/settings.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); + + /// + /// Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. + /// You may submit an array of up to 1000 webhook IDs to replay in the request. + /// + /// Optional parameter: Example: . + /// Returns the Models.ReplayWebhooksResponse response from the API call. + public Models.ReplayWebhooksResponse ReplayWebhooks( + Models.ReplayWebhooksRequest body = null) + => CoreHelper.RunTask(ReplayWebhooksAsync(body)); + + /// + /// Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. + /// You may submit an array of up to 1000 webhook IDs to replay in the request. + /// + /// Optional parameter: Example: . + /// cancellationToken. + /// Returns the Models.ReplayWebhooksResponse response from the API call. + public async Task ReplayWebhooksAsync( + Models.ReplayWebhooksRequest body = null, + CancellationToken cancellationToken = default) + => await CreateApiCall() + .RequestBuilder(_requestBuilder => _requestBuilder + .Setup(HttpMethod.Post, "/webhooks/replay.json") + .WithAuth("global") + .Parameters(_parameters => _parameters + .Body(_bodyParameter => _bodyParameter.Setup(body)) + .Header(_header => _header.Setup("Content-Type", "application/json")))) + .ExecuteAsync(cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Exceptions/ErrorMapResponseException.cs b/AdvancedBilling.Standard/Exceptions/ErrorArrayMapResponseException.cs similarity index 75% rename from AdvancedBilling.Standard/Exceptions/ErrorMapResponseException.cs rename to AdvancedBilling.Standard/Exceptions/ErrorArrayMapResponseException.cs index 0be0ac2..e28e6fd 100644 --- a/AdvancedBilling.Standard/Exceptions/ErrorMapResponseException.cs +++ b/AdvancedBilling.Standard/Exceptions/ErrorArrayMapResponseException.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Exceptions @@ -19,16 +19,16 @@ namespace AdvancedBilling.Standard.Exceptions using Newtonsoft.Json.Converters; /// - /// ErrorMapResponseException. + /// ErrorArrayMapResponseException. /// - public class ErrorMapResponseException : ApiException + public class ErrorArrayMapResponseException : ApiException { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The reason for throwing exception. /// The HTTP context that encapsulates request and response objects. - public ErrorMapResponseException(string reason, HttpContext context) + public ErrorArrayMapResponseException(string reason, HttpContext context) : base(reason, context) { } diff --git a/AdvancedBilling.Standard/Exceptions/NestedErrorResponseException.cs b/AdvancedBilling.Standard/Exceptions/ErrorStringMapResponseException.cs similarity index 71% rename from AdvancedBilling.Standard/Exceptions/NestedErrorResponseException.cs rename to AdvancedBilling.Standard/Exceptions/ErrorStringMapResponseException.cs index 5b29637..cfb8385 100644 --- a/AdvancedBilling.Standard/Exceptions/NestedErrorResponseException.cs +++ b/AdvancedBilling.Standard/Exceptions/ErrorStringMapResponseException.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Exceptions @@ -19,16 +19,16 @@ namespace AdvancedBilling.Standard.Exceptions using Newtonsoft.Json.Converters; /// - /// NestedErrorResponseException. + /// ErrorStringMapResponseException. /// - public class NestedErrorResponseException : ApiException + public class ErrorStringMapResponseException : ApiException { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The reason for throwing exception. /// The HTTP context that encapsulates request and response objects. - public NestedErrorResponseException(string reason, HttpContext context) + public ErrorStringMapResponseException(string reason, HttpContext context) : base(reason, context) { } @@ -37,6 +37,6 @@ public NestedErrorResponseException(string reason, HttpContext context) /// Gets or sets Errors. /// [JsonProperty("errors", NullValueHandling = NullValueHandling.Ignore)] - public object Errors { get; set; } + public Dictionary Errors { get; set; } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/AppliedCreditNote.cs b/AdvancedBilling.Standard/Models/AppliedCreditNoteData.cs similarity index 82% rename from AdvancedBilling.Standard/Models/AppliedCreditNote.cs rename to AdvancedBilling.Standard/Models/AppliedCreditNoteData.cs index 7078f5a..f2e7d4f 100644 --- a/AdvancedBilling.Standard/Models/AppliedCreditNote.cs +++ b/AdvancedBilling.Standard/Models/AppliedCreditNoteData.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Models @@ -17,23 +17,23 @@ namespace AdvancedBilling.Standard.Models using Newtonsoft.Json.Converters; /// - /// AppliedCreditNote. + /// AppliedCreditNoteData. /// - public class AppliedCreditNote + public class AppliedCreditNoteData { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public AppliedCreditNote() + public AppliedCreditNoteData() { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// uid. /// number. - public AppliedCreditNote( + public AppliedCreditNoteData( string uid = null, string number = null) { @@ -60,7 +60,7 @@ public override string ToString() this.ToString(toStringOutput); - return $"AppliedCreditNote : ({string.Join(", ", toStringOutput)})"; + return $"AppliedCreditNoteData : ({string.Join(", ", toStringOutput)})"; } /// @@ -75,7 +75,7 @@ public override bool Equals(object obj) { return true; } - return obj is AppliedCreditNote other && ((this.Uid == null && other.Uid == null) || (this.Uid?.Equals(other.Uid) == true)) && + return obj is AppliedCreditNoteData other && ((this.Uid == null && other.Uid == null) || (this.Uid?.Equals(other.Uid) == true)) && ((this.Number == null && other.Number == null) || (this.Number?.Equals(other.Number) == true)); } diff --git a/AdvancedBilling.Standard/Models/ApplyCreditNoteEventData.cs b/AdvancedBilling.Standard/Models/ApplyCreditNoteEventData.cs index 0c46fca..bd36ce3 100644 --- a/AdvancedBilling.Standard/Models/ApplyCreditNoteEventData.cs +++ b/AdvancedBilling.Standard/Models/ApplyCreditNoteEventData.cs @@ -51,7 +51,7 @@ public ApplyCreditNoteEventData( string memo = null, string role = null, bool? consolidatedInvoice = null, - List appliedCreditNotes = null) + List appliedCreditNotes = null) { this.Uid = uid; this.CreditNoteNumber = creditNoteNumber; @@ -131,7 +131,7 @@ public ApplyCreditNoteEventData( /// List of credit notes applied to children invoices (if consolidated invoice) /// [JsonProperty("applied_credit_notes", NullValueHandling = NullValueHandling.Ignore)] - public List AppliedCreditNotes { get; set; } + public List AppliedCreditNotes { get; set; } /// public override string ToString() diff --git a/AdvancedBilling.Standard/Models/BankAccount.cs b/AdvancedBilling.Standard/Models/BankAccount.cs deleted file mode 100644 index 7139d31..0000000 --- a/AdvancedBilling.Standard/Models/BankAccount.cs +++ /dev/null @@ -1,351 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// BankAccount. - /// - public class BankAccount - { - private string customerVaultToken; - private Dictionary shouldSerialize = new Dictionary - { - { "customer_vault_token", false }, - }; - - /// - /// Initializes a new instance of the class. - /// - public BankAccount() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// id. - /// first_name. - /// last_name. - /// customer_id. - /// current_vault. - /// vault_token. - /// billing_address. - /// billing_city. - /// billing_state. - /// billing_zip. - /// billing_country. - /// customer_vault_token. - /// billing_address_2. - /// bank_name. - /// masked_bank_routing_number. - /// masked_bank_account_number. - /// bank_account_type. - /// bank_account_holder_type. - /// payment_type. - /// verified. - /// site_gateway_setting_id. - /// gateway_handle. - public BankAccount( - int? id = null, - string firstName = null, - string lastName = null, - int? customerId = null, - Models.BankAccountVault? currentVault = null, - string vaultToken = null, - string billingAddress = null, - string billingCity = null, - string billingState = null, - string billingZip = null, - string billingCountry = null, - string customerVaultToken = null, - string billingAddress2 = null, - string bankName = null, - string maskedBankRoutingNumber = null, - string maskedBankAccountNumber = null, - string bankAccountType = null, - string bankAccountHolderType = null, - string paymentType = null, - bool? verified = false, - int? siteGatewaySettingId = null, - string gatewayHandle = null) - { - this.Id = id; - this.FirstName = firstName; - this.LastName = lastName; - this.CustomerId = customerId; - this.CurrentVault = currentVault; - this.VaultToken = vaultToken; - this.BillingAddress = billingAddress; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; - if (customerVaultToken != null) - { - this.CustomerVaultToken = customerVaultToken; - } - - this.BillingAddress2 = billingAddress2; - this.BankName = bankName; - this.MaskedBankRoutingNumber = maskedBankRoutingNumber; - this.MaskedBankAccountNumber = maskedBankAccountNumber; - this.BankAccountType = bankAccountType; - this.BankAccountHolderType = bankAccountHolderType; - this.PaymentType = paymentType; - this.Verified = verified; - this.SiteGatewaySettingId = siteGatewaySettingId; - this.GatewayHandle = gatewayHandle; - } - - /// - /// Gets or sets Id. - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// Gets or sets FirstName. - /// - [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - /// - /// Gets or sets LastName. - /// - [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - /// - /// Gets or sets CustomerId. - /// - [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] - public int? CustomerId { get; set; } - - /// - /// The vault that stores the payment profile with the provided vault_token. - /// - [JsonProperty("current_vault", NullValueHandling = NullValueHandling.Ignore)] - public Models.BankAccountVault? CurrentVault { get; set; } - - /// - /// Gets or sets VaultToken. - /// - [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string VaultToken { get; set; } - - /// - /// Gets or sets BillingAddress. - /// - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } - - /// - /// Gets or sets BillingCity. - /// - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } - - /// - /// Gets or sets BillingState. - /// - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } - - /// - /// Gets or sets BillingZip. - /// - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } - - /// - /// Gets or sets BillingCountry. - /// - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } - - /// - /// Gets or sets CustomerVaultToken. - /// - [JsonProperty("customer_vault_token")] - public string CustomerVaultToken - { - get - { - return this.customerVaultToken; - } - - set - { - this.shouldSerialize["customer_vault_token"] = true; - this.customerVaultToken = value; - } - } - - /// - /// Gets or sets BillingAddress2. - /// - [JsonProperty("billing_address_2", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress2 { get; set; } - - /// - /// Gets or sets BankName. - /// - [JsonProperty("bank_name", NullValueHandling = NullValueHandling.Ignore)] - public string BankName { get; set; } - - /// - /// Gets or sets MaskedBankRoutingNumber. - /// - [JsonProperty("masked_bank_routing_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankRoutingNumber { get; set; } - - /// - /// Gets or sets MaskedBankAccountNumber. - /// - [JsonProperty("masked_bank_account_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankAccountNumber { get; set; } - - /// - /// Gets or sets BankAccountType. - /// - [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } - - /// - /// Gets or sets BankAccountHolderType. - /// - [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } - - /// - /// Gets or sets PaymentType. - /// - [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } - - /// - /// denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account - /// - [JsonProperty("verified", NullValueHandling = NullValueHandling.Ignore)] - public bool? Verified { get; set; } - - /// - /// Gets or sets SiteGatewaySettingId. - /// - [JsonProperty("site_gateway_setting_id", NullValueHandling = NullValueHandling.Ignore)] - public int? SiteGatewaySettingId { get; set; } - - /// - /// Gets or sets GatewayHandle. - /// - [JsonProperty("gateway_handle", NullValueHandling = NullValueHandling.Ignore)] - public string GatewayHandle { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"BankAccount : ({string.Join(", ", toStringOutput)})"; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetCustomerVaultToken() - { - this.shouldSerialize["customer_vault_token"] = false; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeCustomerVaultToken() - { - return this.shouldSerialize["customer_vault_token"]; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is BankAccount other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && - ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && - ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && - ((this.CurrentVault == null && other.CurrentVault == null) || (this.CurrentVault?.Equals(other.CurrentVault) == true)) && - ((this.VaultToken == null && other.VaultToken == null) || (this.VaultToken?.Equals(other.VaultToken) == true)) && - ((this.BillingAddress == null && other.BillingAddress == null) || (this.BillingAddress?.Equals(other.BillingAddress) == true)) && - ((this.BillingCity == null && other.BillingCity == null) || (this.BillingCity?.Equals(other.BillingCity) == true)) && - ((this.BillingState == null && other.BillingState == null) || (this.BillingState?.Equals(other.BillingState) == true)) && - ((this.BillingZip == null && other.BillingZip == null) || (this.BillingZip?.Equals(other.BillingZip) == true)) && - ((this.BillingCountry == null && other.BillingCountry == null) || (this.BillingCountry?.Equals(other.BillingCountry) == true)) && - ((this.CustomerVaultToken == null && other.CustomerVaultToken == null) || (this.CustomerVaultToken?.Equals(other.CustomerVaultToken) == true)) && - ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && - ((this.BankName == null && other.BankName == null) || (this.BankName?.Equals(other.BankName) == true)) && - ((this.MaskedBankRoutingNumber == null && other.MaskedBankRoutingNumber == null) || (this.MaskedBankRoutingNumber?.Equals(other.MaskedBankRoutingNumber) == true)) && - ((this.MaskedBankAccountNumber == null && other.MaskedBankAccountNumber == null) || (this.MaskedBankAccountNumber?.Equals(other.MaskedBankAccountNumber) == true)) && - ((this.BankAccountType == null && other.BankAccountType == null) || (this.BankAccountType?.Equals(other.BankAccountType) == true)) && - ((this.BankAccountHolderType == null && other.BankAccountHolderType == null) || (this.BankAccountHolderType?.Equals(other.BankAccountHolderType) == true)) && - ((this.PaymentType == null && other.PaymentType == null) || (this.PaymentType?.Equals(other.PaymentType) == true)) && - ((this.Verified == null && other.Verified == null) || (this.Verified?.Equals(other.Verified) == true)) && - ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && - ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); - toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); - toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId.ToString())}"); - toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); - toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); - toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); - toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); - toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); - toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); - toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); - toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); - toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.BankName = {(this.BankName == null ? "null" : this.BankName)}"); - toStringOutput.Add($"this.MaskedBankRoutingNumber = {(this.MaskedBankRoutingNumber == null ? "null" : this.MaskedBankRoutingNumber)}"); - toStringOutput.Add($"this.MaskedBankAccountNumber = {(this.MaskedBankAccountNumber == null ? "null" : this.MaskedBankAccountNumber)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); - toStringOutput.Add($"this.Verified = {(this.Verified == null ? "null" : this.Verified.ToString())}"); - toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); - toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/BankAccountAttributes.cs b/AdvancedBilling.Standard/Models/BankAccountAttributes.cs index 0b01b90..f3f29e0 100644 --- a/AdvancedBilling.Standard/Models/BankAccountAttributes.cs +++ b/AdvancedBilling.Standard/Models/BankAccountAttributes.cs @@ -48,11 +48,11 @@ public BankAccountAttributes( string bankName = null, string bankRoutingNumber = null, string bankAccountNumber = null, - string bankAccountType = null, + Models.BankAccountType? bankAccountType = Models.BankAccountType.Checking, string bankBranchCode = null, string bankIban = null, - string bankAccountHolderType = null, - string paymentType = null, + Models.BankAccountHolderType? bankAccountHolderType = null, + Models.PaymentType? paymentType = Models.PaymentType.CreditCard, Models.BankAccountVault? currentVault = null, string vaultToken = null, string customerVaultToken = null) @@ -96,10 +96,10 @@ public BankAccountAttributes( public string BankAccountNumber { get; set; } /// - /// Gets or sets BankAccountType. + /// Defaults to checking /// [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } + public Models.BankAccountType? BankAccountType { get; set; } /// /// (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided @@ -114,16 +114,16 @@ public BankAccountAttributes( public string BankIban { get; set; } /// - /// Gets or sets BankAccountHolderType. + /// Defaults to personal /// [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } + public Models.BankAccountHolderType? BankAccountHolderType { get; set; } /// /// Gets or sets PaymentType. /// [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } + public Models.PaymentType? PaymentType { get; set; } /// /// The vault that stores the payment profile with the provided vault_token. @@ -189,11 +189,11 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.BankName = {(this.BankName == null ? "null" : this.BankName)}"); toStringOutput.Add($"this.BankRoutingNumber = {(this.BankRoutingNumber == null ? "null" : this.BankRoutingNumber)}"); toStringOutput.Add($"this.BankAccountNumber = {(this.BankAccountNumber == null ? "null" : this.BankAccountNumber)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); + toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType.ToString())}"); toStringOutput.Add($"this.BankBranchCode = {(this.BankBranchCode == null ? "null" : this.BankBranchCode)}"); toStringOutput.Add($"this.BankIban = {(this.BankIban == null ? "null" : this.BankIban)}"); - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); + toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType.ToString())}"); + toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType.ToString())}"); toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); diff --git a/AdvancedBilling.Standard/Models/HolderType.cs b/AdvancedBilling.Standard/Models/BankAccountHolderType.cs similarity index 84% rename from AdvancedBilling.Standard/Models/HolderType.cs rename to AdvancedBilling.Standard/Models/BankAccountHolderType.cs index 4844ede..ac50471 100644 --- a/AdvancedBilling.Standard/Models/HolderType.cs +++ b/AdvancedBilling.Standard/Models/BankAccountHolderType.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Models @@ -13,11 +13,11 @@ namespace AdvancedBilling.Standard.Models using Newtonsoft.Json; /// - /// HolderType. + /// BankAccountHolderType. /// [JsonConverter(typeof(StringEnumConverter))] - public enum HolderType + public enum BankAccountHolderType { /// /// Personal. diff --git a/AdvancedBilling.Standard/Models/BankAccountPaymentProfile.cs b/AdvancedBilling.Standard/Models/BankAccountPaymentProfile.cs index ba6ced8..f6cce31 100644 --- a/AdvancedBilling.Standard/Models/BankAccountPaymentProfile.cs +++ b/AdvancedBilling.Standard/Models/BankAccountPaymentProfile.cs @@ -21,11 +21,23 @@ namespace AdvancedBilling.Standard.Models /// public class BankAccountPaymentProfile { + private string billingAddress; + private string billingCity; + private string billingState; + private string billingZip; + private string billingCountry; private string customerVaultToken; + private string billingAddress2; private string gatewayHandle; private Dictionary shouldSerialize = new Dictionary { + { "billing_address", false }, + { "billing_city", false }, + { "billing_state", false }, + { "billing_zip", false }, + { "billing_country", false }, { "customer_vault_token", false }, + { "billing_address_2", false }, { "gateway_handle", false }, }; @@ -78,9 +90,9 @@ public BankAccountPaymentProfile( string customerVaultToken = null, string billingAddress2 = null, string bankName = null, - string bankAccountType = null, - string bankAccountHolderType = null, - string paymentType = null, + Models.BankAccountType? bankAccountType = Models.BankAccountType.Checking, + Models.BankAccountHolderType? bankAccountHolderType = null, + Models.PaymentType? paymentType = Models.PaymentType.CreditCard, bool? verified = false, int? siteGatewaySettingId = null, string gatewayHandle = null) @@ -91,17 +103,41 @@ public BankAccountPaymentProfile( this.CustomerId = customerId; this.CurrentVault = currentVault; this.VaultToken = vaultToken; - this.BillingAddress = billingAddress; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; + if (billingAddress != null) + { + this.BillingAddress = billingAddress; + } + + if (billingCity != null) + { + this.BillingCity = billingCity; + } + + if (billingState != null) + { + this.BillingState = billingState; + } + + if (billingZip != null) + { + this.BillingZip = billingZip; + } + + if (billingCountry != null) + { + this.BillingCountry = billingCountry; + } + if (customerVaultToken != null) { this.CustomerVaultToken = customerVaultToken; } - this.BillingAddress2 = billingAddress2; + if (billingAddress2 != null) + { + this.BillingAddress2 = billingAddress2; + } + this.BankName = bankName; this.MaskedBankRoutingNumber = maskedBankRoutingNumber; this.MaskedBankAccountNumber = maskedBankAccountNumber; @@ -118,27 +154,27 @@ public BankAccountPaymentProfile( } /// - /// Gets or sets Id. + /// The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer /// [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public int? Id { get; set; } /// - /// Gets or sets FirstName. + /// The first name of the bank account holder /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] public string FirstName { get; set; } /// - /// Gets or sets LastName. + /// The last name of the bank account holder /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] public string LastName { get; set; } /// - /// Gets or sets CustomerId. + /// The Chargify-assigned id for the customer record to which the bank account belongs /// [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] public int? CustomerId { get; set; } @@ -150,49 +186,109 @@ public BankAccountPaymentProfile( public Models.BankAccountVault? CurrentVault { get; set; } /// - /// Gets or sets VaultToken. + /// The “token” provided by your vault storage for an already stored payment profile /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] public string VaultToken { get; set; } /// - /// Gets or sets BillingAddress. + /// The current billing street address for the bank account /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } + [JsonProperty("billing_address")] + public string BillingAddress + { + get + { + return this.billingAddress; + } + + set + { + this.shouldSerialize["billing_address"] = true; + this.billingAddress = value; + } + } /// - /// Gets or sets BillingCity. + /// The current billing address city for the bank account /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } + [JsonProperty("billing_city")] + public string BillingCity + { + get + { + return this.billingCity; + } + + set + { + this.shouldSerialize["billing_city"] = true; + this.billingCity = value; + } + } /// - /// Gets or sets BillingState. + /// The current billing address state for the bank account /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } + [JsonProperty("billing_state")] + public string BillingState + { + get + { + return this.billingState; + } + + set + { + this.shouldSerialize["billing_state"] = true; + this.billingState = value; + } + } /// - /// Gets or sets BillingZip. + /// The current billing address zip code for the bank account /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } + [JsonProperty("billing_zip")] + public string BillingZip + { + get + { + return this.billingZip; + } + + set + { + this.shouldSerialize["billing_zip"] = true; + this.billingZip = value; + } + } /// - /// Gets or sets BillingCountry. + /// The current billing address country for the bank account /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } + [JsonProperty("billing_country")] + public string BillingCountry + { + get + { + return this.billingCountry; + } + + set + { + this.shouldSerialize["billing_country"] = true; + this.billingCountry = value; + } + } /// - /// Gets or sets CustomerVaultToken. + /// (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("customer_vault_token")] @@ -211,21 +307,33 @@ public string CustomerVaultToken } /// - /// Gets or sets BillingAddress2. + /// The current billing street address, second line, for the bank account /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_address_2", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress2 { get; set; } + [JsonProperty("billing_address_2")] + public string BillingAddress2 + { + get + { + return this.billingAddress2; + } + + set + { + this.shouldSerialize["billing_address_2"] = true; + this.billingAddress2 = value; + } + } /// - /// Gets or sets BankName. + /// The bank where the account resides /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("bank_name", NullValueHandling = NullValueHandling.Ignore)] public string BankName { get; set; } /// - /// Gets or sets MaskedBankRoutingNumber. + /// A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account /// [JsonConverter(typeof(JsonStringConverter), true)] [JsonProperty("masked_bank_routing_number")] @@ -233,7 +341,7 @@ public string CustomerVaultToken public string MaskedBankRoutingNumber { get; set; } /// - /// Gets or sets MaskedBankAccountNumber. + /// A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) /// [JsonConverter(typeof(JsonStringConverter), true)] [JsonProperty("masked_bank_account_number")] @@ -241,25 +349,22 @@ public string CustomerVaultToken public string MaskedBankAccountNumber { get; set; } /// - /// Gets or sets BankAccountType. + /// Defaults to checking /// - [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } + public Models.BankAccountType? BankAccountType { get; set; } /// - /// Gets or sets BankAccountHolderType. + /// Defaults to personal /// - [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } + public Models.BankAccountHolderType? BankAccountHolderType { get; set; } /// /// Gets or sets PaymentType. /// - [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } + public Models.PaymentType? PaymentType { get; set; } /// /// denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account @@ -302,6 +407,46 @@ public override string ToString() return $"BankAccountPaymentProfile : ({string.Join(", ", toStringOutput)})"; } + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingAddress() + { + this.shouldSerialize["billing_address"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingCity() + { + this.shouldSerialize["billing_city"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingState() + { + this.shouldSerialize["billing_state"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingZip() + { + this.shouldSerialize["billing_zip"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingCountry() + { + this.shouldSerialize["billing_country"] = false; + } + /// /// Marks the field to not be serailized. /// @@ -310,6 +455,14 @@ public void UnsetCustomerVaultToken() this.shouldSerialize["customer_vault_token"] = false; } + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingAddress2() + { + this.shouldSerialize["billing_address_2"] = false; + } + /// /// Marks the field to not be serailized. /// @@ -318,6 +471,51 @@ public void UnsetGatewayHandle() this.shouldSerialize["gateway_handle"] = false; } + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingAddress() + { + return this.shouldSerialize["billing_address"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingCity() + { + return this.shouldSerialize["billing_city"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingState() + { + return this.shouldSerialize["billing_state"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingZip() + { + return this.shouldSerialize["billing_zip"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingCountry() + { + return this.shouldSerialize["billing_country"]; + } + /// /// Checks if the field should be serialized or not. /// @@ -327,6 +525,15 @@ public bool ShouldSerializeCustomerVaultToken() return this.shouldSerialize["customer_vault_token"]; } + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingAddress2() + { + return this.shouldSerialize["billing_address_2"]; + } + /// /// Checks if the field should be serialized or not. /// @@ -394,9 +601,9 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.BankName = {(this.BankName == null ? "null" : this.BankName)}"); toStringOutput.Add($"this.MaskedBankRoutingNumber = {(this.MaskedBankRoutingNumber == null ? "null" : this.MaskedBankRoutingNumber)}"); toStringOutput.Add($"this.MaskedBankAccountNumber = {(this.MaskedBankAccountNumber == null ? "null" : this.MaskedBankAccountNumber)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); + toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType.ToString())}"); + toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType.ToString())}"); + toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType.ToString())}"); toStringOutput.Add($"this.Verified = {(this.Verified == null ? "null" : this.Verified.ToString())}"); toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); diff --git a/AdvancedBilling.Standard/Models/BankAccountResponse.cs b/AdvancedBilling.Standard/Models/BankAccountResponse.cs index 27318b8..597e171 100644 --- a/AdvancedBilling.Standard/Models/BankAccountResponse.cs +++ b/AdvancedBilling.Standard/Models/BankAccountResponse.cs @@ -33,7 +33,7 @@ public BankAccountResponse() /// /// payment_profile. public BankAccountResponse( - Models.BankAccount paymentProfile) + Models.BankAccountPaymentProfile paymentProfile) { this.PaymentProfile = paymentProfile; } @@ -42,7 +42,7 @@ public BankAccountResponse( /// Gets or sets PaymentProfile. /// [JsonProperty("payment_profile")] - public Models.BankAccount PaymentProfile { get; set; } + public Models.BankAccountPaymentProfile PaymentProfile { get; set; } /// public override string ToString() diff --git a/AdvancedBilling.Standard/Models/CardType.cs b/AdvancedBilling.Standard/Models/CardType.cs index 3d6469c..6c1c516 100644 --- a/AdvancedBilling.Standard/Models/CardType.cs +++ b/AdvancedBilling.Standard/Models/CardType.cs @@ -19,12 +19,6 @@ namespace AdvancedBilling.Standard.Models [JsonConverter(typeof(StringEnumConverter))] public enum CardType { - /// - /// Bogus. - /// - [EnumMember(Value = "bogus")] - Bogus, - /// /// Visa. /// @@ -37,6 +31,24 @@ public enum CardType [EnumMember(Value = "master")] Master, + /// + /// Elo. + /// + [EnumMember(Value = "elo")] + Elo, + + /// + /// Cabal. + /// + [EnumMember(Value = "cabal")] + Cabal, + + /// + /// Alelo. + /// + [EnumMember(Value = "alelo")] + Alelo, + /// /// Discover. /// @@ -49,6 +61,12 @@ public enum CardType [EnumMember(Value = "american_express")] AmericanExpress, + /// + /// Naranja. + /// + [EnumMember(Value = "naranja")] + Naranja, + /// /// DinersClub. /// @@ -61,18 +79,6 @@ public enum CardType [EnumMember(Value = "jcb")] Jcb, - /// - /// Switch. - /// - [EnumMember(Value = "switch")] - Switch, - - /// - /// Solo. - /// - [EnumMember(Value = "solo")] - Solo, - /// /// Dankort. /// @@ -86,15 +92,147 @@ public enum CardType Maestro, /// - /// Laser. + /// MaestroNoLuhn. /// - [EnumMember(Value = "laser")] - Laser, + [EnumMember(Value = "maestro_no_luhn")] + MaestroNoLuhn, /// /// Forbrugsforeningen. /// [EnumMember(Value = "forbrugsforeningen")] - Forbrugsforeningen + Forbrugsforeningen, + + /// + /// Sodexo. + /// + [EnumMember(Value = "sodexo")] + Sodexo, + + /// + /// Alia. + /// + [EnumMember(Value = "alia")] + Alia, + + /// + /// Vr. + /// + [EnumMember(Value = "vr")] + Vr, + + /// + /// Unionpay. + /// + [EnumMember(Value = "unionpay")] + Unionpay, + + /// + /// Carnet. + /// + [EnumMember(Value = "carnet")] + Carnet, + + /// + /// CartesBancaires. + /// + [EnumMember(Value = "cartes_bancaires")] + CartesBancaires, + + /// + /// Olimpica. + /// + [EnumMember(Value = "olimpica")] + Olimpica, + + /// + /// Creditel. + /// + [EnumMember(Value = "creditel")] + Creditel, + + /// + /// Confiable. + /// + [EnumMember(Value = "confiable")] + Confiable, + + /// + /// Synchrony. + /// + [EnumMember(Value = "synchrony")] + Synchrony, + + /// + /// Routex. + /// + [EnumMember(Value = "routex")] + Routex, + + /// + /// Mada. + /// + [EnumMember(Value = "mada")] + Mada, + + /// + /// BpPlus. + /// + [EnumMember(Value = "bp_plus")] + BpPlus, + + /// + /// Passcard. + /// + [EnumMember(Value = "passcard")] + Passcard, + + /// + /// Edenred. + /// + [EnumMember(Value = "edenred")] + Edenred, + + /// + /// Anda. + /// + [EnumMember(Value = "anda")] + Anda, + + /// + /// Tarjetad. + /// + [EnumMember(Value = "tarjeta-d")] + Tarjetad, + + /// + /// Hipercard. + /// + [EnumMember(Value = "hipercard")] + Hipercard, + + /// + /// Bogus. + /// + [EnumMember(Value = "bogus")] + Bogus, + + /// + /// Switch. + /// + [EnumMember(Value = "switch")] + Switch, + + /// + /// Solo. + /// + [EnumMember(Value = "solo")] + Solo, + + /// + /// Laser. + /// + [EnumMember(Value = "laser")] + Laser } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/CardType1.cs b/AdvancedBilling.Standard/Models/CardType1.cs deleted file mode 100644 index 5cb7b14..0000000 --- a/AdvancedBilling.Standard/Models/CardType1.cs +++ /dev/null @@ -1,220 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Runtime.Serialization; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - - /// - /// CardType1. - /// - - [JsonConverter(typeof(StringEnumConverter))] - public enum CardType1 - { - /// - /// Visa. - /// - [EnumMember(Value = "visa")] - Visa, - - /// - /// Master. - /// - [EnumMember(Value = "master")] - Master, - - /// - /// Elo. - /// - [EnumMember(Value = "elo")] - Elo, - - /// - /// Cabal. - /// - [EnumMember(Value = "cabal")] - Cabal, - - /// - /// Alelo. - /// - [EnumMember(Value = "alelo")] - Alelo, - - /// - /// Discover. - /// - [EnumMember(Value = "discover")] - Discover, - - /// - /// AmericanExpress. - /// - [EnumMember(Value = "american_express")] - AmericanExpress, - - /// - /// Naranja. - /// - [EnumMember(Value = "naranja")] - Naranja, - - /// - /// DinersClub. - /// - [EnumMember(Value = "diners_club")] - DinersClub, - - /// - /// Jcb. - /// - [EnumMember(Value = "jcb")] - Jcb, - - /// - /// Dankort. - /// - [EnumMember(Value = "dankort")] - Dankort, - - /// - /// Maestro. - /// - [EnumMember(Value = "maestro")] - Maestro, - - /// - /// MaestroNoLuhn. - /// - [EnumMember(Value = "maestro_no_luhn")] - MaestroNoLuhn, - - /// - /// Forbrugsforeningen. - /// - [EnumMember(Value = "forbrugsforeningen")] - Forbrugsforeningen, - - /// - /// Sodexo. - /// - [EnumMember(Value = "sodexo")] - Sodexo, - - /// - /// Alia. - /// - [EnumMember(Value = "alia")] - Alia, - - /// - /// Vr. - /// - [EnumMember(Value = "vr")] - Vr, - - /// - /// Unionpay. - /// - [EnumMember(Value = "unionpay")] - Unionpay, - - /// - /// Carnet. - /// - [EnumMember(Value = "carnet")] - Carnet, - - /// - /// CartesBancaires. - /// - [EnumMember(Value = "cartes_bancaires")] - CartesBancaires, - - /// - /// Olimpica. - /// - [EnumMember(Value = "olimpica")] - Olimpica, - - /// - /// Creditel. - /// - [EnumMember(Value = "creditel")] - Creditel, - - /// - /// Confiable. - /// - [EnumMember(Value = "confiable")] - Confiable, - - /// - /// Synchrony. - /// - [EnumMember(Value = "synchrony")] - Synchrony, - - /// - /// Routex. - /// - [EnumMember(Value = "routex")] - Routex, - - /// - /// Mada. - /// - [EnumMember(Value = "mada")] - Mada, - - /// - /// BpPlus. - /// - [EnumMember(Value = "bp_plus")] - BpPlus, - - /// - /// Passcard. - /// - [EnumMember(Value = "passcard")] - Passcard, - - /// - /// Edenred. - /// - [EnumMember(Value = "edenred")] - Edenred, - - /// - /// Anda. - /// - [EnumMember(Value = "anda")] - Anda, - - /// - /// Tarjetad. - /// - [EnumMember(Value = "tarjeta-d")] - Tarjetad, - - /// - /// Hipercard. - /// - [EnumMember(Value = "hipercard")] - Hipercard, - - /// - /// Bogus. - /// - [EnumMember(Value = "bogus")] - Bogus - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Component.cs b/AdvancedBilling.Standard/Models/Component.cs index 0f7dacc..1d3ea0c 100644 --- a/AdvancedBilling.Standard/Models/Component.cs +++ b/AdvancedBilling.Standard/Models/Component.cs @@ -27,6 +27,8 @@ public class Component private string unitPrice; private long? pricePerUnitInCents; private string description; + private int? defaultPricePointId; + private List overagePrices; private List prices; private string taxCode; private Models.CreditType? upgradeCharge; @@ -42,6 +44,8 @@ public class Component { "unit_price", false }, { "price_per_unit_in_cents", false }, { "description", false }, + { "default_price_point_id", false }, + { "overage_prices", false }, { "prices", false }, { "tax_code", false }, { "upgrade_charge", false }, @@ -76,6 +80,7 @@ public Component() /// taxable. /// description. /// default_price_point_id. + /// overage_prices. /// prices. /// price_point_count. /// price_points_url. @@ -110,6 +115,7 @@ public Component( bool? taxable = null, string description = null, int? defaultPricePointId = null, + List overagePrices = null, List prices = null, int? pricePointCount = null, string pricePointsUrl = null, @@ -118,8 +124,8 @@ public Component( bool? recurring = null, Models.CreditType? upgradeCharge = null, Models.CreditType? downgradeCredit = null, - string createdAt = null, - string updatedAt = null, + DateTimeOffset? createdAt = null, + DateTimeOffset? updatedAt = null, string archivedAt = null, bool? hideDateRangeOnInvoice = null, bool? allowFractionalQuantities = null, @@ -163,7 +169,16 @@ public Component( this.Description = description; } - this.DefaultPricePointId = defaultPricePointId; + if (defaultPricePointId != null) + { + this.DefaultPricePointId = defaultPricePointId; + } + + if (overagePrices != null) + { + this.OveragePrices = overagePrices; + } + if (prices != null) { this.Prices = prices; @@ -358,8 +373,38 @@ public string Description /// /// Gets or sets DefaultPricePointId. /// - [JsonProperty("default_price_point_id", NullValueHandling = NullValueHandling.Ignore)] - public int? DefaultPricePointId { get; set; } + [JsonProperty("default_price_point_id")] + public int? DefaultPricePointId + { + get + { + return this.defaultPricePointId; + } + + set + { + this.shouldSerialize["default_price_point_id"] = true; + this.defaultPricePointId = value; + } + } + + /// + /// An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. + /// + [JsonProperty("overage_prices")] + public List OveragePrices + { + get + { + return this.overagePrices; + } + + set + { + this.shouldSerialize["overage_prices"] = true; + this.overagePrices = value; + } + } /// /// An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. @@ -462,14 +507,16 @@ public Models.CreditType? DowngradeCredit /// /// Timestamp indicating when this component was created /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("created_at", NullValueHandling = NullValueHandling.Ignore)] - public string CreatedAt { get; set; } + public DateTimeOffset? CreatedAt { get; set; } /// /// Timestamp indicating when this component was updated /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("updated_at", NullValueHandling = NullValueHandling.Ignore)] - public string UpdatedAt { get; set; } + public DateTimeOffset? UpdatedAt { get; set; } /// /// Timestamp indicating when this component was archived @@ -623,6 +670,22 @@ public void UnsetDescription() this.shouldSerialize["description"] = false; } + /// + /// Marks the field to not be serailized. + /// + public void UnsetDefaultPricePointId() + { + this.shouldSerialize["default_price_point_id"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetOveragePrices() + { + this.shouldSerialize["overage_prices"] = false; + } + /// /// Marks the field to not be serailized. /// @@ -732,6 +795,24 @@ public bool ShouldSerializeDescription() return this.shouldSerialize["description"]; } + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeDefaultPricePointId() + { + return this.shouldSerialize["default_price_point_id"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeOveragePrices() + { + return this.shouldSerialize["overage_prices"]; + } + /// /// Checks if the field should be serialized or not. /// @@ -830,6 +911,7 @@ public override bool Equals(object obj) ((this.Taxable == null && other.Taxable == null) || (this.Taxable?.Equals(other.Taxable) == true)) && ((this.Description == null && other.Description == null) || (this.Description?.Equals(other.Description) == true)) && ((this.DefaultPricePointId == null && other.DefaultPricePointId == null) || (this.DefaultPricePointId?.Equals(other.DefaultPricePointId) == true)) && + ((this.OveragePrices == null && other.OveragePrices == null) || (this.OveragePrices?.Equals(other.OveragePrices) == true)) && ((this.Prices == null && other.Prices == null) || (this.Prices?.Equals(other.Prices) == true)) && ((this.PricePointCount == null && other.PricePointCount == null) || (this.PricePointCount?.Equals(other.PricePointCount) == true)) && ((this.PricePointsUrl == null && other.PricePointsUrl == null) || (this.PricePointsUrl?.Equals(other.PricePointsUrl) == true)) && @@ -871,6 +953,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.Taxable = {(this.Taxable == null ? "null" : this.Taxable.ToString())}"); toStringOutput.Add($"this.Description = {(this.Description == null ? "null" : this.Description)}"); toStringOutput.Add($"this.DefaultPricePointId = {(this.DefaultPricePointId == null ? "null" : this.DefaultPricePointId.ToString())}"); + toStringOutput.Add($"this.OveragePrices = {(this.OveragePrices == null ? "null" : $"[{string.Join(", ", this.OveragePrices)} ]")}"); toStringOutput.Add($"this.Prices = {(this.Prices == null ? "null" : $"[{string.Join(", ", this.Prices)} ]")}"); toStringOutput.Add($"this.PricePointCount = {(this.PricePointCount == null ? "null" : this.PricePointCount.ToString())}"); toStringOutput.Add($"this.PricePointsUrl = {(this.PricePointsUrl == null ? "null" : this.PricePointsUrl)}"); @@ -879,8 +962,8 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.Recurring = {(this.Recurring == null ? "null" : this.Recurring.ToString())}"); toStringOutput.Add($"this.UpgradeCharge = {(this.UpgradeCharge == null ? "null" : this.UpgradeCharge.ToString())}"); toStringOutput.Add($"this.DowngradeCredit = {(this.DowngradeCredit == null ? "null" : this.DowngradeCredit.ToString())}"); - toStringOutput.Add($"this.CreatedAt = {(this.CreatedAt == null ? "null" : this.CreatedAt)}"); - toStringOutput.Add($"this.UpdatedAt = {(this.UpdatedAt == null ? "null" : this.UpdatedAt)}"); + toStringOutput.Add($"this.CreatedAt = {(this.CreatedAt == null ? "null" : this.CreatedAt.ToString())}"); + toStringOutput.Add($"this.UpdatedAt = {(this.UpdatedAt == null ? "null" : this.UpdatedAt.ToString())}"); toStringOutput.Add($"this.ArchivedAt = {(this.ArchivedAt == null ? "null" : this.ArchivedAt)}"); toStringOutput.Add($"this.HideDateRangeOnInvoice = {(this.HideDateRangeOnInvoice == null ? "null" : this.HideDateRangeOnInvoice.ToString())}"); toStringOutput.Add($"this.AllowFractionalQuantities = {(this.AllowFractionalQuantities == null ? "null" : this.AllowFractionalQuantities.ToString())}"); diff --git a/AdvancedBilling.Standard/Models/ComponentCurrencyPrice.cs b/AdvancedBilling.Standard/Models/ComponentCurrencyPrice.cs new file mode 100644 index 0000000..e8efa9b --- /dev/null +++ b/AdvancedBilling.Standard/Models/ComponentCurrencyPrice.cs @@ -0,0 +1,136 @@ +// +// Copyright (c) APIMatic. All rights reserved. +// +namespace AdvancedBilling.Standard.Models +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using APIMatic.Core.Utilities.Converters; + using AdvancedBilling.Standard; + using AdvancedBilling.Standard.Utilities; + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + + /// + /// ComponentCurrencyPrice. + /// + public class ComponentCurrencyPrice + { + /// + /// Initializes a new instance of the class. + /// + public ComponentCurrencyPrice() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// id. + /// currency. + /// price. + /// formatted_price. + /// price_id. + /// price_point_id. + public ComponentCurrencyPrice( + int? id = null, + string currency = null, + string price = null, + string formattedPrice = null, + int? priceId = null, + int? pricePointId = null) + { + this.Id = id; + this.Currency = currency; + this.Price = price; + this.FormattedPrice = formattedPrice; + this.PriceId = priceId; + this.PricePointId = pricePointId; + } + + /// + /// Gets or sets Id. + /// + [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] + public int? Id { get; set; } + + /// + /// Gets or sets Currency. + /// + [JsonProperty("currency", NullValueHandling = NullValueHandling.Ignore)] + public string Currency { get; set; } + + /// + /// Gets or sets Price. + /// + [JsonProperty("price", NullValueHandling = NullValueHandling.Ignore)] + public string Price { get; set; } + + /// + /// Gets or sets FormattedPrice. + /// + [JsonProperty("formatted_price", NullValueHandling = NullValueHandling.Ignore)] + public string FormattedPrice { get; set; } + + /// + /// Gets or sets PriceId. + /// + [JsonProperty("price_id", NullValueHandling = NullValueHandling.Ignore)] + public int? PriceId { get; set; } + + /// + /// Gets or sets PricePointId. + /// + [JsonProperty("price_point_id", NullValueHandling = NullValueHandling.Ignore)] + public int? PricePointId { get; set; } + + /// + public override string ToString() + { + var toStringOutput = new List(); + + this.ToString(toStringOutput); + + return $"ComponentCurrencyPrice : ({string.Join(", ", toStringOutput)})"; + } + + /// + public override bool Equals(object obj) + { + if (obj == null) + { + return false; + } + + if (obj == this) + { + return true; + } + return obj is ComponentCurrencyPrice other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && + ((this.Currency == null && other.Currency == null) || (this.Currency?.Equals(other.Currency) == true)) && + ((this.Price == null && other.Price == null) || (this.Price?.Equals(other.Price) == true)) && + ((this.FormattedPrice == null && other.FormattedPrice == null) || (this.FormattedPrice?.Equals(other.FormattedPrice) == true)) && + ((this.PriceId == null && other.PriceId == null) || (this.PriceId?.Equals(other.PriceId) == true)) && + ((this.PricePointId == null && other.PricePointId == null) || (this.PricePointId?.Equals(other.PricePointId) == true)); + } + + /// + /// ToString overload. + /// + /// List of strings. + protected void ToString(List toStringOutput) + { + toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); + toStringOutput.Add($"this.Currency = {(this.Currency == null ? "null" : this.Currency)}"); + toStringOutput.Add($"this.Price = {(this.Price == null ? "null" : this.Price)}"); + toStringOutput.Add($"this.FormattedPrice = {(this.FormattedPrice == null ? "null" : this.FormattedPrice)}"); + toStringOutput.Add($"this.PriceId = {(this.PriceId == null ? "null" : this.PriceId.ToString())}"); + toStringOutput.Add($"this.PricePointId = {(this.PricePointId == null ? "null" : this.PricePointId.ToString())}"); + } + } +} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/ListPaymentProfilesResponse.cs b/AdvancedBilling.Standard/Models/ComponentCurrencyPricesResponse.cs similarity index 52% rename from AdvancedBilling.Standard/Models/ListPaymentProfilesResponse.cs rename to AdvancedBilling.Standard/Models/ComponentCurrencyPricesResponse.cs index b4cb772..633d853 100644 --- a/AdvancedBilling.Standard/Models/ListPaymentProfilesResponse.cs +++ b/AdvancedBilling.Standard/Models/ComponentCurrencyPricesResponse.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Models @@ -17,32 +17,32 @@ namespace AdvancedBilling.Standard.Models using Newtonsoft.Json.Converters; /// - /// ListPaymentProfilesResponse. + /// ComponentCurrencyPricesResponse. /// - public class ListPaymentProfilesResponse + public class ComponentCurrencyPricesResponse { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public ListPaymentProfilesResponse() + public ComponentCurrencyPricesResponse() { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// payment_profile. - public ListPaymentProfilesResponse( - Models.ListPaymentProfileItem paymentProfile = null) + /// currency_prices. + public ComponentCurrencyPricesResponse( + List currencyPrices) { - this.PaymentProfile = paymentProfile; + this.CurrencyPrices = currencyPrices; } /// - /// Gets or sets PaymentProfile. + /// Gets or sets CurrencyPrices. /// - [JsonProperty("payment_profile", NullValueHandling = NullValueHandling.Ignore)] - public Models.ListPaymentProfileItem PaymentProfile { get; set; } + [JsonProperty("currency_prices")] + public List CurrencyPrices { get; set; } /// public override string ToString() @@ -51,7 +51,7 @@ public override string ToString() this.ToString(toStringOutput); - return $"ListPaymentProfilesResponse : ({string.Join(", ", toStringOutput)})"; + return $"ComponentCurrencyPricesResponse : ({string.Join(", ", toStringOutput)})"; } /// @@ -66,7 +66,7 @@ public override bool Equals(object obj) { return true; } - return obj is ListPaymentProfilesResponse other && ((this.PaymentProfile == null && other.PaymentProfile == null) || (this.PaymentProfile?.Equals(other.PaymentProfile) == true)); + return obj is ComponentCurrencyPricesResponse other && ((this.CurrencyPrices == null && other.CurrencyPrices == null) || (this.CurrencyPrices?.Equals(other.CurrencyPrices) == true)); } /// @@ -75,7 +75,7 @@ public override bool Equals(object obj) /// List of strings. protected void ToString(List toStringOutput) { - toStringOutput.Add($"this.PaymentProfile = {(this.PaymentProfile == null ? "null" : this.PaymentProfile.ToString())}"); + toStringOutput.Add($"this.CurrencyPrices = {(this.CurrencyPrices == null ? "null" : $"[{string.Join(", ", this.CurrencyPrices)} ]")}"); } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/ComponentKindPath.cs b/AdvancedBilling.Standard/Models/ComponentKindPath.cs deleted file mode 100644 index 71d73f5..0000000 --- a/AdvancedBilling.Standard/Models/ComponentKindPath.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Runtime.Serialization; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - - /// - /// ComponentKindPath. - /// - - [JsonConverter(typeof(StringEnumConverter))] - public enum ComponentKindPath - { - /// - /// MeteredComponents. - /// - [EnumMember(Value = "metered_components")] - MeteredComponents, - - /// - /// QuantityBasedComponents. - /// - [EnumMember(Value = "quantity_based_components")] - QuantityBasedComponents, - - /// - /// OnOffComponents. - /// - [EnumMember(Value = "on_off_components")] - OnOffComponents, - - /// - /// PrepaidUsageComponents. - /// - [EnumMember(Value = "prepaid_usage_components")] - PrepaidUsageComponents, - - /// - /// EventBasedComponents. - /// - [EnumMember(Value = "event_based_components")] - EventBasedComponents - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/ComponentPricePoint.cs b/AdvancedBilling.Standard/Models/ComponentPricePoint.cs index 23d3f8b..fa217a0 100644 --- a/AdvancedBilling.Standard/Models/ComponentPricePoint.cs +++ b/AdvancedBilling.Standard/Models/ComponentPricePoint.cs @@ -12,6 +12,7 @@ namespace AdvancedBilling.Standard.Models using System.Threading.Tasks; using APIMatic.Core.Utilities.Converters; using AdvancedBilling.Standard; + using AdvancedBilling.Standard.Models.Containers; using AdvancedBilling.Standard.Utilities; using Newtonsoft.Json; using Newtonsoft.Json.Converters; @@ -21,10 +22,14 @@ namespace AdvancedBilling.Standard.Models /// public class ComponentPricePoint { - private string archivedAt; + private DateTimeOffset? archivedAt; + private int? interval; + private ComponentPricePointIntervalUnit intervalUnit; private Dictionary shouldSerialize = new Dictionary { { "archived_at", false }, + { "interval", false }, + { "interval_unit", false }, }; /// @@ -53,6 +58,7 @@ public ComponentPricePoint() /// tax_included. /// interval. /// interval_unit. + /// currency_prices. public ComponentPricePoint( int? id = null, Models.PricePointType? type = null, @@ -61,15 +67,16 @@ public ComponentPricePoint( Models.PricingScheme? pricingScheme = null, int? componentId = null, string handle = null, - string archivedAt = null, - string createdAt = null, - string updatedAt = null, - List prices = null, + DateTimeOffset? archivedAt = null, + DateTimeOffset? createdAt = null, + DateTimeOffset? updatedAt = null, + List prices = null, bool? useSiteExchangeRate = true, int? subscriptionId = null, bool? taxIncluded = null, int? interval = null, - Models.IntervalUnit? intervalUnit = null) + ComponentPricePointIntervalUnit intervalUnit = null, + List currencyPrices = null) { this.Id = id; this.Type = type; @@ -89,8 +96,17 @@ public ComponentPricePoint( this.UseSiteExchangeRate = useSiteExchangeRate; this.SubscriptionId = subscriptionId; this.TaxIncluded = taxIncluded; - this.Interval = interval; - this.IntervalUnit = intervalUnit; + if (interval != null) + { + this.Interval = interval; + } + + if (intervalUnit != null) + { + this.IntervalUnit = intervalUnit; + } + + this.CurrencyPrices = currencyPrices; } /// @@ -141,8 +157,9 @@ public ComponentPricePoint( /// /// Gets or sets ArchivedAt. /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("archived_at")] - public string ArchivedAt + public DateTimeOffset? ArchivedAt { get { @@ -159,20 +176,22 @@ public string ArchivedAt /// /// Gets or sets CreatedAt. /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("created_at", NullValueHandling = NullValueHandling.Ignore)] - public string CreatedAt { get; set; } + public DateTimeOffset? CreatedAt { get; set; } /// /// Gets or sets UpdatedAt. /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("updated_at", NullValueHandling = NullValueHandling.Ignore)] - public string UpdatedAt { get; set; } + public DateTimeOffset? UpdatedAt { get; set; } /// /// Gets or sets Prices. /// [JsonProperty("prices", NullValueHandling = NullValueHandling.Ignore)] - public List Prices { get; set; } + public List Prices { get; set; } /// /// Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. @@ -195,14 +214,44 @@ public string ArchivedAt /// /// The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. /// - [JsonProperty("interval", NullValueHandling = NullValueHandling.Ignore)] - public int? Interval { get; set; } + [JsonProperty("interval")] + public int? Interval + { + get + { + return this.interval; + } + + set + { + this.shouldSerialize["interval"] = true; + this.interval = value; + } + } /// /// A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. /// - [JsonProperty("interval_unit", NullValueHandling = NullValueHandling.Ignore)] - public Models.IntervalUnit? IntervalUnit { get; set; } + [JsonProperty("interval_unit")] + public ComponentPricePointIntervalUnit IntervalUnit + { + get + { + return this.intervalUnit; + } + + set + { + this.shouldSerialize["interval_unit"] = true; + this.intervalUnit = value; + } + } + + /// + /// An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. + /// + [JsonProperty("currency_prices", NullValueHandling = NullValueHandling.Ignore)] + public List CurrencyPrices { get; set; } /// public override string ToString() @@ -222,6 +271,22 @@ public void UnsetArchivedAt() this.shouldSerialize["archived_at"] = false; } + /// + /// Marks the field to not be serailized. + /// + public void UnsetInterval() + { + this.shouldSerialize["interval"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetIntervalUnit() + { + this.shouldSerialize["interval_unit"] = false; + } + /// /// Checks if the field should be serialized or not. /// @@ -231,6 +296,24 @@ public bool ShouldSerializeArchivedAt() return this.shouldSerialize["archived_at"]; } + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeInterval() + { + return this.shouldSerialize["interval"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeIntervalUnit() + { + return this.shouldSerialize["interval_unit"]; + } + /// public override bool Equals(object obj) { @@ -258,7 +341,8 @@ public override bool Equals(object obj) ((this.SubscriptionId == null && other.SubscriptionId == null) || (this.SubscriptionId?.Equals(other.SubscriptionId) == true)) && ((this.TaxIncluded == null && other.TaxIncluded == null) || (this.TaxIncluded?.Equals(other.TaxIncluded) == true)) && ((this.Interval == null && other.Interval == null) || (this.Interval?.Equals(other.Interval) == true)) && - ((this.IntervalUnit == null && other.IntervalUnit == null) || (this.IntervalUnit?.Equals(other.IntervalUnit) == true)); + ((this.IntervalUnit == null && other.IntervalUnit == null) || (this.IntervalUnit?.Equals(other.IntervalUnit) == true)) && + ((this.CurrencyPrices == null && other.CurrencyPrices == null) || (this.CurrencyPrices?.Equals(other.CurrencyPrices) == true)); } /// @@ -274,15 +358,16 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.PricingScheme = {(this.PricingScheme == null ? "null" : this.PricingScheme.ToString())}"); toStringOutput.Add($"this.ComponentId = {(this.ComponentId == null ? "null" : this.ComponentId.ToString())}"); toStringOutput.Add($"this.Handle = {(this.Handle == null ? "null" : this.Handle)}"); - toStringOutput.Add($"this.ArchivedAt = {(this.ArchivedAt == null ? "null" : this.ArchivedAt)}"); - toStringOutput.Add($"this.CreatedAt = {(this.CreatedAt == null ? "null" : this.CreatedAt)}"); - toStringOutput.Add($"this.UpdatedAt = {(this.UpdatedAt == null ? "null" : this.UpdatedAt)}"); + toStringOutput.Add($"this.ArchivedAt = {(this.ArchivedAt == null ? "null" : this.ArchivedAt.ToString())}"); + toStringOutput.Add($"this.CreatedAt = {(this.CreatedAt == null ? "null" : this.CreatedAt.ToString())}"); + toStringOutput.Add($"this.UpdatedAt = {(this.UpdatedAt == null ? "null" : this.UpdatedAt.ToString())}"); toStringOutput.Add($"this.Prices = {(this.Prices == null ? "null" : $"[{string.Join(", ", this.Prices)} ]")}"); toStringOutput.Add($"this.UseSiteExchangeRate = {(this.UseSiteExchangeRate == null ? "null" : this.UseSiteExchangeRate.ToString())}"); toStringOutput.Add($"this.SubscriptionId = {(this.SubscriptionId == null ? "null" : this.SubscriptionId.ToString())}"); toStringOutput.Add($"this.TaxIncluded = {(this.TaxIncluded == null ? "null" : this.TaxIncluded.ToString())}"); toStringOutput.Add($"this.Interval = {(this.Interval == null ? "null" : this.Interval.ToString())}"); - toStringOutput.Add($"this.IntervalUnit = {(this.IntervalUnit == null ? "null" : this.IntervalUnit.ToString())}"); + toStringOutput.Add($"IntervalUnit = {(this.IntervalUnit == null ? "null" : this.IntervalUnit.ToString())}"); + toStringOutput.Add($"this.CurrencyPrices = {(this.CurrencyPrices == null ? "null" : $"[{string.Join(", ", this.CurrencyPrices)} ]")}"); } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/ComponentPricePointPrice.cs b/AdvancedBilling.Standard/Models/ComponentPricePointPrice.cs deleted file mode 100644 index deff7a6..0000000 --- a/AdvancedBilling.Standard/Models/ComponentPricePointPrice.cs +++ /dev/null @@ -1,232 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// ComponentPricePointPrice. - /// - public class ComponentPricePointPrice - { - private int? endingQuantity; - private int? segmentId; - private Dictionary shouldSerialize = new Dictionary - { - { "ending_quantity", false }, - { "segment_id", false }, - }; - - /// - /// Initializes a new instance of the class. - /// - public ComponentPricePointPrice() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// id. - /// component_id. - /// starting_quantity. - /// ending_quantity. - /// unit_price. - /// price_point_id. - /// formatted_unit_price. - /// segment_id. - public ComponentPricePointPrice( - int? id = null, - int? componentId = null, - int? startingQuantity = null, - int? endingQuantity = null, - string unitPrice = null, - int? pricePointId = null, - string formattedUnitPrice = null, - int? segmentId = null) - { - this.Id = id; - this.ComponentId = componentId; - this.StartingQuantity = startingQuantity; - if (endingQuantity != null) - { - this.EndingQuantity = endingQuantity; - } - - this.UnitPrice = unitPrice; - this.PricePointId = pricePointId; - this.FormattedUnitPrice = formattedUnitPrice; - if (segmentId != null) - { - this.SegmentId = segmentId; - } - - } - - /// - /// Gets or sets Id. - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// Gets or sets ComponentId. - /// - [JsonProperty("component_id", NullValueHandling = NullValueHandling.Ignore)] - public int? ComponentId { get; set; } - - /// - /// Gets or sets StartingQuantity. - /// - [JsonProperty("starting_quantity", NullValueHandling = NullValueHandling.Ignore)] - public int? StartingQuantity { get; set; } - - /// - /// Gets or sets EndingQuantity. - /// - [JsonProperty("ending_quantity")] - public int? EndingQuantity - { - get - { - return this.endingQuantity; - } - - set - { - this.shouldSerialize["ending_quantity"] = true; - this.endingQuantity = value; - } - } - - /// - /// Gets or sets UnitPrice. - /// - [JsonProperty("unit_price", NullValueHandling = NullValueHandling.Ignore)] - public string UnitPrice { get; set; } - - /// - /// Gets or sets PricePointId. - /// - [JsonProperty("price_point_id", NullValueHandling = NullValueHandling.Ignore)] - public int? PricePointId { get; set; } - - /// - /// Gets or sets FormattedUnitPrice. - /// - [JsonProperty("formatted_unit_price", NullValueHandling = NullValueHandling.Ignore)] - public string FormattedUnitPrice { get; set; } - - /// - /// Gets or sets SegmentId. - /// - [JsonProperty("segment_id")] - public int? SegmentId - { - get - { - return this.segmentId; - } - - set - { - this.shouldSerialize["segment_id"] = true; - this.segmentId = value; - } - } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"ComponentPricePointPrice : ({string.Join(", ", toStringOutput)})"; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetEndingQuantity() - { - this.shouldSerialize["ending_quantity"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetSegmentId() - { - this.shouldSerialize["segment_id"] = false; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeEndingQuantity() - { - return this.shouldSerialize["ending_quantity"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeSegmentId() - { - return this.shouldSerialize["segment_id"]; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is ComponentPricePointPrice other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.ComponentId == null && other.ComponentId == null) || (this.ComponentId?.Equals(other.ComponentId) == true)) && - ((this.StartingQuantity == null && other.StartingQuantity == null) || (this.StartingQuantity?.Equals(other.StartingQuantity) == true)) && - ((this.EndingQuantity == null && other.EndingQuantity == null) || (this.EndingQuantity?.Equals(other.EndingQuantity) == true)) && - ((this.UnitPrice == null && other.UnitPrice == null) || (this.UnitPrice?.Equals(other.UnitPrice) == true)) && - ((this.PricePointId == null && other.PricePointId == null) || (this.PricePointId?.Equals(other.PricePointId) == true)) && - ((this.FormattedUnitPrice == null && other.FormattedUnitPrice == null) || (this.FormattedUnitPrice?.Equals(other.FormattedUnitPrice) == true)) && - ((this.SegmentId == null && other.SegmentId == null) || (this.SegmentId?.Equals(other.SegmentId) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.ComponentId = {(this.ComponentId == null ? "null" : this.ComponentId.ToString())}"); - toStringOutput.Add($"this.StartingQuantity = {(this.StartingQuantity == null ? "null" : this.StartingQuantity.ToString())}"); - toStringOutput.Add($"this.EndingQuantity = {(this.EndingQuantity == null ? "null" : this.EndingQuantity.ToString())}"); - toStringOutput.Add($"this.UnitPrice = {(this.UnitPrice == null ? "null" : this.UnitPrice)}"); - toStringOutput.Add($"this.PricePointId = {(this.PricePointId == null ? "null" : this.PricePointId.ToString())}"); - toStringOutput.Add($"this.FormattedUnitPrice = {(this.FormattedUnitPrice == null ? "null" : this.FormattedUnitPrice)}"); - toStringOutput.Add($"this.SegmentId = {(this.SegmentId == null ? "null" : this.SegmentId.ToString())}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/ComponentPricePointsResponse.cs b/AdvancedBilling.Standard/Models/ComponentPricePointsResponse.cs index 2aae09a..fac1f64 100644 --- a/AdvancedBilling.Standard/Models/ComponentPricePointsResponse.cs +++ b/AdvancedBilling.Standard/Models/ComponentPricePointsResponse.cs @@ -32,10 +32,13 @@ public ComponentPricePointsResponse() /// Initializes a new instance of the class. /// /// price_points. + /// meta. public ComponentPricePointsResponse( - List pricePoints = null) + List pricePoints = null, + Models.ListPublicKeysMeta meta = null) { this.PricePoints = pricePoints; + this.Meta = meta; } /// @@ -44,6 +47,12 @@ public ComponentPricePointsResponse( [JsonProperty("price_points", NullValueHandling = NullValueHandling.Ignore)] public List PricePoints { get; set; } + /// + /// Gets or sets Meta. + /// + [JsonProperty("meta", NullValueHandling = NullValueHandling.Ignore)] + public Models.ListPublicKeysMeta Meta { get; set; } + /// public override string ToString() { @@ -66,7 +75,8 @@ public override bool Equals(object obj) { return true; } - return obj is ComponentPricePointsResponse other && ((this.PricePoints == null && other.PricePoints == null) || (this.PricePoints?.Equals(other.PricePoints) == true)); + return obj is ComponentPricePointsResponse other && ((this.PricePoints == null && other.PricePoints == null) || (this.PricePoints?.Equals(other.PricePoints) == true)) && + ((this.Meta == null && other.Meta == null) || (this.Meta?.Equals(other.Meta) == true)); } /// @@ -76,6 +86,7 @@ public override bool Equals(object obj) protected void ToString(List toStringOutput) { toStringOutput.Add($"this.PricePoints = {(this.PricePoints == null ? "null" : $"[{string.Join(", ", this.PricePoints)} ]")}"); + toStringOutput.Add($"this.Meta = {(this.Meta == null ? "null" : this.Meta.ToString())}"); } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Containers/ComponentPricePointIntervalUnit.cs b/AdvancedBilling.Standard/Models/Containers/ComponentPricePointIntervalUnit.cs new file mode 100644 index 0000000..03ab081 --- /dev/null +++ b/AdvancedBilling.Standard/Models/Containers/ComponentPricePointIntervalUnit.cs @@ -0,0 +1,67 @@ +using APIMatic.Core.Utilities.Converters; +using Newtonsoft.Json; +using System; + +namespace AdvancedBilling.Standard.Models.Containers +{ + /// + /// This is a container class for one-of types. + /// + [JsonConverter( + typeof(UnionTypeConverter), + new Type[] { + typeof(IntervalUnitCase) + }, + true + )] + public abstract class ComponentPricePointIntervalUnit + { + /// + /// This is Interval Unit case. + /// + /// + /// The ComponentPricePointIntervalUnit instance, wrapping the provided IntervalUnit value. + /// + public static ComponentPricePointIntervalUnit FromIntervalUnit(IntervalUnit intervalUnit) + { + return new IntervalUnitCase().Set(intervalUnit); + } + + /// + /// Method to match from the provided one-of cases. Here parameters + /// represents the callback functions for one-of type cases. All + /// callback functions must have the same return type T. This typeparam T + /// represents the type that will be returned after applying the selected + /// callback function. + /// + /// + public abstract T Match(Func intervalUnit); + + [JsonConverter(typeof(UnionTypeCaseConverter))] + private sealed class IntervalUnitCase : ComponentPricePointIntervalUnit, ICaseValue + { + public IntervalUnit _value; + + public override T Match(Func intervalUnit) + { + return intervalUnit(_value); + } + + public IntervalUnitCase Set(IntervalUnit value) + { + _value = value; + return this; + } + + public IntervalUnit Get() + { + return _value; + } + + public override string ToString() + { + return _value.ToString(); + } + } + } +} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Containers/CreateComponentBody.cs b/AdvancedBilling.Standard/Models/Containers/CreateComponentBody.cs deleted file mode 100644 index 057ea0e..0000000 --- a/AdvancedBilling.Standard/Models/Containers/CreateComponentBody.cs +++ /dev/null @@ -1,253 +0,0 @@ -using APIMatic.Core.Utilities.Converters; -using Newtonsoft.Json; -using System; - -namespace AdvancedBilling.Standard.Models.Containers -{ - /// - /// This is a container class for one-of types. - /// - [JsonConverter( - typeof(UnionTypeConverter), - new Type[] { - typeof(CreateMeteredComponentCase), - typeof(CreateQuantityBasedComponentCase), - typeof(CreateOnOffComponentCase), - typeof(CreatePrepaidComponentCase), - typeof(CreateEBBComponentCase) - }, - true - )] - public abstract class CreateComponentBody - { - /// - /// This is Create Metered Component case. - /// - /// - /// The CreateComponentBody instance, wrapping the provided CreateMeteredComponent value. - /// - public static CreateComponentBody FromCreateMeteredComponent(CreateMeteredComponent createMeteredComponent) - { - return new CreateMeteredComponentCase().Set(createMeteredComponent); - } - - /// - /// This is Create Quantity Based Component case. - /// - /// - /// The CreateComponentBody instance, wrapping the provided CreateQuantityBasedComponent value. - /// - public static CreateComponentBody FromCreateQuantityBasedComponent(CreateQuantityBasedComponent createQuantityBasedComponent) - { - return new CreateQuantityBasedComponentCase().Set(createQuantityBasedComponent); - } - - /// - /// This is Create On/Off Component case. - /// - /// - /// The CreateComponentBody instance, wrapping the provided CreateOnOffComponent value. - /// - public static CreateComponentBody FromCreateOnOffComponent(CreateOnOffComponent createOnOffComponent) - { - return new CreateOnOffComponentCase().Set(createOnOffComponent); - } - - /// - /// This is Create Prepaid Component case. - /// - /// - /// The CreateComponentBody instance, wrapping the provided CreatePrepaidComponent value. - /// - public static CreateComponentBody FromCreatePrepaidComponent(CreatePrepaidComponent createPrepaidComponent) - { - return new CreatePrepaidComponentCase().Set(createPrepaidComponent); - } - - /// - /// This is Create EBB Component case. - /// - /// - /// The CreateComponentBody instance, wrapping the provided CreateEBBComponent value. - /// - public static CreateComponentBody FromCreateEBBComponent(CreateEBBComponent createEBBComponent) - { - return new CreateEBBComponentCase().Set(createEBBComponent); - } - - /// - /// Method to match from the provided one-of cases. Here parameters - /// represents the callback functions for one-of type cases. All - /// callback functions must have the same return type T. This typeparam T - /// represents the type that will be returned after applying the selected - /// callback function. - /// - /// - public abstract T Match( - Func createMeteredComponent, - Func createQuantityBasedComponent, - Func createOnOffComponent, - Func createPrepaidComponent, - Func createEBBComponent); - - [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class CreateMeteredComponentCase : CreateComponentBody, ICaseValue - { - public CreateMeteredComponent _value; - - public override T Match( - Func createMeteredComponent, - Func createQuantityBasedComponent, - Func createOnOffComponent, - Func createPrepaidComponent, - Func createEBBComponent) - { - return createMeteredComponent(_value); - } - - public CreateMeteredComponentCase Set(CreateMeteredComponent value) - { - _value = value; - return this; - } - - public CreateMeteredComponent Get() - { - return _value; - } - - public override string ToString() - { - return _value?.ToString(); - } - } - - [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class CreateQuantityBasedComponentCase : CreateComponentBody, ICaseValue - { - public CreateQuantityBasedComponent _value; - - public override T Match( - Func createMeteredComponent, - Func createQuantityBasedComponent, - Func createOnOffComponent, - Func createPrepaidComponent, - Func createEBBComponent) - { - return createQuantityBasedComponent(_value); - } - - public CreateQuantityBasedComponentCase Set(CreateQuantityBasedComponent value) - { - _value = value; - return this; - } - - public CreateQuantityBasedComponent Get() - { - return _value; - } - - public override string ToString() - { - return _value?.ToString(); - } - } - - [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class CreateOnOffComponentCase : CreateComponentBody, ICaseValue - { - public CreateOnOffComponent _value; - - public override T Match( - Func createMeteredComponent, - Func createQuantityBasedComponent, - Func createOnOffComponent, - Func createPrepaidComponent, - Func createEBBComponent) - { - return createOnOffComponent(_value); - } - - public CreateOnOffComponentCase Set(CreateOnOffComponent value) - { - _value = value; - return this; - } - - public CreateOnOffComponent Get() - { - return _value; - } - - public override string ToString() - { - return _value?.ToString(); - } - } - - [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class CreatePrepaidComponentCase : CreateComponentBody, ICaseValue - { - public CreatePrepaidComponent _value; - - public override T Match( - Func createMeteredComponent, - Func createQuantityBasedComponent, - Func createOnOffComponent, - Func createPrepaidComponent, - Func createEBBComponent) - { - return createPrepaidComponent(_value); - } - - public CreatePrepaidComponentCase Set(CreatePrepaidComponent value) - { - _value = value; - return this; - } - - public CreatePrepaidComponent Get() - { - return _value; - } - - public override string ToString() - { - return _value?.ToString(); - } - } - - [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class CreateEBBComponentCase : CreateComponentBody, ICaseValue - { - public CreateEBBComponent _value; - - public override T Match( - Func createMeteredComponent, - Func createQuantityBasedComponent, - Func createOnOffComponent, - Func createPrepaidComponent, - Func createEBBComponent) - { - return createEBBComponent(_value); - } - - public CreateEBBComponentCase Set(CreateEBBComponent value) - { - _value = value; - return this; - } - - public CreateEBBComponent Get() - { - return _value; - } - - public override string ToString() - { - return _value?.ToString(); - } - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Containers/CreateOrUpdatePercentageCouponPercentage.cs b/AdvancedBilling.Standard/Models/Containers/CreateOrUpdatePercentageCouponPercentage.cs index a45b850..1829bf6 100644 --- a/AdvancedBilling.Standard/Models/Containers/CreateOrUpdatePercentageCouponPercentage.cs +++ b/AdvancedBilling.Standard/Models/Containers/CreateOrUpdatePercentageCouponPercentage.cs @@ -11,33 +11,33 @@ namespace AdvancedBilling.Standard.Models.Containers [JsonConverter( typeof(UnionTypeConverter), new Type[] { - typeof(PrecisionCase), - typeof(MStringCase) + typeof(MStringCase), + typeof(PrecisionCase) }, true )] public abstract class CreateOrUpdatePercentageCouponPercentage { /// - /// This is Precision case. + /// This is String case. /// /// - /// The CreateOrUpdatePercentageCouponPercentage instance, wrapping the provided double value. + /// The CreateOrUpdatePercentageCouponPercentage instance, wrapping the provided string value. /// - public static CreateOrUpdatePercentageCouponPercentage FromPrecision(double precision) + public static CreateOrUpdatePercentageCouponPercentage FromString(string mString) { - return new PrecisionCase().Set(precision); + return new MStringCase().Set(mString); } /// - /// This is String case. + /// This is Precision case. /// /// - /// The CreateOrUpdatePercentageCouponPercentage instance, wrapping the provided string value. + /// The CreateOrUpdatePercentageCouponPercentage instance, wrapping the provided double value. /// - public static CreateOrUpdatePercentageCouponPercentage FromString(string mString) + public static CreateOrUpdatePercentageCouponPercentage FromPrecision(double precision) { - return new MStringCase().Set(mString); + return new PrecisionCase().Set(precision); } /// @@ -48,59 +48,59 @@ public static CreateOrUpdatePercentageCouponPercentage FromString(string mString /// callback function. /// /// - public abstract T Match(Func precision, Func mString); + public abstract T Match(Func mString, Func precision); - [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.Float)] - private sealed class PrecisionCase : CreateOrUpdatePercentageCouponPercentage, ICaseValue + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.String, JTokenType.Null)] + private sealed class MStringCase : CreateOrUpdatePercentageCouponPercentage, ICaseValue { - public double _value; + public string _value; - public override T Match(Func precision, Func mString) + public override T Match(Func mString, Func precision) { - return precision(_value); + return mString(_value); } - public PrecisionCase Set(double value) + public MStringCase Set(string value) { _value = value; return this; } - public double Get() + public string Get() { return _value; } public override string ToString() { - return _value.ToString(); + return _value?.ToString(); } } - [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.String, JTokenType.Null)] - private sealed class MStringCase : CreateOrUpdatePercentageCouponPercentage, ICaseValue + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.Float)] + private sealed class PrecisionCase : CreateOrUpdatePercentageCouponPercentage, ICaseValue { - public string _value; + public double _value; - public override T Match(Func precision, Func mString) + public override T Match(Func mString, Func precision) { - return mString(_value); + return precision(_value); } - public MStringCase Set(string value) + public PrecisionCase Set(double value) { _value = value; return this; } - public string Get() + public double Get() { return _value; } public override string ToString() { - return _value?.ToString(); + return _value.ToString(); } } } diff --git a/AdvancedBilling.Standard/Models/Containers/InvoiceEventEventData.cs b/AdvancedBilling.Standard/Models/Containers/InvoiceEventEventData.cs index 00e6afa..b22a86f 100644 --- a/AdvancedBilling.Standard/Models/Containers/InvoiceEventEventData.cs +++ b/AdvancedBilling.Standard/Models/Containers/InvoiceEventEventData.cs @@ -18,7 +18,7 @@ namespace AdvancedBilling.Standard.Models.Containers typeof(RefundInvoiceEventDataCase), typeof(RemovePaymentEventDataCase), typeof(VoidInvoiceEventDataCase), - typeof(VoidInvoiceEventData1Case) + typeof(VoidRemainderEventDataCase) }, false )] @@ -113,14 +113,14 @@ public static InvoiceEventEventData FromVoidInvoiceEventData(VoidInvoiceEventDat } /// - /// This is Void Invoice Event Data1 case. + /// This is Void Remainder Event Data case. /// /// - /// The InvoiceEventEventData instance, wrapping the provided VoidInvoiceEventData1 value. + /// The InvoiceEventEventData instance, wrapping the provided VoidRemainderEventData value. /// - public static InvoiceEventEventData FromVoidInvoiceEventData1(VoidInvoiceEventData1 voidInvoiceEventData1) + public static InvoiceEventEventData FromVoidRemainderEventData(VoidRemainderEventData voidRemainderEventData) { - return new VoidInvoiceEventData1Case().Set(voidInvoiceEventData1); + return new VoidRemainderEventDataCase().Set(voidRemainderEventData); } /// @@ -140,7 +140,7 @@ public abstract T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1); + Func voidRemainderEventData); [JsonConverter(typeof(UnionTypeCaseConverter))] private sealed class ApplyCreditNoteEventDataCase : InvoiceEventEventData, ICaseValue @@ -156,7 +156,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return applyCreditNoteEventData(_value); } @@ -192,7 +192,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return applyDebitNoteEventData(_value); } @@ -228,7 +228,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return applyPaymentEventData(_value); } @@ -264,7 +264,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return changeInvoiceCollectionMethodEventData(_value); } @@ -300,7 +300,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return issueInvoiceEventData(_value); } @@ -336,7 +336,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return refundInvoiceEventData(_value); } @@ -372,7 +372,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return removePaymentEventData(_value); } @@ -408,7 +408,7 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { return voidInvoiceEventData(_value); } @@ -430,10 +430,10 @@ public override string ToString() } } - [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class VoidInvoiceEventData1Case : InvoiceEventEventData, ICaseValue + [JsonConverter(typeof(UnionTypeCaseConverter))] + private sealed class VoidRemainderEventDataCase : InvoiceEventEventData, ICaseValue { - public VoidInvoiceEventData1 _value; + public VoidRemainderEventData _value; public override T Match( Func applyCreditNoteEventData, @@ -444,18 +444,18 @@ public override T Match( Func refundInvoiceEventData, Func removePaymentEventData, Func voidInvoiceEventData, - Func voidInvoiceEventData1) + Func voidRemainderEventData) { - return voidInvoiceEventData1(_value); + return voidRemainderEventData(_value); } - public VoidInvoiceEventData1Case Set(VoidInvoiceEventData1 value) + public VoidRemainderEventDataCase Set(VoidRemainderEventData value) { _value = value; return this; } - public VoidInvoiceEventData1 Get() + public VoidRemainderEventData Get() { return _value; } diff --git a/AdvancedBilling.Standard/Models/Containers/ReadPaymentProfileResponsePaymentProfile.cs b/AdvancedBilling.Standard/Models/Containers/PaymentProfileResponsePaymentProfile.cs similarity index 75% rename from AdvancedBilling.Standard/Models/Containers/ReadPaymentProfileResponsePaymentProfile.cs rename to AdvancedBilling.Standard/Models/Containers/PaymentProfileResponsePaymentProfile.cs index 21cd1a6..7b11e56 100644 --- a/AdvancedBilling.Standard/Models/Containers/ReadPaymentProfileResponsePaymentProfile.cs +++ b/AdvancedBilling.Standard/Models/Containers/PaymentProfileResponsePaymentProfile.cs @@ -8,22 +8,22 @@ namespace AdvancedBilling.Standard.Models.Containers /// This is a container class for one-of types. /// [JsonConverter( - typeof(UnionTypeConverter), + typeof(UnionTypeConverter), new Type[] { typeof(BankAccountPaymentProfileCase), typeof(CreditCardPaymentProfileCase) }, true )] - public abstract class ReadPaymentProfileResponsePaymentProfile + public abstract class PaymentProfileResponsePaymentProfile { /// /// This is Bank Account Payment Profile case. /// /// - /// The ReadPaymentProfileResponsePaymentProfile instance, wrapping the provided BankAccountPaymentProfile value. + /// The PaymentProfileResponsePaymentProfile instance, wrapping the provided BankAccountPaymentProfile value. /// - public static ReadPaymentProfileResponsePaymentProfile FromBankAccountPaymentProfile(BankAccountPaymentProfile bankAccountPaymentProfile) + public static PaymentProfileResponsePaymentProfile FromBankAccountPaymentProfile(BankAccountPaymentProfile bankAccountPaymentProfile) { return new BankAccountPaymentProfileCase().Set(bankAccountPaymentProfile); } @@ -32,9 +32,9 @@ public static ReadPaymentProfileResponsePaymentProfile FromBankAccountPaymentPro /// This is Credit Card Payment Profile case. /// /// - /// The ReadPaymentProfileResponsePaymentProfile instance, wrapping the provided CreditCardPaymentProfile value. + /// The PaymentProfileResponsePaymentProfile instance, wrapping the provided CreditCardPaymentProfile value. /// - public static ReadPaymentProfileResponsePaymentProfile FromCreditCardPaymentProfile(CreditCardPaymentProfile creditCardPaymentProfile) + public static PaymentProfileResponsePaymentProfile FromCreditCardPaymentProfile(CreditCardPaymentProfile creditCardPaymentProfile) { return new CreditCardPaymentProfileCase().Set(creditCardPaymentProfile); } @@ -50,7 +50,7 @@ public static ReadPaymentProfileResponsePaymentProfile FromCreditCardPaymentProf public abstract T Match(Func bankAccountPaymentProfile, Func creditCardPaymentProfile); [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class BankAccountPaymentProfileCase : ReadPaymentProfileResponsePaymentProfile, ICaseValue + private sealed class BankAccountPaymentProfileCase : PaymentProfileResponsePaymentProfile, ICaseValue { public BankAccountPaymentProfile _value; @@ -77,7 +77,7 @@ public override string ToString() } [JsonConverter(typeof(UnionTypeCaseConverter))] - private sealed class CreditCardPaymentProfileCase : ReadPaymentProfileResponsePaymentProfile, ICaseValue + private sealed class CreditCardPaymentProfileCase : PaymentProfileResponsePaymentProfile, ICaseValue { public CreditCardPaymentProfile _value; diff --git a/AdvancedBilling.Standard/Models/Containers/UpdatePriceEndingQuantity.cs b/AdvancedBilling.Standard/Models/Containers/UpdatePriceEndingQuantity.cs new file mode 100644 index 0000000..3e86daa --- /dev/null +++ b/AdvancedBilling.Standard/Models/Containers/UpdatePriceEndingQuantity.cs @@ -0,0 +1,107 @@ +using APIMatic.Core.Utilities.Converters; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; + +namespace AdvancedBilling.Standard.Models.Containers +{ + /// + /// This is a container class for one-of types. + /// + [JsonConverter( + typeof(UnionTypeConverter), + new Type[] { + typeof(NumberCase), + typeof(MStringCase) + }, + true + )] + public abstract class UpdatePriceEndingQuantity + { + /// + /// This is Number case. + /// + /// + /// The UpdatePriceEndingQuantity instance, wrapping the provided int value. + /// + public static UpdatePriceEndingQuantity FromNumber(int number) + { + return new NumberCase().Set(number); + } + + /// + /// This is String case. + /// + /// + /// The UpdatePriceEndingQuantity instance, wrapping the provided string value. + /// + public static UpdatePriceEndingQuantity FromString(string mString) + { + return new MStringCase().Set(mString); + } + + /// + /// Method to match from the provided one-of cases. Here parameters + /// represents the callback functions for one-of type cases. All + /// callback functions must have the same return type T. This typeparam T + /// represents the type that will be returned after applying the selected + /// callback function. + /// + /// + public abstract T Match(Func number, Func mString); + + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.Integer)] + private sealed class NumberCase : UpdatePriceEndingQuantity, ICaseValue + { + public int _value; + + public override T Match(Func number, Func mString) + { + return number(_value); + } + + public NumberCase Set(int value) + { + _value = value; + return this; + } + + public int Get() + { + return _value; + } + + public override string ToString() + { + return _value.ToString(); + } + } + + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.String, JTokenType.Null)] + private sealed class MStringCase : UpdatePriceEndingQuantity, ICaseValue + { + public string _value; + + public override T Match(Func number, Func mString) + { + return mString(_value); + } + + public MStringCase Set(string value) + { + _value = value; + return this; + } + + public string Get() + { + return _value; + } + + public override string ToString() + { + return _value?.ToString(); + } + } + } +} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Containers/UpdatePriceStartingQuantity.cs b/AdvancedBilling.Standard/Models/Containers/UpdatePriceStartingQuantity.cs new file mode 100644 index 0000000..984b92a --- /dev/null +++ b/AdvancedBilling.Standard/Models/Containers/UpdatePriceStartingQuantity.cs @@ -0,0 +1,107 @@ +using APIMatic.Core.Utilities.Converters; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; + +namespace AdvancedBilling.Standard.Models.Containers +{ + /// + /// This is a container class for one-of types. + /// + [JsonConverter( + typeof(UnionTypeConverter), + new Type[] { + typeof(NumberCase), + typeof(MStringCase) + }, + true + )] + public abstract class UpdatePriceStartingQuantity + { + /// + /// This is Number case. + /// + /// + /// The UpdatePriceStartingQuantity instance, wrapping the provided int value. + /// + public static UpdatePriceStartingQuantity FromNumber(int number) + { + return new NumberCase().Set(number); + } + + /// + /// This is String case. + /// + /// + /// The UpdatePriceStartingQuantity instance, wrapping the provided string value. + /// + public static UpdatePriceStartingQuantity FromString(string mString) + { + return new MStringCase().Set(mString); + } + + /// + /// Method to match from the provided one-of cases. Here parameters + /// represents the callback functions for one-of type cases. All + /// callback functions must have the same return type T. This typeparam T + /// represents the type that will be returned after applying the selected + /// callback function. + /// + /// + public abstract T Match(Func number, Func mString); + + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.Integer)] + private sealed class NumberCase : UpdatePriceStartingQuantity, ICaseValue + { + public int _value; + + public override T Match(Func number, Func mString) + { + return number(_value); + } + + public NumberCase Set(int value) + { + _value = value; + return this; + } + + public int Get() + { + return _value; + } + + public override string ToString() + { + return _value.ToString(); + } + } + + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.String, JTokenType.Null)] + private sealed class MStringCase : UpdatePriceStartingQuantity, ICaseValue + { + public string _value; + + public override T Match(Func number, Func mString) + { + return mString(_value); + } + + public MStringCase Set(string value) + { + _value = value; + return this; + } + + public string Get() + { + return _value; + } + + public override string ToString() + { + return _value?.ToString(); + } + } + } +} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Containers/UpdatePriceUnitPrice.cs b/AdvancedBilling.Standard/Models/Containers/UpdatePriceUnitPrice.cs new file mode 100644 index 0000000..629ca46 --- /dev/null +++ b/AdvancedBilling.Standard/Models/Containers/UpdatePriceUnitPrice.cs @@ -0,0 +1,107 @@ +using APIMatic.Core.Utilities.Converters; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; + +namespace AdvancedBilling.Standard.Models.Containers +{ + /// + /// This is a container class for one-of types. + /// + [JsonConverter( + typeof(UnionTypeConverter), + new Type[] { + typeof(PrecisionCase), + typeof(MStringCase) + }, + true + )] + public abstract class UpdatePriceUnitPrice + { + /// + /// This is Precision case. + /// + /// + /// The UpdatePriceUnitPrice instance, wrapping the provided double value. + /// + public static UpdatePriceUnitPrice FromPrecision(double precision) + { + return new PrecisionCase().Set(precision); + } + + /// + /// This is String case. + /// + /// + /// The UpdatePriceUnitPrice instance, wrapping the provided string value. + /// + public static UpdatePriceUnitPrice FromString(string mString) + { + return new MStringCase().Set(mString); + } + + /// + /// Method to match from the provided one-of cases. Here parameters + /// represents the callback functions for one-of type cases. All + /// callback functions must have the same return type T. This typeparam T + /// represents the type that will be returned after applying the selected + /// callback function. + /// + /// + public abstract T Match(Func precision, Func mString); + + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.Float)] + private sealed class PrecisionCase : UpdatePriceUnitPrice, ICaseValue + { + public double _value; + + public override T Match(Func precision, Func mString) + { + return precision(_value); + } + + public PrecisionCase Set(double value) + { + _value = value; + return this; + } + + public double Get() + { + return _value; + } + + public override string ToString() + { + return _value.ToString(); + } + } + + [JsonConverter(typeof(UnionTypeCaseConverter), JTokenType.String, JTokenType.Null)] + private sealed class MStringCase : UpdatePriceUnitPrice, ICaseValue + { + public string _value; + + public override T Match(Func precision, Func mString) + { + return mString(_value); + } + + public MStringCase Set(string value) + { + _value = value; + return this; + } + + public string Get() + { + return _value; + } + + public override string ToString() + { + return _value?.ToString(); + } + } + } +} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Coupon.cs b/AdvancedBilling.Standard/Models/Coupon.cs index c3e1914..cd0382a 100644 --- a/AdvancedBilling.Standard/Models/Coupon.cs +++ b/AdvancedBilling.Standard/Models/Coupon.cs @@ -26,7 +26,7 @@ public class Coupon private int? amountInCents; private string productFamilyName; private string endDate; - private double? percentage; + private string percentage; private int? durationPeriodCount; private int? durationInterval; private string durationIntervalUnit; @@ -98,7 +98,7 @@ public Coupon( string productFamilyName = null, string startDate = null, string endDate = null, - double? percentage = null, + string percentage = null, bool? recurring = null, Models.RecurringScheme? recurringScheme = null, int? durationPeriodCount = null, @@ -305,7 +305,7 @@ public string EndDate /// Gets or sets Percentage. /// [JsonProperty("percentage")] - public double? Percentage + public string Percentage { get { @@ -755,7 +755,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.ProductFamilyName = {(this.ProductFamilyName == null ? "null" : this.ProductFamilyName)}"); toStringOutput.Add($"this.StartDate = {(this.StartDate == null ? "null" : this.StartDate)}"); toStringOutput.Add($"this.EndDate = {(this.EndDate == null ? "null" : this.EndDate)}"); - toStringOutput.Add($"this.Percentage = {(this.Percentage == null ? "null" : this.Percentage.ToString())}"); + toStringOutput.Add($"this.Percentage = {(this.Percentage == null ? "null" : this.Percentage)}"); toStringOutput.Add($"this.Recurring = {(this.Recurring == null ? "null" : this.Recurring.ToString())}"); toStringOutput.Add($"this.RecurringScheme = {(this.RecurringScheme == null ? "null" : this.RecurringScheme.ToString())}"); toStringOutput.Add($"this.DurationPeriodCount = {(this.DurationPeriodCount == null ? "null" : this.DurationPeriodCount.ToString())}"); diff --git a/AdvancedBilling.Standard/Models/CreateComponentPricePoint.cs b/AdvancedBilling.Standard/Models/CreateComponentPricePoint.cs index e75b584..283968b 100644 --- a/AdvancedBilling.Standard/Models/CreateComponentPricePoint.cs +++ b/AdvancedBilling.Standard/Models/CreateComponentPricePoint.cs @@ -36,6 +36,7 @@ public CreateComponentPricePoint() /// prices. /// handle. /// use_site_exchange_rate. + /// tax_included. /// interval. /// interval_unit. public CreateComponentPricePoint( @@ -44,6 +45,7 @@ public CreateComponentPricePoint( List prices, string handle = null, bool? useSiteExchangeRate = true, + bool? taxIncluded = null, int? interval = null, Models.IntervalUnit? intervalUnit = null) { @@ -52,6 +54,7 @@ public CreateComponentPricePoint( this.PricingScheme = pricingScheme; this.Prices = prices; this.UseSiteExchangeRate = useSiteExchangeRate; + this.TaxIncluded = taxIncluded; this.Interval = interval; this.IntervalUnit = intervalUnit; } @@ -91,6 +94,12 @@ public CreateComponentPricePoint( [JsonProperty("use_site_exchange_rate", NullValueHandling = NullValueHandling.Ignore)] public bool? UseSiteExchangeRate { get; set; } + /// + /// Whether or not the price point includes tax + /// + [JsonProperty("tax_included", NullValueHandling = NullValueHandling.Ignore)] + public bool? TaxIncluded { get; set; } + /// /// The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. /// @@ -130,6 +139,7 @@ public override bool Equals(object obj) this.PricingScheme.Equals(other.PricingScheme) && ((this.Prices == null && other.Prices == null) || (this.Prices?.Equals(other.Prices) == true)) && ((this.UseSiteExchangeRate == null && other.UseSiteExchangeRate == null) || (this.UseSiteExchangeRate?.Equals(other.UseSiteExchangeRate) == true)) && + ((this.TaxIncluded == null && other.TaxIncluded == null) || (this.TaxIncluded?.Equals(other.TaxIncluded) == true)) && ((this.Interval == null && other.Interval == null) || (this.Interval?.Equals(other.Interval) == true)) && ((this.IntervalUnit == null && other.IntervalUnit == null) || (this.IntervalUnit?.Equals(other.IntervalUnit) == true)); } @@ -145,6 +155,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.PricingScheme = {this.PricingScheme}"); toStringOutput.Add($"this.Prices = {(this.Prices == null ? "null" : $"[{string.Join(", ", this.Prices)} ]")}"); toStringOutput.Add($"this.UseSiteExchangeRate = {(this.UseSiteExchangeRate == null ? "null" : this.UseSiteExchangeRate.ToString())}"); + toStringOutput.Add($"this.TaxIncluded = {(this.TaxIncluded == null ? "null" : this.TaxIncluded.ToString())}"); toStringOutput.Add($"this.Interval = {(this.Interval == null ? "null" : this.Interval.ToString())}"); toStringOutput.Add($"this.IntervalUnit = {(this.IntervalUnit == null ? "null" : this.IntervalUnit.ToString())}"); } diff --git a/AdvancedBilling.Standard/Models/CreateCurrencyPrice.cs b/AdvancedBilling.Standard/Models/CreateCurrencyPrice.cs index a8dbce5..ae02c6b 100644 --- a/AdvancedBilling.Standard/Models/CreateCurrencyPrice.cs +++ b/AdvancedBilling.Standard/Models/CreateCurrencyPrice.cs @@ -36,7 +36,7 @@ public CreateCurrencyPrice() /// price_id. public CreateCurrencyPrice( string currency = null, - int? price = null, + double? price = null, int? priceId = null) { this.Currency = currency; @@ -54,7 +54,7 @@ public CreateCurrencyPrice( /// Price for the price level in this currency /// [JsonProperty("price", NullValueHandling = NullValueHandling.Ignore)] - public int? Price { get; set; } + public double? Price { get; set; } /// /// ID of the price that this corresponds with diff --git a/AdvancedBilling.Standard/Models/CreateEBBComponent.cs b/AdvancedBilling.Standard/Models/CreateEBBComponent.cs index 9b3cd54..b3faf94 100644 --- a/AdvancedBilling.Standard/Models/CreateEBBComponent.cs +++ b/AdvancedBilling.Standard/Models/CreateEBBComponent.cs @@ -42,7 +42,6 @@ public CreateEBBComponent( /// Gets or sets EventBasedComponent. /// [JsonProperty("event_based_component")] - [JsonRequired] public Models.EBBComponent EventBasedComponent { get; set; } /// diff --git a/AdvancedBilling.Standard/Models/CreateMeteredComponent.cs b/AdvancedBilling.Standard/Models/CreateMeteredComponent.cs index 61ad055..20799c6 100644 --- a/AdvancedBilling.Standard/Models/CreateMeteredComponent.cs +++ b/AdvancedBilling.Standard/Models/CreateMeteredComponent.cs @@ -42,7 +42,6 @@ public CreateMeteredComponent( /// Gets or sets MeteredComponent. /// [JsonProperty("metered_component")] - [JsonRequired] public Models.MeteredComponent MeteredComponent { get; set; } /// diff --git a/AdvancedBilling.Standard/Models/CreateOnOffComponent.cs b/AdvancedBilling.Standard/Models/CreateOnOffComponent.cs index f30dadc..746f3d2 100644 --- a/AdvancedBilling.Standard/Models/CreateOnOffComponent.cs +++ b/AdvancedBilling.Standard/Models/CreateOnOffComponent.cs @@ -42,7 +42,6 @@ public CreateOnOffComponent( /// Gets or sets OnOffComponent. /// [JsonProperty("on_off_component")] - [JsonRequired] public Models.OnOffComponent OnOffComponent { get; set; } /// diff --git a/AdvancedBilling.Standard/Models/CreatePaymentProfile.cs b/AdvancedBilling.Standard/Models/CreatePaymentProfile.cs index 72f14a9..2c4563c 100644 --- a/AdvancedBilling.Standard/Models/CreatePaymentProfile.cs +++ b/AdvancedBilling.Standard/Models/CreatePaymentProfile.cs @@ -100,8 +100,8 @@ public CreatePaymentProfile( string bankRoutingNumber = null, string bankAccountNumber = null, string bankBranchCode = null, - string bankAccountType = null, - string bankAccountHolderType = null, + Models.BankAccountType? bankAccountType = Models.BankAccountType.Checking, + Models.BankAccountHolderType? bankAccountHolderType = null, string lastFour = null) { this.ChargifyToken = chargifyToken; @@ -329,16 +329,16 @@ public string BillingAddress2 public string BankBranchCode { get; set; } /// - /// Gets or sets BankAccountType. + /// Defaults to checking /// [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } + public Models.BankAccountType? BankAccountType { get; set; } /// - /// Gets or sets BankAccountHolderType. + /// Defaults to personal /// [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } + public Models.BankAccountHolderType? BankAccountHolderType { get; set; } /// /// (Optional) Used for creating subscription with payment profile imported using vault_token, for proper display in Advanced Billing UI @@ -454,8 +454,8 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.BankRoutingNumber = {(this.BankRoutingNumber == null ? "null" : this.BankRoutingNumber)}"); toStringOutput.Add($"this.BankAccountNumber = {(this.BankAccountNumber == null ? "null" : this.BankAccountNumber)}"); toStringOutput.Add($"this.BankBranchCode = {(this.BankBranchCode == null ? "null" : this.BankBranchCode)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); + toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType.ToString())}"); + toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType.ToString())}"); toStringOutput.Add($"this.LastFour = {(this.LastFour == null ? "null" : this.LastFour)}"); } } diff --git a/AdvancedBilling.Standard/Models/CreatePaymentProfileResponse.cs b/AdvancedBilling.Standard/Models/CreatePaymentProfileResponse.cs deleted file mode 100644 index 9af28df..0000000 --- a/AdvancedBilling.Standard/Models/CreatePaymentProfileResponse.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// CreatePaymentProfileResponse. - /// - public class CreatePaymentProfileResponse - { - /// - /// Initializes a new instance of the class. - /// - public CreatePaymentProfileResponse() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// payment_profile. - public CreatePaymentProfileResponse( - Models.CreatedPaymentProfile paymentProfile) - { - this.PaymentProfile = paymentProfile; - } - - /// - /// Gets or sets PaymentProfile. - /// - [JsonProperty("payment_profile")] - public Models.CreatedPaymentProfile PaymentProfile { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"CreatePaymentProfileResponse : ({string.Join(", ", toStringOutput)})"; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is CreatePaymentProfileResponse other && ((this.PaymentProfile == null && other.PaymentProfile == null) || (this.PaymentProfile?.Equals(other.PaymentProfile) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.PaymentProfile = {(this.PaymentProfile == null ? "null" : this.PaymentProfile.ToString())}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/CreatePrepaidComponent.cs b/AdvancedBilling.Standard/Models/CreatePrepaidComponent.cs index 31e29b9..d72d6f0 100644 --- a/AdvancedBilling.Standard/Models/CreatePrepaidComponent.cs +++ b/AdvancedBilling.Standard/Models/CreatePrepaidComponent.cs @@ -42,7 +42,6 @@ public CreatePrepaidComponent( /// Gets or sets PrepaidUsageComponent. /// [JsonProperty("prepaid_usage_component")] - [JsonRequired] public Models.PrepaidUsageComponent PrepaidUsageComponent { get; set; } /// diff --git a/AdvancedBilling.Standard/Models/CreateQuantityBasedComponent.cs b/AdvancedBilling.Standard/Models/CreateQuantityBasedComponent.cs index f142861..43e6433 100644 --- a/AdvancedBilling.Standard/Models/CreateQuantityBasedComponent.cs +++ b/AdvancedBilling.Standard/Models/CreateQuantityBasedComponent.cs @@ -42,7 +42,6 @@ public CreateQuantityBasedComponent( /// Gets or sets QuantityBasedComponent. /// [JsonProperty("quantity_based_component")] - [JsonRequired] public Models.QuantityBasedComponent QuantityBasedComponent { get; set; } /// diff --git a/AdvancedBilling.Standard/Models/CreatedPaymentProfile.cs b/AdvancedBilling.Standard/Models/CreatedPaymentProfile.cs deleted file mode 100644 index 60f7ec1..0000000 --- a/AdvancedBilling.Standard/Models/CreatedPaymentProfile.cs +++ /dev/null @@ -1,476 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// CreatedPaymentProfile. - /// - public class CreatedPaymentProfile - { - private string maskedCardNumber; - private string customerVaultToken; - private string billingAddress2; - private Dictionary shouldSerialize = new Dictionary - { - { "masked_card_number", false }, - { "customer_vault_token", false }, - { "billing_address_2", false }, - }; - - /// - /// Initializes a new instance of the class. - /// - public CreatedPaymentProfile() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// id. - /// first_name. - /// last_name. - /// masked_card_number. - /// card_type. - /// expiration_month. - /// expiration_year. - /// customer_id. - /// current_vault. - /// vault_token. - /// billing_address. - /// billing_city. - /// billing_state. - /// billing_zip. - /// billing_country. - /// customer_vault_token. - /// billing_address_2. - /// payment_type. - /// bank_name. - /// masked_bank_routing_number. - /// masked_bank_account_number. - /// bank_account_type. - /// bank_account_holder_type. - /// verified. - /// site_gateway_setting_id. - /// gateway_handle. - /// disabled. - public CreatedPaymentProfile( - int? id = null, - string firstName = null, - string lastName = null, - string maskedCardNumber = null, - string cardType = null, - int? expirationMonth = null, - int? expirationYear = null, - int? customerId = null, - Models.CurrentVault? currentVault = null, - string vaultToken = null, - string billingAddress = null, - string billingCity = null, - string billingState = null, - string billingZip = null, - string billingCountry = null, - string customerVaultToken = null, - string billingAddress2 = null, - string paymentType = null, - string bankName = null, - string maskedBankRoutingNumber = null, - string maskedBankAccountNumber = null, - string bankAccountType = null, - string bankAccountHolderType = null, - bool? verified = null, - int? siteGatewaySettingId = null, - string gatewayHandle = null, - bool? disabled = null) - { - this.Id = id; - this.FirstName = firstName; - this.LastName = lastName; - if (maskedCardNumber != null) - { - this.MaskedCardNumber = maskedCardNumber; - } - - this.CardType = cardType; - this.ExpirationMonth = expirationMonth; - this.ExpirationYear = expirationYear; - this.CustomerId = customerId; - this.CurrentVault = currentVault; - this.VaultToken = vaultToken; - this.BillingAddress = billingAddress; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; - if (customerVaultToken != null) - { - this.CustomerVaultToken = customerVaultToken; - } - - if (billingAddress2 != null) - { - this.BillingAddress2 = billingAddress2; - } - - this.PaymentType = paymentType; - this.BankName = bankName; - this.MaskedBankRoutingNumber = maskedBankRoutingNumber; - this.MaskedBankAccountNumber = maskedBankAccountNumber; - this.BankAccountType = bankAccountType; - this.BankAccountHolderType = bankAccountHolderType; - this.Verified = verified; - this.SiteGatewaySettingId = siteGatewaySettingId; - this.GatewayHandle = gatewayHandle; - this.Disabled = disabled; - } - - /// - /// Gets or sets Id. - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// Gets or sets FirstName. - /// - [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - /// - /// Gets or sets LastName. - /// - [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - /// - /// Gets or sets MaskedCardNumber. - /// - [JsonProperty("masked_card_number")] - public string MaskedCardNumber - { - get - { - return this.maskedCardNumber; - } - - set - { - this.shouldSerialize["masked_card_number"] = true; - this.maskedCardNumber = value; - } - } - - /// - /// Gets or sets CardType. - /// - [JsonProperty("card_type", NullValueHandling = NullValueHandling.Ignore)] - public string CardType { get; set; } - - /// - /// Gets or sets ExpirationMonth. - /// - [JsonProperty("expiration_month", NullValueHandling = NullValueHandling.Ignore)] - public int? ExpirationMonth { get; set; } - - /// - /// Gets or sets ExpirationYear. - /// - [JsonProperty("expiration_year", NullValueHandling = NullValueHandling.Ignore)] - public int? ExpirationYear { get; set; } - - /// - /// Gets or sets CustomerId. - /// - [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] - public int? CustomerId { get; set; } - - /// - /// The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - /// - [JsonProperty("current_vault", NullValueHandling = NullValueHandling.Ignore)] - public Models.CurrentVault? CurrentVault { get; set; } - - /// - /// Gets or sets VaultToken. - /// - [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string VaultToken { get; set; } - - /// - /// Gets or sets BillingAddress. - /// - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } - - /// - /// Gets or sets BillingCity. - /// - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } - - /// - /// Gets or sets BillingState. - /// - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } - - /// - /// Gets or sets BillingZip. - /// - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } - - /// - /// Gets or sets BillingCountry. - /// - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } - - /// - /// Gets or sets CustomerVaultToken. - /// - [JsonProperty("customer_vault_token")] - public string CustomerVaultToken - { - get - { - return this.customerVaultToken; - } - - set - { - this.shouldSerialize["customer_vault_token"] = true; - this.customerVaultToken = value; - } - } - - /// - /// Gets or sets BillingAddress2. - /// - [JsonProperty("billing_address_2")] - public string BillingAddress2 - { - get - { - return this.billingAddress2; - } - - set - { - this.shouldSerialize["billing_address_2"] = true; - this.billingAddress2 = value; - } - } - - /// - /// Gets or sets PaymentType. - /// - [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } - - /// - /// Gets or sets BankName. - /// - [JsonProperty("bank_name", NullValueHandling = NullValueHandling.Ignore)] - public string BankName { get; set; } - - /// - /// Gets or sets MaskedBankRoutingNumber. - /// - [JsonProperty("masked_bank_routing_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankRoutingNumber { get; set; } - - /// - /// Gets or sets MaskedBankAccountNumber. - /// - [JsonProperty("masked_bank_account_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankAccountNumber { get; set; } - - /// - /// Gets or sets BankAccountType. - /// - [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } - - /// - /// Gets or sets BankAccountHolderType. - /// - [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } - - /// - /// Gets or sets Verified. - /// - [JsonProperty("verified", NullValueHandling = NullValueHandling.Ignore)] - public bool? Verified { get; set; } - - /// - /// Gets or sets SiteGatewaySettingId. - /// - [JsonProperty("site_gateway_setting_id", NullValueHandling = NullValueHandling.Ignore)] - public int? SiteGatewaySettingId { get; set; } - - /// - /// Gets or sets GatewayHandle. - /// - [JsonProperty("gateway_handle", NullValueHandling = NullValueHandling.Ignore)] - public string GatewayHandle { get; set; } - - /// - /// Gets or sets Disabled. - /// - [JsonProperty("disabled", NullValueHandling = NullValueHandling.Ignore)] - public bool? Disabled { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"CreatedPaymentProfile : ({string.Join(", ", toStringOutput)})"; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetMaskedCardNumber() - { - this.shouldSerialize["masked_card_number"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetCustomerVaultToken() - { - this.shouldSerialize["customer_vault_token"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingAddress2() - { - this.shouldSerialize["billing_address_2"] = false; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeMaskedCardNumber() - { - return this.shouldSerialize["masked_card_number"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeCustomerVaultToken() - { - return this.shouldSerialize["customer_vault_token"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingAddress2() - { - return this.shouldSerialize["billing_address_2"]; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is CreatedPaymentProfile other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && - ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && - ((this.MaskedCardNumber == null && other.MaskedCardNumber == null) || (this.MaskedCardNumber?.Equals(other.MaskedCardNumber) == true)) && - ((this.CardType == null && other.CardType == null) || (this.CardType?.Equals(other.CardType) == true)) && - ((this.ExpirationMonth == null && other.ExpirationMonth == null) || (this.ExpirationMonth?.Equals(other.ExpirationMonth) == true)) && - ((this.ExpirationYear == null && other.ExpirationYear == null) || (this.ExpirationYear?.Equals(other.ExpirationYear) == true)) && - ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && - ((this.CurrentVault == null && other.CurrentVault == null) || (this.CurrentVault?.Equals(other.CurrentVault) == true)) && - ((this.VaultToken == null && other.VaultToken == null) || (this.VaultToken?.Equals(other.VaultToken) == true)) && - ((this.BillingAddress == null && other.BillingAddress == null) || (this.BillingAddress?.Equals(other.BillingAddress) == true)) && - ((this.BillingCity == null && other.BillingCity == null) || (this.BillingCity?.Equals(other.BillingCity) == true)) && - ((this.BillingState == null && other.BillingState == null) || (this.BillingState?.Equals(other.BillingState) == true)) && - ((this.BillingZip == null && other.BillingZip == null) || (this.BillingZip?.Equals(other.BillingZip) == true)) && - ((this.BillingCountry == null && other.BillingCountry == null) || (this.BillingCountry?.Equals(other.BillingCountry) == true)) && - ((this.CustomerVaultToken == null && other.CustomerVaultToken == null) || (this.CustomerVaultToken?.Equals(other.CustomerVaultToken) == true)) && - ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && - ((this.PaymentType == null && other.PaymentType == null) || (this.PaymentType?.Equals(other.PaymentType) == true)) && - ((this.BankName == null && other.BankName == null) || (this.BankName?.Equals(other.BankName) == true)) && - ((this.MaskedBankRoutingNumber == null && other.MaskedBankRoutingNumber == null) || (this.MaskedBankRoutingNumber?.Equals(other.MaskedBankRoutingNumber) == true)) && - ((this.MaskedBankAccountNumber == null && other.MaskedBankAccountNumber == null) || (this.MaskedBankAccountNumber?.Equals(other.MaskedBankAccountNumber) == true)) && - ((this.BankAccountType == null && other.BankAccountType == null) || (this.BankAccountType?.Equals(other.BankAccountType) == true)) && - ((this.BankAccountHolderType == null && other.BankAccountHolderType == null) || (this.BankAccountHolderType?.Equals(other.BankAccountHolderType) == true)) && - ((this.Verified == null && other.Verified == null) || (this.Verified?.Equals(other.Verified) == true)) && - ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && - ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)) && - ((this.Disabled == null && other.Disabled == null) || (this.Disabled?.Equals(other.Disabled) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); - toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); - toStringOutput.Add($"this.MaskedCardNumber = {(this.MaskedCardNumber == null ? "null" : this.MaskedCardNumber)}"); - toStringOutput.Add($"this.CardType = {(this.CardType == null ? "null" : this.CardType)}"); - toStringOutput.Add($"this.ExpirationMonth = {(this.ExpirationMonth == null ? "null" : this.ExpirationMonth.ToString())}"); - toStringOutput.Add($"this.ExpirationYear = {(this.ExpirationYear == null ? "null" : this.ExpirationYear.ToString())}"); - toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId.ToString())}"); - toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); - toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); - toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); - toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); - toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); - toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); - toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); - toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); - toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); - toStringOutput.Add($"this.BankName = {(this.BankName == null ? "null" : this.BankName)}"); - toStringOutput.Add($"this.MaskedBankRoutingNumber = {(this.MaskedBankRoutingNumber == null ? "null" : this.MaskedBankRoutingNumber)}"); - toStringOutput.Add($"this.MaskedBankAccountNumber = {(this.MaskedBankAccountNumber == null ? "null" : this.MaskedBankAccountNumber)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); - toStringOutput.Add($"this.Verified = {(this.Verified == null ? "null" : this.Verified.ToString())}"); - toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); - toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); - toStringOutput.Add($"this.Disabled = {(this.Disabled == null ? "null" : this.Disabled.ToString())}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/CreditCardPaymentProfile.cs b/AdvancedBilling.Standard/Models/CreditCardPaymentProfile.cs index 9581d38..d524dfd 100644 --- a/AdvancedBilling.Standard/Models/CreditCardPaymentProfile.cs +++ b/AdvancedBilling.Standard/Models/CreditCardPaymentProfile.cs @@ -21,11 +21,27 @@ namespace AdvancedBilling.Standard.Models /// public class CreditCardPaymentProfile { + private string vaultToken; + private string billingAddress; + private string billingCity; + private string billingState; + private string billingZip; + private string billingCountry; private string customerVaultToken; + private string billingAddress2; + private int? siteGatewaySettingId; private string gatewayHandle; private Dictionary shouldSerialize = new Dictionary { + { "vault_token", false }, + { "billing_address", false }, + { "billing_city", false }, + { "billing_state", false }, + { "billing_zip", false }, + { "billing_country", false }, { "customer_vault_token", false }, + { "billing_address_2", false }, + { "site_gateway_setting_id", false }, { "gateway_handle", false }, }; @@ -58,6 +74,7 @@ public CreditCardPaymentProfile() /// billing_address_2. /// payment_type. /// disabled. + /// chargify_token. /// site_gateway_setting_id. /// gateway_handle. public CreditCardPaymentProfile( @@ -65,7 +82,7 @@ public CreditCardPaymentProfile( int? id = null, string firstName = null, string lastName = null, - Models.CardType1? cardType = null, + Models.CardType? cardType = null, int? expirationMonth = null, int? expirationYear = null, int? customerId = null, @@ -78,8 +95,9 @@ public CreditCardPaymentProfile( string billingCountry = null, string customerVaultToken = null, string billingAddress2 = null, - string paymentType = null, + Models.PaymentType? paymentType = Models.PaymentType.CreditCard, bool? disabled = null, + string chargifyToken = null, int? siteGatewaySettingId = null, string gatewayHandle = null) { @@ -92,21 +110,54 @@ public CreditCardPaymentProfile( this.ExpirationYear = expirationYear; this.CustomerId = customerId; this.CurrentVault = currentVault; - this.VaultToken = vaultToken; - this.BillingAddress = billingAddress; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; + if (vaultToken != null) + { + this.VaultToken = vaultToken; + } + + if (billingAddress != null) + { + this.BillingAddress = billingAddress; + } + + if (billingCity != null) + { + this.BillingCity = billingCity; + } + + if (billingState != null) + { + this.BillingState = billingState; + } + + if (billingZip != null) + { + this.BillingZip = billingZip; + } + + if (billingCountry != null) + { + this.BillingCountry = billingCountry; + } + if (customerVaultToken != null) { this.CustomerVaultToken = customerVaultToken; } - this.BillingAddress2 = billingAddress2; + if (billingAddress2 != null) + { + this.BillingAddress2 = billingAddress2; + } + this.PaymentType = paymentType; this.Disabled = disabled; - this.SiteGatewaySettingId = siteGatewaySettingId; + this.ChargifyToken = chargifyToken; + if (siteGatewaySettingId != null) + { + this.SiteGatewaySettingId = siteGatewaySettingId; + } + if (gatewayHandle != null) { this.GatewayHandle = gatewayHandle; @@ -115,27 +166,27 @@ public CreditCardPaymentProfile( } /// - /// Gets or sets Id. + /// The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. /// [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public int? Id { get; set; } /// - /// Gets or sets FirstName. + /// The first name of the card holder. /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] public string FirstName { get; set; } /// - /// Gets or sets LastName. + /// The last name of the card holder. /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] public string LastName { get; set; } /// - /// Gets or sets MaskedCardNumber. + /// A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). /// [JsonConverter(typeof(JsonStringConverter), true)] [JsonProperty("masked_card_number")] @@ -143,25 +194,25 @@ public CreditCardPaymentProfile( public string MaskedCardNumber { get; set; } /// - /// Gets or sets CardType. + /// The type of card used. /// [JsonProperty("card_type", NullValueHandling = NullValueHandling.Ignore)] - public Models.CardType1? CardType { get; set; } + public Models.CardType? CardType { get; set; } /// - /// Gets or sets ExpirationMonth. + /// An integer representing the expiration month of the card(1 – 12). /// [JsonProperty("expiration_month", NullValueHandling = NullValueHandling.Ignore)] public int? ExpirationMonth { get; set; } /// - /// Gets or sets ExpirationYear. + /// An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). /// [JsonProperty("expiration_year", NullValueHandling = NullValueHandling.Ignore)] public int? ExpirationYear { get; set; } /// - /// Gets or sets CustomerId. + /// The Chargify-assigned id for the customer record to which the card belongs. /// [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] public int? CustomerId { get; set; } @@ -173,49 +224,121 @@ public CreditCardPaymentProfile( public Models.CurrentVault? CurrentVault { get; set; } /// - /// Gets or sets VaultToken. + /// The “token” provided by your vault storage for an already stored payment profile. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string VaultToken { get; set; } + [JsonProperty("vault_token")] + public string VaultToken + { + get + { + return this.vaultToken; + } + + set + { + this.shouldSerialize["vault_token"] = true; + this.vaultToken = value; + } + } /// - /// Gets or sets BillingAddress. + /// The current billing street address for the card. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } + [JsonProperty("billing_address")] + public string BillingAddress + { + get + { + return this.billingAddress; + } + + set + { + this.shouldSerialize["billing_address"] = true; + this.billingAddress = value; + } + } /// - /// Gets or sets BillingCity. + /// The current billing address city for the card. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } + [JsonProperty("billing_city")] + public string BillingCity + { + get + { + return this.billingCity; + } + + set + { + this.shouldSerialize["billing_city"] = true; + this.billingCity = value; + } + } /// - /// Gets or sets BillingState. + /// The current billing address state for the card. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } + [JsonProperty("billing_state")] + public string BillingState + { + get + { + return this.billingState; + } + + set + { + this.shouldSerialize["billing_state"] = true; + this.billingState = value; + } + } /// - /// Gets or sets BillingZip. + /// The current billing address zip code for the card. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } + [JsonProperty("billing_zip")] + public string BillingZip + { + get + { + return this.billingZip; + } + + set + { + this.shouldSerialize["billing_zip"] = true; + this.billingZip = value; + } + } /// - /// Gets or sets BillingCountry. + /// The current billing address country for the card. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } + [JsonProperty("billing_country")] + public string BillingCountry + { + get + { + return this.billingCountry; + } + + set + { + this.shouldSerialize["billing_country"] = true; + this.billingCountry = value; + } + } /// - /// Gets or sets CustomerVaultToken. + /// (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("customer_vault_token")] @@ -234,18 +357,29 @@ public string CustomerVaultToken } /// - /// Gets or sets BillingAddress2. + /// The current billing street address, second line, for the card. /// [JsonConverter(typeof(JsonStringConverter))] - [JsonProperty("billing_address_2", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress2 { get; set; } + [JsonProperty("billing_address_2")] + public string BillingAddress2 + { + get + { + return this.billingAddress2; + } + + set + { + this.shouldSerialize["billing_address_2"] = true; + this.billingAddress2 = value; + } + } /// /// Gets or sets PaymentType. /// - [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } + public Models.PaymentType? PaymentType { get; set; } /// /// Gets or sets Disabled. @@ -253,14 +387,33 @@ public string CustomerVaultToken [JsonProperty("disabled", NullValueHandling = NullValueHandling.Ignore)] public bool? Disabled { get; set; } + /// + /// Token received after sending billing information using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) + /// + [JsonConverter(typeof(JsonStringConverter))] + [JsonProperty("chargify_token", NullValueHandling = NullValueHandling.Ignore)] + public string ChargifyToken { get; set; } + /// /// Gets or sets SiteGatewaySettingId. /// - [JsonProperty("site_gateway_setting_id", NullValueHandling = NullValueHandling.Ignore)] - public int? SiteGatewaySettingId { get; set; } + [JsonProperty("site_gateway_setting_id")] + public int? SiteGatewaySettingId + { + get + { + return this.siteGatewaySettingId; + } + + set + { + this.shouldSerialize["site_gateway_setting_id"] = true; + this.siteGatewaySettingId = value; + } + } /// - /// Gets or sets GatewayHandle. + /// An identifier of connected gateway. /// [JsonConverter(typeof(JsonStringConverter))] [JsonProperty("gateway_handle")] @@ -288,6 +441,54 @@ public override string ToString() return $"CreditCardPaymentProfile : ({string.Join(", ", toStringOutput)})"; } + /// + /// Marks the field to not be serailized. + /// + public void UnsetVaultToken() + { + this.shouldSerialize["vault_token"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingAddress() + { + this.shouldSerialize["billing_address"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingCity() + { + this.shouldSerialize["billing_city"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingState() + { + this.shouldSerialize["billing_state"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingZip() + { + this.shouldSerialize["billing_zip"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingCountry() + { + this.shouldSerialize["billing_country"] = false; + } + /// /// Marks the field to not be serailized. /// @@ -296,6 +497,22 @@ public void UnsetCustomerVaultToken() this.shouldSerialize["customer_vault_token"] = false; } + /// + /// Marks the field to not be serailized. + /// + public void UnsetBillingAddress2() + { + this.shouldSerialize["billing_address_2"] = false; + } + + /// + /// Marks the field to not be serailized. + /// + public void UnsetSiteGatewaySettingId() + { + this.shouldSerialize["site_gateway_setting_id"] = false; + } + /// /// Marks the field to not be serailized. /// @@ -304,6 +521,60 @@ public void UnsetGatewayHandle() this.shouldSerialize["gateway_handle"] = false; } + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeVaultToken() + { + return this.shouldSerialize["vault_token"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingAddress() + { + return this.shouldSerialize["billing_address"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingCity() + { + return this.shouldSerialize["billing_city"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingState() + { + return this.shouldSerialize["billing_state"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingZip() + { + return this.shouldSerialize["billing_zip"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingCountry() + { + return this.shouldSerialize["billing_country"]; + } + /// /// Checks if the field should be serialized or not. /// @@ -313,6 +584,24 @@ public bool ShouldSerializeCustomerVaultToken() return this.shouldSerialize["customer_vault_token"]; } + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeBillingAddress2() + { + return this.shouldSerialize["billing_address_2"]; + } + + /// + /// Checks if the field should be serialized or not. + /// + /// A boolean weather the field should be serialized or not. + public bool ShouldSerializeSiteGatewaySettingId() + { + return this.shouldSerialize["site_gateway_setting_id"]; + } + /// /// Checks if the field should be serialized or not. /// @@ -353,6 +642,7 @@ public override bool Equals(object obj) ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && ((this.PaymentType == null && other.PaymentType == null) || (this.PaymentType?.Equals(other.PaymentType) == true)) && ((this.Disabled == null && other.Disabled == null) || (this.Disabled?.Equals(other.Disabled) == true)) && + ((this.ChargifyToken == null && other.ChargifyToken == null) || (this.ChargifyToken?.Equals(other.ChargifyToken) == true)) && ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)); } @@ -380,8 +670,9 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); + toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType.ToString())}"); toStringOutput.Add($"this.Disabled = {(this.Disabled == null ? "null" : this.Disabled.ToString())}"); + toStringOutput.Add($"this.ChargifyToken = {(this.ChargifyToken == null ? "null" : this.ChargifyToken)}"); toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); } diff --git a/AdvancedBilling.Standard/Models/ProductPricePointCurrencyPrice.cs b/AdvancedBilling.Standard/Models/CurrencyPricesResponse.cs similarity index 71% rename from AdvancedBilling.Standard/Models/ProductPricePointCurrencyPrice.cs rename to AdvancedBilling.Standard/Models/CurrencyPricesResponse.cs index 43d7d02..753c84f 100644 --- a/AdvancedBilling.Standard/Models/ProductPricePointCurrencyPrice.cs +++ b/AdvancedBilling.Standard/Models/CurrencyPricesResponse.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Models @@ -17,22 +17,22 @@ namespace AdvancedBilling.Standard.Models using Newtonsoft.Json.Converters; /// - /// ProductPricePointCurrencyPrice. + /// CurrencyPricesResponse. /// - public class ProductPricePointCurrencyPrice + public class CurrencyPricesResponse { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public ProductPricePointCurrencyPrice() + public CurrencyPricesResponse() { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// currency_prices. - public ProductPricePointCurrencyPrice( + public CurrencyPricesResponse( List currencyPrices) { this.CurrencyPrices = currencyPrices; @@ -51,7 +51,7 @@ public override string ToString() this.ToString(toStringOutput); - return $"ProductPricePointCurrencyPrice : ({string.Join(", ", toStringOutput)})"; + return $"CurrencyPricesResponse : ({string.Join(", ", toStringOutput)})"; } /// @@ -66,7 +66,7 @@ public override bool Equals(object obj) { return true; } - return obj is ProductPricePointCurrencyPrice other && ((this.CurrencyPrices == null && other.CurrencyPrices == null) || (this.CurrencyPrices?.Equals(other.CurrencyPrices) == true)); + return obj is CurrencyPricesResponse other && ((this.CurrencyPrices == null && other.CurrencyPrices == null) || (this.CurrencyPrices?.Equals(other.CurrencyPrices) == true)); } /// diff --git a/AdvancedBilling.Standard/Models/GetOneTimeTokenPaymentProfile.cs b/AdvancedBilling.Standard/Models/GetOneTimeTokenPaymentProfile.cs index 0e05aae..c893573 100644 --- a/AdvancedBilling.Standard/Models/GetOneTimeTokenPaymentProfile.cs +++ b/AdvancedBilling.Standard/Models/GetOneTimeTokenPaymentProfile.cs @@ -68,7 +68,7 @@ public GetOneTimeTokenPaymentProfile( string firstName, string lastName, string maskedCardNumber, - string cardType, + Models.CardType cardType, double expirationMonth, double expirationYear, Models.CurrentVault currentVault, @@ -163,10 +163,10 @@ public string Id public string MaskedCardNumber { get; set; } /// - /// Gets or sets CardType. + /// The type of card used. /// [JsonProperty("card_type")] - public string CardType { get; set; } + public Models.CardType CardType { get; set; } /// /// Gets or sets ExpirationMonth. @@ -394,7 +394,7 @@ public override bool Equals(object obj) ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && ((this.MaskedCardNumber == null && other.MaskedCardNumber == null) || (this.MaskedCardNumber?.Equals(other.MaskedCardNumber) == true)) && - ((this.CardType == null && other.CardType == null) || (this.CardType?.Equals(other.CardType) == true)) && + this.CardType.Equals(other.CardType) && this.ExpirationMonth.Equals(other.ExpirationMonth) && this.ExpirationYear.Equals(other.ExpirationYear) && ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && @@ -423,7 +423,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); toStringOutput.Add($"this.MaskedCardNumber = {(this.MaskedCardNumber == null ? "null" : this.MaskedCardNumber)}"); - toStringOutput.Add($"this.CardType = {(this.CardType == null ? "null" : this.CardType)}"); + toStringOutput.Add($"this.CardType = {this.CardType}"); toStringOutput.Add($"this.ExpirationMonth = {this.ExpirationMonth}"); toStringOutput.Add($"this.ExpirationYear = {this.ExpirationYear}"); toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId)}"); diff --git a/AdvancedBilling.Standard/Models/InvoiceCredit.cs b/AdvancedBilling.Standard/Models/InvoiceCredit.cs index 7ff710d..91fe80f 100644 --- a/AdvancedBilling.Standard/Models/InvoiceCredit.cs +++ b/AdvancedBilling.Standard/Models/InvoiceCredit.cs @@ -42,7 +42,7 @@ public InvoiceCredit( string uid = null, string creditNoteNumber = null, string creditNoteUid = null, - string transactionTime = null, + DateTimeOffset? transactionTime = null, string memo = null, string originalAmount = null, string appliedAmount = null) @@ -77,8 +77,9 @@ public InvoiceCredit( /// /// Gets or sets TransactionTime. /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("transaction_time", NullValueHandling = NullValueHandling.Ignore)] - public string TransactionTime { get; set; } + public DateTimeOffset? TransactionTime { get; set; } /// /// Gets or sets Memo. @@ -138,7 +139,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.Uid = {(this.Uid == null ? "null" : this.Uid)}"); toStringOutput.Add($"this.CreditNoteNumber = {(this.CreditNoteNumber == null ? "null" : this.CreditNoteNumber)}"); toStringOutput.Add($"this.CreditNoteUid = {(this.CreditNoteUid == null ? "null" : this.CreditNoteUid)}"); - toStringOutput.Add($"this.TransactionTime = {(this.TransactionTime == null ? "null" : this.TransactionTime)}"); + toStringOutput.Add($"this.TransactionTime = {(this.TransactionTime == null ? "null" : this.TransactionTime.ToString())}"); toStringOutput.Add($"this.Memo = {(this.Memo == null ? "null" : this.Memo)}"); toStringOutput.Add($"this.OriginalAmount = {(this.OriginalAmount == null ? "null" : this.OriginalAmount)}"); toStringOutput.Add($"this.AppliedAmount = {(this.AppliedAmount == null ? "null" : this.AppliedAmount)}"); diff --git a/AdvancedBilling.Standard/Models/InvoiceEvent1.cs b/AdvancedBilling.Standard/Models/InvoiceEvent1.cs index cde70d8..c9270d2 100644 --- a/AdvancedBilling.Standard/Models/InvoiceEvent1.cs +++ b/AdvancedBilling.Standard/Models/InvoiceEvent1.cs @@ -70,7 +70,7 @@ public InvoiceEvent1( string memo = null, string role = null, bool? consolidatedInvoice = null, - List appliedCreditNotes = null, + List appliedCreditNotes = null, string debitNoteNumber = null, string debitNoteUid = null, InvoiceEvent1PaymentMethod paymentMethod = null, @@ -179,7 +179,7 @@ public InvoiceEvent1( /// List of credit notes applied to children invoices (if consolidated invoice) /// [JsonProperty("applied_credit_notes", NullValueHandling = NullValueHandling.Ignore)] - public List AppliedCreditNotes { get; set; } + public List AppliedCreditNotes { get; set; } /// /// A unique, identifying string that appears on the debit note and in places it is referenced. diff --git a/AdvancedBilling.Standard/Models/InvoiceLineItem.cs b/AdvancedBilling.Standard/Models/InvoiceLineItem.cs index 1ae4683..6a30b34 100644 --- a/AdvancedBilling.Standard/Models/InvoiceLineItem.cs +++ b/AdvancedBilling.Standard/Models/InvoiceLineItem.cs @@ -80,8 +80,8 @@ public InvoiceLineItem( string taxAmount = null, string totalAmount = null, bool? tieredUnitPrice = null, - string periodRangeStart = null, - string periodRangeEnd = null, + DateTime? periodRangeStart = null, + DateTime? periodRangeEnd = null, int? transactionId = null, int? productId = null, int? productVersion = null, @@ -211,8 +211,9 @@ public InvoiceLineItem( /// * For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date. /// * For non-periodic charges, this date and the end date will match. /// + [JsonConverter(typeof(CustomDateTimeConverter), "yyyy'-'MM'-'dd")] [JsonProperty("period_range_start", NullValueHandling = NullValueHandling.Ignore)] - public string PeriodRangeStart { get; set; } + public DateTime? PeriodRangeStart { get; set; } /// /// End date for the period covered by this line. The format is `"YYYY-MM-DD"`. @@ -220,8 +221,9 @@ public InvoiceLineItem( /// * For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date. /// * For non-periodic charges, this date and the start date will match. /// + [JsonConverter(typeof(CustomDateTimeConverter), "yyyy'-'MM'-'dd")] [JsonProperty("period_range_end", NullValueHandling = NullValueHandling.Ignore)] - public string PeriodRangeEnd { get; set; } + public DateTime? PeriodRangeEnd { get; set; } /// /// Gets or sets TransactionId. @@ -513,8 +515,8 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.TaxAmount = {(this.TaxAmount == null ? "null" : this.TaxAmount)}"); toStringOutput.Add($"this.TotalAmount = {(this.TotalAmount == null ? "null" : this.TotalAmount)}"); toStringOutput.Add($"this.TieredUnitPrice = {(this.TieredUnitPrice == null ? "null" : this.TieredUnitPrice.ToString())}"); - toStringOutput.Add($"this.PeriodRangeStart = {(this.PeriodRangeStart == null ? "null" : this.PeriodRangeStart)}"); - toStringOutput.Add($"this.PeriodRangeEnd = {(this.PeriodRangeEnd == null ? "null" : this.PeriodRangeEnd)}"); + toStringOutput.Add($"this.PeriodRangeStart = {(this.PeriodRangeStart == null ? "null" : this.PeriodRangeStart.ToString())}"); + toStringOutput.Add($"this.PeriodRangeEnd = {(this.PeriodRangeEnd == null ? "null" : this.PeriodRangeEnd.ToString())}"); toStringOutput.Add($"this.TransactionId = {(this.TransactionId == null ? "null" : this.TransactionId.ToString())}"); toStringOutput.Add($"this.ProductId = {(this.ProductId == null ? "null" : this.ProductId.ToString())}"); toStringOutput.Add($"this.ProductVersion = {(this.ProductVersion == null ? "null" : this.ProductVersion.ToString())}"); diff --git a/AdvancedBilling.Standard/Models/InvoicePayment.cs b/AdvancedBilling.Standard/Models/InvoicePayment.cs index ccb7e85..e4c6d3a 100644 --- a/AdvancedBilling.Standard/Models/InvoicePayment.cs +++ b/AdvancedBilling.Standard/Models/InvoicePayment.cs @@ -50,7 +50,7 @@ public InvoicePayment() /// gateway_used. /// gateway_transaction_id. public InvoicePayment( - string transactionTime = null, + DateTimeOffset? transactionTime = null, string memo = null, string originalAmount = null, string appliedAmount = null, @@ -84,8 +84,9 @@ public InvoicePayment( /// /// Gets or sets TransactionTime. /// + [JsonConverter(typeof(IsoDateTimeConverter))] [JsonProperty("transaction_time", NullValueHandling = NullValueHandling.Ignore)] - public string TransactionTime { get; set; } + public DateTimeOffset? TransactionTime { get; set; } /// /// Gets or sets Memo. @@ -239,7 +240,7 @@ public override bool Equals(object obj) /// List of strings. protected void ToString(List toStringOutput) { - toStringOutput.Add($"this.TransactionTime = {(this.TransactionTime == null ? "null" : this.TransactionTime)}"); + toStringOutput.Add($"this.TransactionTime = {(this.TransactionTime == null ? "null" : this.TransactionTime.ToString())}"); toStringOutput.Add($"this.Memo = {(this.Memo == null ? "null" : this.Memo)}"); toStringOutput.Add($"this.OriginalAmount = {(this.OriginalAmount == null ? "null" : this.OriginalAmount)}"); toStringOutput.Add($"this.AppliedAmount = {(this.AppliedAmount == null ? "null" : this.AppliedAmount)}"); diff --git a/AdvancedBilling.Standard/Models/ListPaymentProfileItem.cs b/AdvancedBilling.Standard/Models/ListPaymentProfileItem.cs deleted file mode 100644 index f783571..0000000 --- a/AdvancedBilling.Standard/Models/ListPaymentProfileItem.cs +++ /dev/null @@ -1,340 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// ListPaymentProfileItem. - /// - public class ListPaymentProfileItem - { - private string customerVaultToken; - private Dictionary shouldSerialize = new Dictionary - { - { "customer_vault_token", false }, - }; - - /// - /// Initializes a new instance of the class. - /// - public ListPaymentProfileItem() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// id. - /// first_name. - /// last_name. - /// customer_id. - /// current_vault. - /// vault_token. - /// billing_address. - /// billing_city. - /// billing_state. - /// billing_zip. - /// billing_country. - /// customer_vault_token. - /// billing_address_2. - /// bank_name. - /// masked_bank_routing_number. - /// masked_bank_account_number. - /// bank_account_type. - /// bank_account_holder_type. - /// payment_type. - /// site_gateway_setting_id. - /// gateway_handle. - public ListPaymentProfileItem( - int? id = null, - string firstName = null, - string lastName = null, - int? customerId = null, - Models.CurrentVault? currentVault = null, - string vaultToken = null, - string billingAddress = null, - string billingCity = null, - string billingState = null, - string billingZip = null, - string billingCountry = null, - string customerVaultToken = null, - string billingAddress2 = null, - string bankName = null, - string maskedBankRoutingNumber = null, - string maskedBankAccountNumber = null, - string bankAccountType = null, - string bankAccountHolderType = null, - string paymentType = null, - int? siteGatewaySettingId = null, - string gatewayHandle = null) - { - this.Id = id; - this.FirstName = firstName; - this.LastName = lastName; - this.CustomerId = customerId; - this.CurrentVault = currentVault; - this.VaultToken = vaultToken; - this.BillingAddress = billingAddress; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; - if (customerVaultToken != null) - { - this.CustomerVaultToken = customerVaultToken; - } - - this.BillingAddress2 = billingAddress2; - this.BankName = bankName; - this.MaskedBankRoutingNumber = maskedBankRoutingNumber; - this.MaskedBankAccountNumber = maskedBankAccountNumber; - this.BankAccountType = bankAccountType; - this.BankAccountHolderType = bankAccountHolderType; - this.PaymentType = paymentType; - this.SiteGatewaySettingId = siteGatewaySettingId; - this.GatewayHandle = gatewayHandle; - } - - /// - /// Gets or sets Id. - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// Gets or sets FirstName. - /// - [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - /// - /// Gets or sets LastName. - /// - [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - /// - /// Gets or sets CustomerId. - /// - [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] - public int? CustomerId { get; set; } - - /// - /// The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - /// - [JsonProperty("current_vault", NullValueHandling = NullValueHandling.Ignore)] - public Models.CurrentVault? CurrentVault { get; set; } - - /// - /// Gets or sets VaultToken. - /// - [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string VaultToken { get; set; } - - /// - /// Gets or sets BillingAddress. - /// - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } - - /// - /// Gets or sets BillingCity. - /// - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } - - /// - /// Gets or sets BillingState. - /// - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } - - /// - /// Gets or sets BillingZip. - /// - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } - - /// - /// Gets or sets BillingCountry. - /// - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } - - /// - /// Gets or sets CustomerVaultToken. - /// - [JsonProperty("customer_vault_token")] - public string CustomerVaultToken - { - get - { - return this.customerVaultToken; - } - - set - { - this.shouldSerialize["customer_vault_token"] = true; - this.customerVaultToken = value; - } - } - - /// - /// Gets or sets BillingAddress2. - /// - [JsonProperty("billing_address_2", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress2 { get; set; } - - /// - /// Gets or sets BankName. - /// - [JsonProperty("bank_name", NullValueHandling = NullValueHandling.Ignore)] - public string BankName { get; set; } - - /// - /// Gets or sets MaskedBankRoutingNumber. - /// - [JsonProperty("masked_bank_routing_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankRoutingNumber { get; set; } - - /// - /// Gets or sets MaskedBankAccountNumber. - /// - [JsonProperty("masked_bank_account_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankAccountNumber { get; set; } - - /// - /// Gets or sets BankAccountType. - /// - [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } - - /// - /// Gets or sets BankAccountHolderType. - /// - [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } - - /// - /// Gets or sets PaymentType. - /// - [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } - - /// - /// Gets or sets SiteGatewaySettingId. - /// - [JsonProperty("site_gateway_setting_id", NullValueHandling = NullValueHandling.Ignore)] - public int? SiteGatewaySettingId { get; set; } - - /// - /// Gets or sets GatewayHandle. - /// - [JsonProperty("gateway_handle", NullValueHandling = NullValueHandling.Ignore)] - public string GatewayHandle { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"ListPaymentProfileItem : ({string.Join(", ", toStringOutput)})"; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetCustomerVaultToken() - { - this.shouldSerialize["customer_vault_token"] = false; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeCustomerVaultToken() - { - return this.shouldSerialize["customer_vault_token"]; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is ListPaymentProfileItem other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && - ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && - ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && - ((this.CurrentVault == null && other.CurrentVault == null) || (this.CurrentVault?.Equals(other.CurrentVault) == true)) && - ((this.VaultToken == null && other.VaultToken == null) || (this.VaultToken?.Equals(other.VaultToken) == true)) && - ((this.BillingAddress == null && other.BillingAddress == null) || (this.BillingAddress?.Equals(other.BillingAddress) == true)) && - ((this.BillingCity == null && other.BillingCity == null) || (this.BillingCity?.Equals(other.BillingCity) == true)) && - ((this.BillingState == null && other.BillingState == null) || (this.BillingState?.Equals(other.BillingState) == true)) && - ((this.BillingZip == null && other.BillingZip == null) || (this.BillingZip?.Equals(other.BillingZip) == true)) && - ((this.BillingCountry == null && other.BillingCountry == null) || (this.BillingCountry?.Equals(other.BillingCountry) == true)) && - ((this.CustomerVaultToken == null && other.CustomerVaultToken == null) || (this.CustomerVaultToken?.Equals(other.CustomerVaultToken) == true)) && - ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && - ((this.BankName == null && other.BankName == null) || (this.BankName?.Equals(other.BankName) == true)) && - ((this.MaskedBankRoutingNumber == null && other.MaskedBankRoutingNumber == null) || (this.MaskedBankRoutingNumber?.Equals(other.MaskedBankRoutingNumber) == true)) && - ((this.MaskedBankAccountNumber == null && other.MaskedBankAccountNumber == null) || (this.MaskedBankAccountNumber?.Equals(other.MaskedBankAccountNumber) == true)) && - ((this.BankAccountType == null && other.BankAccountType == null) || (this.BankAccountType?.Equals(other.BankAccountType) == true)) && - ((this.BankAccountHolderType == null && other.BankAccountHolderType == null) || (this.BankAccountHolderType?.Equals(other.BankAccountHolderType) == true)) && - ((this.PaymentType == null && other.PaymentType == null) || (this.PaymentType?.Equals(other.PaymentType) == true)) && - ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && - ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); - toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); - toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId.ToString())}"); - toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); - toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); - toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); - toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); - toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); - toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); - toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); - toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); - toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.BankName = {(this.BankName == null ? "null" : this.BankName)}"); - toStringOutput.Add($"this.MaskedBankRoutingNumber = {(this.MaskedBankRoutingNumber == null ? "null" : this.MaskedBankRoutingNumber)}"); - toStringOutput.Add($"this.MaskedBankAccountNumber = {(this.MaskedBankAccountNumber == null ? "null" : this.MaskedBankAccountNumber)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); - toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); - toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/PaymentProfile.cs b/AdvancedBilling.Standard/Models/PaymentProfile.cs deleted file mode 100644 index e4cac4a..0000000 --- a/AdvancedBilling.Standard/Models/PaymentProfile.cs +++ /dev/null @@ -1,666 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// PaymentProfile. - /// - public class PaymentProfile - { - private string vaultToken; - private string billingAddress; - private string billingCity; - private string billingState; - private string billingZip; - private string billingCountry; - private string customerVaultToken; - private string billingAddress2; - private int? siteGatewaySettingId; - private string gatewayHandle; - private Dictionary shouldSerialize = new Dictionary - { - { "vault_token", false }, - { "billing_address", false }, - { "billing_city", false }, - { "billing_state", false }, - { "billing_zip", false }, - { "billing_country", false }, - { "customer_vault_token", false }, - { "billing_address_2", false }, - { "site_gateway_setting_id", false }, - { "gateway_handle", false }, - }; - - /// - /// Initializes a new instance of the class. - /// - public PaymentProfile() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// id. - /// first_name. - /// last_name. - /// masked_card_number. - /// card_type. - /// expiration_month. - /// expiration_year. - /// customer_id. - /// current_vault. - /// vault_token. - /// billing_address. - /// billing_city. - /// billing_state. - /// billing_zip. - /// billing_country. - /// customer_vault_token. - /// billing_address_2. - /// payment_type. - /// disabled. - /// chargify_token. - /// site_gateway_setting_id. - /// gateway_handle. - public PaymentProfile( - int? id = null, - string firstName = null, - string lastName = null, - string maskedCardNumber = null, - Models.CardType? cardType = null, - int? expirationMonth = null, - int? expirationYear = null, - int? customerId = null, - Models.CurrentVault? currentVault = null, - string vaultToken = null, - string billingAddress = null, - string billingCity = null, - string billingState = null, - string billingZip = null, - string billingCountry = null, - string customerVaultToken = null, - string billingAddress2 = null, - Models.PaymentType? paymentType = Models.PaymentType.CreditCard, - bool? disabled = null, - string chargifyToken = null, - int? siteGatewaySettingId = null, - string gatewayHandle = null) - { - this.Id = id; - this.FirstName = firstName; - this.LastName = lastName; - this.MaskedCardNumber = maskedCardNumber; - this.CardType = cardType; - this.ExpirationMonth = expirationMonth; - this.ExpirationYear = expirationYear; - this.CustomerId = customerId; - this.CurrentVault = currentVault; - if (vaultToken != null) - { - this.VaultToken = vaultToken; - } - - if (billingAddress != null) - { - this.BillingAddress = billingAddress; - } - - if (billingCity != null) - { - this.BillingCity = billingCity; - } - - if (billingState != null) - { - this.BillingState = billingState; - } - - if (billingZip != null) - { - this.BillingZip = billingZip; - } - - if (billingCountry != null) - { - this.BillingCountry = billingCountry; - } - - if (customerVaultToken != null) - { - this.CustomerVaultToken = customerVaultToken; - } - - if (billingAddress2 != null) - { - this.BillingAddress2 = billingAddress2; - } - - this.PaymentType = paymentType; - this.Disabled = disabled; - this.ChargifyToken = chargifyToken; - if (siteGatewaySettingId != null) - { - this.SiteGatewaySettingId = siteGatewaySettingId; - } - - if (gatewayHandle != null) - { - this.GatewayHandle = gatewayHandle; - } - - } - - /// - /// The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// The first name of the card holder. - /// - [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - /// - /// The last name of the card holder. - /// - [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - /// - /// A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). - /// - [JsonProperty("masked_card_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedCardNumber { get; set; } - - /// - /// The type of card used. - /// - [JsonProperty("card_type", NullValueHandling = NullValueHandling.Ignore)] - public Models.CardType? CardType { get; set; } - - /// - /// An integer representing the expiration month of the card(1 – 12). - /// - [JsonProperty("expiration_month", NullValueHandling = NullValueHandling.Ignore)] - public int? ExpirationMonth { get; set; } - - /// - /// An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). - /// - [JsonProperty("expiration_year", NullValueHandling = NullValueHandling.Ignore)] - public int? ExpirationYear { get; set; } - - /// - /// The Chargify-assigned id for the customer record to which the card belongs. - /// - [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] - public int? CustomerId { get; set; } - - /// - /// The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - /// - [JsonProperty("current_vault", NullValueHandling = NullValueHandling.Ignore)] - public Models.CurrentVault? CurrentVault { get; set; } - - /// - /// The “token” provided by your vault storage for an already stored payment profile. - /// - [JsonProperty("vault_token")] - public string VaultToken - { - get - { - return this.vaultToken; - } - - set - { - this.shouldSerialize["vault_token"] = true; - this.vaultToken = value; - } - } - - /// - /// The current billing street address for the card. - /// - [JsonProperty("billing_address")] - public string BillingAddress - { - get - { - return this.billingAddress; - } - - set - { - this.shouldSerialize["billing_address"] = true; - this.billingAddress = value; - } - } - - /// - /// The current billing address city for the card. - /// - [JsonProperty("billing_city")] - public string BillingCity - { - get - { - return this.billingCity; - } - - set - { - this.shouldSerialize["billing_city"] = true; - this.billingCity = value; - } - } - - /// - /// The current billing address state for the card. - /// - [JsonProperty("billing_state")] - public string BillingState - { - get - { - return this.billingState; - } - - set - { - this.shouldSerialize["billing_state"] = true; - this.billingState = value; - } - } - - /// - /// The current billing address zip code for the card. - /// - [JsonProperty("billing_zip")] - public string BillingZip - { - get - { - return this.billingZip; - } - - set - { - this.shouldSerialize["billing_zip"] = true; - this.billingZip = value; - } - } - - /// - /// The current billing address country for the card. - /// - [JsonProperty("billing_country")] - public string BillingCountry - { - get - { - return this.billingCountry; - } - - set - { - this.shouldSerialize["billing_country"] = true; - this.billingCountry = value; - } - } - - /// - /// (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. - /// - [JsonProperty("customer_vault_token")] - public string CustomerVaultToken - { - get - { - return this.customerVaultToken; - } - - set - { - this.shouldSerialize["customer_vault_token"] = true; - this.customerVaultToken = value; - } - } - - /// - /// The current billing street address, second line, for the card. - /// - [JsonProperty("billing_address_2")] - public string BillingAddress2 - { - get - { - return this.billingAddress2; - } - - set - { - this.shouldSerialize["billing_address_2"] = true; - this.billingAddress2 = value; - } - } - - /// - /// Gets or sets PaymentType. - /// - [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public Models.PaymentType? PaymentType { get; set; } - - /// - /// Gets or sets Disabled. - /// - [JsonProperty("disabled", NullValueHandling = NullValueHandling.Ignore)] - public bool? Disabled { get; set; } - - /// - /// Token received after sending billing informations using chargify.js. - /// - [JsonProperty("chargify_token", NullValueHandling = NullValueHandling.Ignore)] - public string ChargifyToken { get; set; } - - /// - /// Gets or sets SiteGatewaySettingId. - /// - [JsonProperty("site_gateway_setting_id")] - public int? SiteGatewaySettingId - { - get - { - return this.siteGatewaySettingId; - } - - set - { - this.shouldSerialize["site_gateway_setting_id"] = true; - this.siteGatewaySettingId = value; - } - } - - /// - /// An identifier of connected gateway. - /// - [JsonProperty("gateway_handle")] - public string GatewayHandle - { - get - { - return this.gatewayHandle; - } - - set - { - this.shouldSerialize["gateway_handle"] = true; - this.gatewayHandle = value; - } - } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"PaymentProfile : ({string.Join(", ", toStringOutput)})"; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetVaultToken() - { - this.shouldSerialize["vault_token"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingAddress() - { - this.shouldSerialize["billing_address"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingCity() - { - this.shouldSerialize["billing_city"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingState() - { - this.shouldSerialize["billing_state"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingZip() - { - this.shouldSerialize["billing_zip"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingCountry() - { - this.shouldSerialize["billing_country"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetCustomerVaultToken() - { - this.shouldSerialize["customer_vault_token"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetBillingAddress2() - { - this.shouldSerialize["billing_address_2"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetSiteGatewaySettingId() - { - this.shouldSerialize["site_gateway_setting_id"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetGatewayHandle() - { - this.shouldSerialize["gateway_handle"] = false; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeVaultToken() - { - return this.shouldSerialize["vault_token"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingAddress() - { - return this.shouldSerialize["billing_address"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingCity() - { - return this.shouldSerialize["billing_city"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingState() - { - return this.shouldSerialize["billing_state"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingZip() - { - return this.shouldSerialize["billing_zip"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingCountry() - { - return this.shouldSerialize["billing_country"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeCustomerVaultToken() - { - return this.shouldSerialize["customer_vault_token"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeBillingAddress2() - { - return this.shouldSerialize["billing_address_2"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeSiteGatewaySettingId() - { - return this.shouldSerialize["site_gateway_setting_id"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeGatewayHandle() - { - return this.shouldSerialize["gateway_handle"]; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is PaymentProfile other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && - ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && - ((this.MaskedCardNumber == null && other.MaskedCardNumber == null) || (this.MaskedCardNumber?.Equals(other.MaskedCardNumber) == true)) && - ((this.CardType == null && other.CardType == null) || (this.CardType?.Equals(other.CardType) == true)) && - ((this.ExpirationMonth == null && other.ExpirationMonth == null) || (this.ExpirationMonth?.Equals(other.ExpirationMonth) == true)) && - ((this.ExpirationYear == null && other.ExpirationYear == null) || (this.ExpirationYear?.Equals(other.ExpirationYear) == true)) && - ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && - ((this.CurrentVault == null && other.CurrentVault == null) || (this.CurrentVault?.Equals(other.CurrentVault) == true)) && - ((this.VaultToken == null && other.VaultToken == null) || (this.VaultToken?.Equals(other.VaultToken) == true)) && - ((this.BillingAddress == null && other.BillingAddress == null) || (this.BillingAddress?.Equals(other.BillingAddress) == true)) && - ((this.BillingCity == null && other.BillingCity == null) || (this.BillingCity?.Equals(other.BillingCity) == true)) && - ((this.BillingState == null && other.BillingState == null) || (this.BillingState?.Equals(other.BillingState) == true)) && - ((this.BillingZip == null && other.BillingZip == null) || (this.BillingZip?.Equals(other.BillingZip) == true)) && - ((this.BillingCountry == null && other.BillingCountry == null) || (this.BillingCountry?.Equals(other.BillingCountry) == true)) && - ((this.CustomerVaultToken == null && other.CustomerVaultToken == null) || (this.CustomerVaultToken?.Equals(other.CustomerVaultToken) == true)) && - ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && - ((this.PaymentType == null && other.PaymentType == null) || (this.PaymentType?.Equals(other.PaymentType) == true)) && - ((this.Disabled == null && other.Disabled == null) || (this.Disabled?.Equals(other.Disabled) == true)) && - ((this.ChargifyToken == null && other.ChargifyToken == null) || (this.ChargifyToken?.Equals(other.ChargifyToken) == true)) && - ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && - ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); - toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); - toStringOutput.Add($"this.MaskedCardNumber = {(this.MaskedCardNumber == null ? "null" : this.MaskedCardNumber)}"); - toStringOutput.Add($"this.CardType = {(this.CardType == null ? "null" : this.CardType.ToString())}"); - toStringOutput.Add($"this.ExpirationMonth = {(this.ExpirationMonth == null ? "null" : this.ExpirationMonth.ToString())}"); - toStringOutput.Add($"this.ExpirationYear = {(this.ExpirationYear == null ? "null" : this.ExpirationYear.ToString())}"); - toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId.ToString())}"); - toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); - toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); - toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); - toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); - toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); - toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); - toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); - toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); - toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType.ToString())}"); - toStringOutput.Add($"this.Disabled = {(this.Disabled == null ? "null" : this.Disabled.ToString())}"); - toStringOutput.Add($"this.ChargifyToken = {(this.ChargifyToken == null ? "null" : this.ChargifyToken)}"); - toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); - toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/PaymentProfileResponse.cs b/AdvancedBilling.Standard/Models/PaymentProfileResponse.cs index 328093b..471e06a 100644 --- a/AdvancedBilling.Standard/Models/PaymentProfileResponse.cs +++ b/AdvancedBilling.Standard/Models/PaymentProfileResponse.cs @@ -12,6 +12,7 @@ namespace AdvancedBilling.Standard.Models using System.Threading.Tasks; using APIMatic.Core.Utilities.Converters; using AdvancedBilling.Standard; + using AdvancedBilling.Standard.Models.Containers; using AdvancedBilling.Standard.Utilities; using Newtonsoft.Json; using Newtonsoft.Json.Converters; @@ -33,7 +34,7 @@ public PaymentProfileResponse() /// /// payment_profile. public PaymentProfileResponse( - Models.PaymentProfile paymentProfile) + PaymentProfileResponsePaymentProfile paymentProfile) { this.PaymentProfile = paymentProfile; } @@ -42,7 +43,7 @@ public PaymentProfileResponse( /// Gets or sets PaymentProfile. /// [JsonProperty("payment_profile")] - public Models.PaymentProfile PaymentProfile { get; set; } + public PaymentProfileResponsePaymentProfile PaymentProfile { get; set; } /// public override string ToString() @@ -75,7 +76,7 @@ public override bool Equals(object obj) /// List of strings. protected void ToString(List toStringOutput) { - toStringOutput.Add($"this.PaymentProfile = {(this.PaymentProfile == null ? "null" : this.PaymentProfile.ToString())}"); + toStringOutput.Add($"PaymentProfile = {(this.PaymentProfile == null ? "null" : this.PaymentProfile.ToString())}"); } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/PrepaidUsageComponent.cs b/AdvancedBilling.Standard/Models/PrepaidUsageComponent.cs index 0f3a031..ae5ddbf 100644 --- a/AdvancedBilling.Standard/Models/PrepaidUsageComponent.cs +++ b/AdvancedBilling.Standard/Models/PrepaidUsageComponent.cs @@ -63,7 +63,7 @@ public PrepaidUsageComponent() /// allow_fractional_quantities. /// public_signup_page_ids. public PrepaidUsageComponent( - string name = null, + string name, string unitName = null, string description = null, string handle = null, @@ -121,7 +121,7 @@ public PrepaidUsageComponent( /// /// A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". /// - [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] + [JsonProperty("name")] public string Name { get; set; } /// diff --git a/AdvancedBilling.Standard/Models/PricePoint.cs b/AdvancedBilling.Standard/Models/PricePoint.cs index 6a1f8dc..eb43854 100644 --- a/AdvancedBilling.Standard/Models/PricePoint.cs +++ b/AdvancedBilling.Standard/Models/PricePoint.cs @@ -36,6 +36,7 @@ public PricePoint() /// pricing_scheme. /// prices. /// use_site_exchange_rate. + /// tax_included. /// interval. /// interval_unit. /// overage_pricing. @@ -49,6 +50,7 @@ public PricePoint( Models.PricingScheme? pricingScheme = null, List prices = null, bool? useSiteExchangeRate = true, + bool? taxIncluded = null, int? interval = null, Models.IntervalUnit? intervalUnit = null, Models.OveragePricing overagePricing = null, @@ -62,6 +64,7 @@ public PricePoint( this.PricingScheme = pricingScheme; this.Prices = prices; this.UseSiteExchangeRate = useSiteExchangeRate; + this.TaxIncluded = taxIncluded; this.Interval = interval; this.IntervalUnit = intervalUnit; this.OveragePricing = overagePricing; @@ -101,6 +104,12 @@ public PricePoint( [JsonProperty("use_site_exchange_rate", NullValueHandling = NullValueHandling.Ignore)] public bool? UseSiteExchangeRate { get; set; } + /// + /// Whether or not the price point includes tax + /// + [JsonProperty("tax_included", NullValueHandling = NullValueHandling.Ignore)] + public bool? TaxIncluded { get; set; } + /// /// The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. /// @@ -170,6 +179,7 @@ public override bool Equals(object obj) ((this.PricingScheme == null && other.PricingScheme == null) || (this.PricingScheme?.Equals(other.PricingScheme) == true)) && ((this.Prices == null && other.Prices == null) || (this.Prices?.Equals(other.Prices) == true)) && ((this.UseSiteExchangeRate == null && other.UseSiteExchangeRate == null) || (this.UseSiteExchangeRate?.Equals(other.UseSiteExchangeRate) == true)) && + ((this.TaxIncluded == null && other.TaxIncluded == null) || (this.TaxIncluded?.Equals(other.TaxIncluded) == true)) && ((this.Interval == null && other.Interval == null) || (this.Interval?.Equals(other.Interval) == true)) && ((this.IntervalUnit == null && other.IntervalUnit == null) || (this.IntervalUnit?.Equals(other.IntervalUnit) == true)) && ((this.OveragePricing == null && other.OveragePricing == null) || (this.OveragePricing?.Equals(other.OveragePricing) == true)) && @@ -190,6 +200,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.PricingScheme = {(this.PricingScheme == null ? "null" : this.PricingScheme.ToString())}"); toStringOutput.Add($"this.Prices = {(this.Prices == null ? "null" : $"[{string.Join(", ", this.Prices)} ]")}"); toStringOutput.Add($"this.UseSiteExchangeRate = {(this.UseSiteExchangeRate == null ? "null" : this.UseSiteExchangeRate.ToString())}"); + toStringOutput.Add($"this.TaxIncluded = {(this.TaxIncluded == null ? "null" : this.TaxIncluded.ToString())}"); toStringOutput.Add($"this.Interval = {(this.Interval == null ? "null" : this.Interval.ToString())}"); toStringOutput.Add($"this.IntervalUnit = {(this.IntervalUnit == null ? "null" : this.IntervalUnit.ToString())}"); toStringOutput.Add($"this.OveragePricing = {(this.OveragePricing == null ? "null" : this.OveragePricing.ToString())}"); diff --git a/AdvancedBilling.Standard/Models/ProductPricePoint.cs b/AdvancedBilling.Standard/Models/ProductPricePoint.cs index 3cb09f0..f643a19 100644 --- a/AdvancedBilling.Standard/Models/ProductPricePoint.cs +++ b/AdvancedBilling.Standard/Models/ProductPricePoint.cs @@ -62,6 +62,7 @@ public ProductPricePoint() /// type. /// tax_included. /// subscription_id. + /// currency_prices. public ProductPricePoint( int? id = null, string name = null, @@ -85,7 +86,8 @@ public ProductPricePoint( bool? useSiteExchangeRate = null, Models.PricePointType? type = null, bool? taxIncluded = null, - int? subscriptionId = null) + int? subscriptionId = null, + List currencyPrices = null) { this.Id = id; this.Name = name; @@ -118,6 +120,7 @@ public ProductPricePoint( this.SubscriptionId = subscriptionId; } + this.CurrencyPrices = currencyPrices; } /// @@ -285,6 +288,12 @@ public int? SubscriptionId } } + /// + /// An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. + /// + [JsonProperty("currency_prices", NullValueHandling = NullValueHandling.Ignore)] + public List CurrencyPrices { get; set; } + /// public override string ToString() { @@ -363,7 +372,8 @@ public override bool Equals(object obj) ((this.UseSiteExchangeRate == null && other.UseSiteExchangeRate == null) || (this.UseSiteExchangeRate?.Equals(other.UseSiteExchangeRate) == true)) && ((this.Type == null && other.Type == null) || (this.Type?.Equals(other.Type) == true)) && ((this.TaxIncluded == null && other.TaxIncluded == null) || (this.TaxIncluded?.Equals(other.TaxIncluded) == true)) && - ((this.SubscriptionId == null && other.SubscriptionId == null) || (this.SubscriptionId?.Equals(other.SubscriptionId) == true)); + ((this.SubscriptionId == null && other.SubscriptionId == null) || (this.SubscriptionId?.Equals(other.SubscriptionId) == true)) && + ((this.CurrencyPrices == null && other.CurrencyPrices == null) || (this.CurrencyPrices?.Equals(other.CurrencyPrices) == true)); } /// @@ -395,6 +405,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.Type = {(this.Type == null ? "null" : this.Type.ToString())}"); toStringOutput.Add($"this.TaxIncluded = {(this.TaxIncluded == null ? "null" : this.TaxIncluded.ToString())}"); toStringOutput.Add($"this.SubscriptionId = {(this.SubscriptionId == null ? "null" : this.SubscriptionId.ToString())}"); + toStringOutput.Add($"this.CurrencyPrices = {(this.CurrencyPrices == null ? "null" : $"[{string.Join(", ", this.CurrencyPrices)} ]")}"); } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/ReadPaymentProfileResponse.cs b/AdvancedBilling.Standard/Models/ReadPaymentProfileResponse.cs deleted file mode 100644 index 06d29f0..0000000 --- a/AdvancedBilling.Standard/Models/ReadPaymentProfileResponse.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Models.Containers; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// ReadPaymentProfileResponse. - /// - public class ReadPaymentProfileResponse - { - /// - /// Initializes a new instance of the class. - /// - public ReadPaymentProfileResponse() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// payment_profile. - public ReadPaymentProfileResponse( - ReadPaymentProfileResponsePaymentProfile paymentProfile) - { - this.PaymentProfile = paymentProfile; - } - - /// - /// Gets or sets PaymentProfile. - /// - [JsonProperty("payment_profile")] - public ReadPaymentProfileResponsePaymentProfile PaymentProfile { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"ReadPaymentProfileResponse : ({string.Join(", ", toStringOutput)})"; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is ReadPaymentProfileResponse other && ((this.PaymentProfile == null && other.PaymentProfile == null) || (this.PaymentProfile?.Equals(other.PaymentProfile) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"PaymentProfile = {(this.PaymentProfile == null ? "null" : this.PaymentProfile.ToString())}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Subscription.cs b/AdvancedBilling.Standard/Models/Subscription.cs index cdee3de..a8e6fc0 100644 --- a/AdvancedBilling.Standard/Models/Subscription.cs +++ b/AdvancedBilling.Standard/Models/Subscription.cs @@ -187,9 +187,9 @@ public Subscription( Models.PaymentCollectionMethod? paymentCollectionMethod = Models.PaymentCollectionMethod.Automatic, Models.Customer customer = null, Models.Product product = null, - Models.PaymentProfile creditCard = null, + Models.CreditCardPaymentProfile creditCard = null, SubscriptionGroup2 mGroup = null, - Models.SubscriptionBankAccount bankAccount = null, + Models.BankAccountPaymentProfile bankAccount = null, string paymentType = null, string referralCode = null, int? nextProductId = null, @@ -728,7 +728,7 @@ public string SnapDay /// Gets or sets CreditCard. /// [JsonProperty("credit_card", NullValueHandling = NullValueHandling.Ignore)] - public Models.PaymentProfile CreditCard { get; set; } + public Models.CreditCardPaymentProfile CreditCard { get; set; } /// /// Gets or sets MGroup. @@ -752,7 +752,7 @@ public SubscriptionGroup2 MGroup /// Gets or sets BankAccount. /// [JsonProperty("bank_account", NullValueHandling = NullValueHandling.Ignore)] - public Models.SubscriptionBankAccount BankAccount { get; set; } + public Models.BankAccountPaymentProfile BankAccount { get; set; } /// /// The payment profile type for the active profile on file. diff --git a/AdvancedBilling.Standard/Models/SubscriptionBankAccount.cs b/AdvancedBilling.Standard/Models/SubscriptionBankAccount.cs deleted file mode 100644 index 790b0b4..0000000 --- a/AdvancedBilling.Standard/Models/SubscriptionBankAccount.cs +++ /dev/null @@ -1,301 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// SubscriptionBankAccount. - /// - public class SubscriptionBankAccount - { - /// - /// Initializes a new instance of the class. - /// - public SubscriptionBankAccount() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// bank_account_holder_type. - /// bank_account_type. - /// bank_name. - /// billing_address. - /// billing_address_2. - /// billing_city. - /// billing_state. - /// billing_zip. - /// billing_country. - /// current_vault. - /// customer_id. - /// customer_vault_token. - /// first_name. - /// last_name. - /// id. - /// masked_bank_account_number. - /// masked_bank_routing_number. - /// vault_token. - /// chargify_token. - /// site_gateway_setting_id. - /// gateway_handle. - public SubscriptionBankAccount( - string bankAccountHolderType = null, - string bankAccountType = null, - string bankName = null, - string billingAddress = null, - string billingAddress2 = null, - string billingCity = null, - string billingState = null, - string billingZip = null, - string billingCountry = null, - Models.BankAccountVault? currentVault = null, - int? customerId = null, - string customerVaultToken = null, - string firstName = null, - string lastName = null, - int? id = null, - string maskedBankAccountNumber = null, - string maskedBankRoutingNumber = null, - string vaultToken = null, - string chargifyToken = null, - int? siteGatewaySettingId = null, - string gatewayHandle = null) - { - this.BankAccountHolderType = bankAccountHolderType; - this.BankAccountType = bankAccountType; - this.BankName = bankName; - this.BillingAddress = billingAddress; - this.BillingAddress2 = billingAddress2; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; - this.CurrentVault = currentVault; - this.CustomerId = customerId; - this.CustomerVaultToken = customerVaultToken; - this.FirstName = firstName; - this.LastName = lastName; - this.Id = id; - this.MaskedBankAccountNumber = maskedBankAccountNumber; - this.MaskedBankRoutingNumber = maskedBankRoutingNumber; - this.VaultToken = vaultToken; - this.ChargifyToken = chargifyToken; - this.SiteGatewaySettingId = siteGatewaySettingId; - this.GatewayHandle = gatewayHandle; - } - - /// - /// Defaults to personal - /// - [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountHolderType { get; set; } - - /// - /// Defaults to checking - /// - [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] - public string BankAccountType { get; set; } - - /// - /// The bank where the account resides - /// - [JsonProperty("bank_name", NullValueHandling = NullValueHandling.Ignore)] - public string BankName { get; set; } - - /// - /// The current billing street address for the bank account - /// - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } - - /// - /// The current billing street address, second line, for the bank account - /// - [JsonProperty("billing_address_2", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress2 { get; set; } - - /// - /// The current billing address city for the bank account - /// - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } - - /// - /// The current billing address state for the bank account - /// - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } - - /// - /// The current billing address zip code for the bank account - /// - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } - - /// - /// The current billing address country for the bank account - /// - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } - - /// - /// The vault that stores the payment profile with the provided vault_token. - /// - [JsonProperty("current_vault", NullValueHandling = NullValueHandling.Ignore)] - public Models.BankAccountVault? CurrentVault { get; set; } - - /// - /// The Chargify-assigned id for the customer record to which the bank account belongs - /// - [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] - public int? CustomerId { get; set; } - - /// - /// (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token - /// - [JsonProperty("customer_vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string CustomerVaultToken { get; set; } - - /// - /// The first name of the bank account holder - /// - [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - /// - /// The last name of the bank account holder - /// - [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - /// - /// The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) - /// - [JsonProperty("masked_bank_account_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankAccountNumber { get; set; } - - /// - /// A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account - /// - [JsonProperty("masked_bank_routing_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedBankRoutingNumber { get; set; } - - /// - /// The “token” provided by your vault storage for an already stored payment profile - /// - [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string VaultToken { get; set; } - - /// - /// Token received after sending billing informations using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) - /// - [JsonProperty("chargify_token", NullValueHandling = NullValueHandling.Ignore)] - public string ChargifyToken { get; set; } - - /// - /// Gets or sets SiteGatewaySettingId. - /// - [JsonProperty("site_gateway_setting_id", NullValueHandling = NullValueHandling.Ignore)] - public int? SiteGatewaySettingId { get; set; } - - /// - /// Gets or sets GatewayHandle. - /// - [JsonProperty("gateway_handle", NullValueHandling = NullValueHandling.Ignore)] - public string GatewayHandle { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"SubscriptionBankAccount : ({string.Join(", ", toStringOutput)})"; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is SubscriptionBankAccount other && ((this.BankAccountHolderType == null && other.BankAccountHolderType == null) || (this.BankAccountHolderType?.Equals(other.BankAccountHolderType) == true)) && - ((this.BankAccountType == null && other.BankAccountType == null) || (this.BankAccountType?.Equals(other.BankAccountType) == true)) && - ((this.BankName == null && other.BankName == null) || (this.BankName?.Equals(other.BankName) == true)) && - ((this.BillingAddress == null && other.BillingAddress == null) || (this.BillingAddress?.Equals(other.BillingAddress) == true)) && - ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && - ((this.BillingCity == null && other.BillingCity == null) || (this.BillingCity?.Equals(other.BillingCity) == true)) && - ((this.BillingState == null && other.BillingState == null) || (this.BillingState?.Equals(other.BillingState) == true)) && - ((this.BillingZip == null && other.BillingZip == null) || (this.BillingZip?.Equals(other.BillingZip) == true)) && - ((this.BillingCountry == null && other.BillingCountry == null) || (this.BillingCountry?.Equals(other.BillingCountry) == true)) && - ((this.CurrentVault == null && other.CurrentVault == null) || (this.CurrentVault?.Equals(other.CurrentVault) == true)) && - ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && - ((this.CustomerVaultToken == null && other.CustomerVaultToken == null) || (this.CustomerVaultToken?.Equals(other.CustomerVaultToken) == true)) && - ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && - ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && - ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.MaskedBankAccountNumber == null && other.MaskedBankAccountNumber == null) || (this.MaskedBankAccountNumber?.Equals(other.MaskedBankAccountNumber) == true)) && - ((this.MaskedBankRoutingNumber == null && other.MaskedBankRoutingNumber == null) || (this.MaskedBankRoutingNumber?.Equals(other.MaskedBankRoutingNumber) == true)) && - ((this.VaultToken == null && other.VaultToken == null) || (this.VaultToken?.Equals(other.VaultToken) == true)) && - ((this.ChargifyToken == null && other.ChargifyToken == null) || (this.ChargifyToken?.Equals(other.ChargifyToken) == true)) && - ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && - ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType)}"); - toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType)}"); - toStringOutput.Add($"this.BankName = {(this.BankName == null ? "null" : this.BankName)}"); - toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); - toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); - toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); - toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); - toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); - toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); - toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId.ToString())}"); - toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); - toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); - toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.MaskedBankAccountNumber = {(this.MaskedBankAccountNumber == null ? "null" : this.MaskedBankAccountNumber)}"); - toStringOutput.Add($"this.MaskedBankRoutingNumber = {(this.MaskedBankRoutingNumber == null ? "null" : this.MaskedBankRoutingNumber)}"); - toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); - toStringOutput.Add($"this.ChargifyToken = {(this.ChargifyToken == null ? "null" : this.ChargifyToken)}"); - toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); - toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/SubscriptionGroupBankAccount.cs b/AdvancedBilling.Standard/Models/SubscriptionGroupBankAccount.cs index 24357fe..c8c28e9 100644 --- a/AdvancedBilling.Standard/Models/SubscriptionGroupBankAccount.cs +++ b/AdvancedBilling.Standard/Models/SubscriptionGroupBankAccount.cs @@ -54,8 +54,8 @@ public SubscriptionGroupBankAccount( string bankIban = null, string bankBranchCode = null, Models.BankAccountType? bankAccountType = Models.BankAccountType.Checking, - Models.HolderType? bankAccountHolderType = null, - string paymentType = null, + Models.BankAccountHolderType? bankAccountHolderType = null, + Models.PaymentType? paymentType = Models.PaymentType.CreditCard, string billingAddress = null, string billingCity = null, string billingState = null, @@ -114,22 +114,22 @@ public SubscriptionGroupBankAccount( public string BankBranchCode { get; set; } /// - /// Gets or sets BankAccountType. + /// Defaults to checking /// [JsonProperty("bank_account_type", NullValueHandling = NullValueHandling.Ignore)] public Models.BankAccountType? BankAccountType { get; set; } /// - /// Gets or sets BankAccountHolderType. + /// Defaults to personal /// [JsonProperty("bank_account_holder_type", NullValueHandling = NullValueHandling.Ignore)] - public Models.HolderType? BankAccountHolderType { get; set; } + public Models.BankAccountHolderType? BankAccountHolderType { get; set; } /// /// Gets or sets PaymentType. /// [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } + public Models.PaymentType? PaymentType { get; set; } /// /// Gets or sets BillingAddress. @@ -232,7 +232,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.BankBranchCode = {(this.BankBranchCode == null ? "null" : this.BankBranchCode)}"); toStringOutput.Add($"this.BankAccountType = {(this.BankAccountType == null ? "null" : this.BankAccountType.ToString())}"); toStringOutput.Add($"this.BankAccountHolderType = {(this.BankAccountHolderType == null ? "null" : this.BankAccountHolderType.ToString())}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); + toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType.ToString())}"); toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); diff --git a/AdvancedBilling.Standard/Models/SubscriptionGroupCreditCard.cs b/AdvancedBilling.Standard/Models/SubscriptionGroupCreditCard.cs index d0eed2c..da2352a 100644 --- a/AdvancedBilling.Standard/Models/SubscriptionGroupCreditCard.cs +++ b/AdvancedBilling.Standard/Models/SubscriptionGroupCreditCard.cs @@ -69,7 +69,7 @@ public SubscriptionGroupCreditCard( string billingZip = null, string billingCountry = null, string lastFour = null, - string cardType = null, + Models.CardType? cardType = null, string customerVaultToken = null, string cvv = null, string paymentType = null) @@ -193,10 +193,10 @@ public SubscriptionGroupCreditCard( public string LastFour { get; set; } /// - /// Gets or sets CardType. + /// The type of card used. /// [JsonProperty("card_type", NullValueHandling = NullValueHandling.Ignore)] - public string CardType { get; set; } + public Models.CardType? CardType { get; set; } /// /// Gets or sets CustomerVaultToken. @@ -282,7 +282,7 @@ protected void ToString(List toStringOutput) toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); toStringOutput.Add($"this.LastFour = {(this.LastFour == null ? "null" : this.LastFour)}"); - toStringOutput.Add($"this.CardType = {(this.CardType == null ? "null" : this.CardType)}"); + toStringOutput.Add($"this.CardType = {(this.CardType == null ? "null" : this.CardType.ToString())}"); toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); toStringOutput.Add($"this.Cvv = {(this.Cvv == null ? "null" : this.Cvv)}"); toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); diff --git a/AdvancedBilling.Standard/Models/UpdateComponentPricePoint.cs b/AdvancedBilling.Standard/Models/UpdateComponentPricePoint.cs index c13f378..e665b2f 100644 --- a/AdvancedBilling.Standard/Models/UpdateComponentPricePoint.cs +++ b/AdvancedBilling.Standard/Models/UpdateComponentPricePoint.cs @@ -32,16 +32,28 @@ public UpdateComponentPricePoint() /// Initializes a new instance of the class. /// /// name. + /// handle. + /// pricing_scheme. + /// use_site_exchange_rate. + /// tax_included. /// interval. /// interval_unit. /// prices. public UpdateComponentPricePoint( string name = null, + string handle = null, + Models.PricingScheme? pricingScheme = null, + bool? useSiteExchangeRate = null, + bool? taxIncluded = null, int? interval = null, Models.IntervalUnit? intervalUnit = null, List prices = null) { this.Name = name; + this.Handle = handle; + this.PricingScheme = pricingScheme; + this.UseSiteExchangeRate = useSiteExchangeRate; + this.TaxIncluded = taxIncluded; this.Interval = interval; this.IntervalUnit = intervalUnit; this.Prices = prices; @@ -53,6 +65,30 @@ public UpdateComponentPricePoint( [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } + /// + /// Gets or sets Handle. + /// + [JsonProperty("handle", NullValueHandling = NullValueHandling.Ignore)] + public string Handle { get; set; } + + /// + /// The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + /// + [JsonProperty("pricing_scheme", NullValueHandling = NullValueHandling.Ignore)] + public Models.PricingScheme? PricingScheme { get; set; } + + /// + /// Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. + /// + [JsonProperty("use_site_exchange_rate", NullValueHandling = NullValueHandling.Ignore)] + public bool? UseSiteExchangeRate { get; set; } + + /// + /// Whether or not the price point includes tax + /// + [JsonProperty("tax_included", NullValueHandling = NullValueHandling.Ignore)] + public bool? TaxIncluded { get; set; } + /// /// The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. /// @@ -94,6 +130,10 @@ public override bool Equals(object obj) return true; } return obj is UpdateComponentPricePoint other && ((this.Name == null && other.Name == null) || (this.Name?.Equals(other.Name) == true)) && + ((this.Handle == null && other.Handle == null) || (this.Handle?.Equals(other.Handle) == true)) && + ((this.PricingScheme == null && other.PricingScheme == null) || (this.PricingScheme?.Equals(other.PricingScheme) == true)) && + ((this.UseSiteExchangeRate == null && other.UseSiteExchangeRate == null) || (this.UseSiteExchangeRate?.Equals(other.UseSiteExchangeRate) == true)) && + ((this.TaxIncluded == null && other.TaxIncluded == null) || (this.TaxIncluded?.Equals(other.TaxIncluded) == true)) && ((this.Interval == null && other.Interval == null) || (this.Interval?.Equals(other.Interval) == true)) && ((this.IntervalUnit == null && other.IntervalUnit == null) || (this.IntervalUnit?.Equals(other.IntervalUnit) == true)) && ((this.Prices == null && other.Prices == null) || (this.Prices?.Equals(other.Prices) == true)); @@ -106,6 +146,10 @@ public override bool Equals(object obj) protected void ToString(List toStringOutput) { toStringOutput.Add($"this.Name = {(this.Name == null ? "null" : this.Name)}"); + toStringOutput.Add($"this.Handle = {(this.Handle == null ? "null" : this.Handle)}"); + toStringOutput.Add($"this.PricingScheme = {(this.PricingScheme == null ? "null" : this.PricingScheme.ToString())}"); + toStringOutput.Add($"this.UseSiteExchangeRate = {(this.UseSiteExchangeRate == null ? "null" : this.UseSiteExchangeRate.ToString())}"); + toStringOutput.Add($"this.TaxIncluded = {(this.TaxIncluded == null ? "null" : this.TaxIncluded.ToString())}"); toStringOutput.Add($"this.Interval = {(this.Interval == null ? "null" : this.Interval.ToString())}"); toStringOutput.Add($"this.IntervalUnit = {(this.IntervalUnit == null ? "null" : this.IntervalUnit.ToString())}"); toStringOutput.Add($"this.Prices = {(this.Prices == null ? "null" : $"[{string.Join(", ", this.Prices)} ]")}"); diff --git a/AdvancedBilling.Standard/Models/UpdatePaymentProfileResponse.cs b/AdvancedBilling.Standard/Models/UpdatePaymentProfileResponse.cs deleted file mode 100644 index c2097f0..0000000 --- a/AdvancedBilling.Standard/Models/UpdatePaymentProfileResponse.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// UpdatePaymentProfileResponse. - /// - public class UpdatePaymentProfileResponse - { - /// - /// Initializes a new instance of the class. - /// - public UpdatePaymentProfileResponse() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// payment_profile. - public UpdatePaymentProfileResponse( - Models.UpdatedPaymentProfile paymentProfile) - { - this.PaymentProfile = paymentProfile; - } - - /// - /// Gets or sets PaymentProfile. - /// - [JsonProperty("payment_profile")] - public Models.UpdatedPaymentProfile PaymentProfile { get; set; } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"UpdatePaymentProfileResponse : ({string.Join(", ", toStringOutput)})"; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is UpdatePaymentProfileResponse other && ((this.PaymentProfile == null && other.PaymentProfile == null) || (this.PaymentProfile?.Equals(other.PaymentProfile) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.PaymentProfile = {(this.PaymentProfile == null ? "null" : this.PaymentProfile.ToString())}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/UpdatePrice.cs b/AdvancedBilling.Standard/Models/UpdatePrice.cs index 22ef783..60321e4 100644 --- a/AdvancedBilling.Standard/Models/UpdatePrice.cs +++ b/AdvancedBilling.Standard/Models/UpdatePrice.cs @@ -12,6 +12,7 @@ namespace AdvancedBilling.Standard.Models using System.Threading.Tasks; using APIMatic.Core.Utilities.Converters; using AdvancedBilling.Standard; + using AdvancedBilling.Standard.Models.Containers; using AdvancedBilling.Standard.Utilities; using Newtonsoft.Json; using Newtonsoft.Json.Converters; @@ -38,10 +39,10 @@ public UpdatePrice() /// starting_quantity. public UpdatePrice( int? id = null, - int? endingQuantity = null, - int? unitPrice = null, - string destroy = null, - int? startingQuantity = null) + UpdatePriceEndingQuantity endingQuantity = null, + UpdatePriceUnitPrice unitPrice = null, + bool? destroy = null, + UpdatePriceStartingQuantity startingQuantity = null) { this.Id = id; this.EndingQuantity = endingQuantity; @@ -60,25 +61,25 @@ public UpdatePrice( /// Gets or sets EndingQuantity. /// [JsonProperty("ending_quantity", NullValueHandling = NullValueHandling.Ignore)] - public int? EndingQuantity { get; set; } + public UpdatePriceEndingQuantity EndingQuantity { get; set; } /// - /// Gets or sets UnitPrice. + /// The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 /// [JsonProperty("unit_price", NullValueHandling = NullValueHandling.Ignore)] - public int? UnitPrice { get; set; } + public UpdatePriceUnitPrice UnitPrice { get; set; } /// /// Gets or sets Destroy. /// [JsonProperty("_destroy", NullValueHandling = NullValueHandling.Ignore)] - public string Destroy { get; set; } + public bool? Destroy { get; set; } /// /// Gets or sets StartingQuantity. /// [JsonProperty("starting_quantity", NullValueHandling = NullValueHandling.Ignore)] - public int? StartingQuantity { get; set; } + public UpdatePriceStartingQuantity StartingQuantity { get; set; } /// public override string ToString() @@ -116,10 +117,10 @@ public override bool Equals(object obj) protected void ToString(List toStringOutput) { toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.EndingQuantity = {(this.EndingQuantity == null ? "null" : this.EndingQuantity.ToString())}"); - toStringOutput.Add($"this.UnitPrice = {(this.UnitPrice == null ? "null" : this.UnitPrice.ToString())}"); - toStringOutput.Add($"this.Destroy = {(this.Destroy == null ? "null" : this.Destroy)}"); - toStringOutput.Add($"this.StartingQuantity = {(this.StartingQuantity == null ? "null" : this.StartingQuantity.ToString())}"); + toStringOutput.Add($"EndingQuantity = {(this.EndingQuantity == null ? "null" : this.EndingQuantity.ToString())}"); + toStringOutput.Add($"UnitPrice = {(this.UnitPrice == null ? "null" : this.UnitPrice.ToString())}"); + toStringOutput.Add($"this.Destroy = {(this.Destroy == null ? "null" : this.Destroy.ToString())}"); + toStringOutput.Add($"StartingQuantity = {(this.StartingQuantity == null ? "null" : this.StartingQuantity.ToString())}"); } } } \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/UpdatedPaymentProfile.cs b/AdvancedBilling.Standard/Models/UpdatedPaymentProfile.cs deleted file mode 100644 index 7ea2f90..0000000 --- a/AdvancedBilling.Standard/Models/UpdatedPaymentProfile.cs +++ /dev/null @@ -1,364 +0,0 @@ -// -// Copyright (c) APIMatic. All rights reserved. -// -namespace AdvancedBilling.Standard.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - using APIMatic.Core.Utilities.Converters; - using AdvancedBilling.Standard; - using AdvancedBilling.Standard.Utilities; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - - /// - /// UpdatedPaymentProfile. - /// - public class UpdatedPaymentProfile - { - private string gatewayHandle; - private string customerVaultToken; - private Dictionary shouldSerialize = new Dictionary - { - { "gateway_handle", false }, - { "customer_vault_token", false }, - }; - - /// - /// Initializes a new instance of the class. - /// - public UpdatedPaymentProfile() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// id. - /// first_name. - /// last_name. - /// card_type. - /// expiration_month. - /// expiration_year. - /// customer_id. - /// current_vault. - /// vault_token. - /// billing_address. - /// billing_address_2. - /// billing_city. - /// billing_state. - /// billing_zip. - /// billing_country. - /// payment_type. - /// site_gateway_setting_id. - /// gateway_handle. - /// masked_card_number. - /// customer_vault_token. - public UpdatedPaymentProfile( - int? id = null, - string firstName = null, - string lastName = null, - string cardType = null, - int? expirationMonth = null, - int? expirationYear = null, - int? customerId = null, - Models.CurrentVault? currentVault = null, - string vaultToken = null, - string billingAddress = null, - string billingAddress2 = null, - string billingCity = null, - string billingState = null, - string billingZip = null, - string billingCountry = null, - string paymentType = null, - int? siteGatewaySettingId = null, - string gatewayHandle = null, - string maskedCardNumber = null, - string customerVaultToken = null) - { - this.Id = id; - this.FirstName = firstName; - this.LastName = lastName; - this.CardType = cardType; - this.ExpirationMonth = expirationMonth; - this.ExpirationYear = expirationYear; - this.CustomerId = customerId; - this.CurrentVault = currentVault; - this.VaultToken = vaultToken; - this.BillingAddress = billingAddress; - this.BillingAddress2 = billingAddress2; - this.BillingCity = billingCity; - this.BillingState = billingState; - this.BillingZip = billingZip; - this.BillingCountry = billingCountry; - this.PaymentType = paymentType; - this.SiteGatewaySettingId = siteGatewaySettingId; - if (gatewayHandle != null) - { - this.GatewayHandle = gatewayHandle; - } - - this.MaskedCardNumber = maskedCardNumber; - if (customerVaultToken != null) - { - this.CustomerVaultToken = customerVaultToken; - } - - } - - /// - /// Gets or sets Id. - /// - [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } - - /// - /// Gets or sets FirstName. - /// - [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - /// - /// Gets or sets LastName. - /// - [JsonProperty("last_name", NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - /// - /// Gets or sets CardType. - /// - [JsonProperty("card_type", NullValueHandling = NullValueHandling.Ignore)] - public string CardType { get; set; } - - /// - /// Gets or sets ExpirationMonth. - /// - [JsonProperty("expiration_month", NullValueHandling = NullValueHandling.Ignore)] - public int? ExpirationMonth { get; set; } - - /// - /// Gets or sets ExpirationYear. - /// - [JsonProperty("expiration_year", NullValueHandling = NullValueHandling.Ignore)] - public int? ExpirationYear { get; set; } - - /// - /// Gets or sets CustomerId. - /// - [JsonProperty("customer_id", NullValueHandling = NullValueHandling.Ignore)] - public int? CustomerId { get; set; } - - /// - /// The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - /// - [JsonProperty("current_vault", NullValueHandling = NullValueHandling.Ignore)] - public Models.CurrentVault? CurrentVault { get; set; } - - /// - /// Gets or sets VaultToken. - /// - [JsonProperty("vault_token", NullValueHandling = NullValueHandling.Ignore)] - public string VaultToken { get; set; } - - /// - /// Gets or sets BillingAddress. - /// - [JsonProperty("billing_address", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress { get; set; } - - /// - /// Gets or sets BillingAddress2. - /// - [JsonProperty("billing_address_2", NullValueHandling = NullValueHandling.Ignore)] - public string BillingAddress2 { get; set; } - - /// - /// Gets or sets BillingCity. - /// - [JsonProperty("billing_city", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCity { get; set; } - - /// - /// Gets or sets BillingState. - /// - [JsonProperty("billing_state", NullValueHandling = NullValueHandling.Ignore)] - public string BillingState { get; set; } - - /// - /// Gets or sets BillingZip. - /// - [JsonProperty("billing_zip", NullValueHandling = NullValueHandling.Ignore)] - public string BillingZip { get; set; } - - /// - /// Gets or sets BillingCountry. - /// - [JsonProperty("billing_country", NullValueHandling = NullValueHandling.Ignore)] - public string BillingCountry { get; set; } - - /// - /// Gets or sets PaymentType. - /// - [JsonProperty("payment_type", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentType { get; set; } - - /// - /// Gets or sets SiteGatewaySettingId. - /// - [JsonProperty("site_gateway_setting_id", NullValueHandling = NullValueHandling.Ignore)] - public int? SiteGatewaySettingId { get; set; } - - /// - /// Gets or sets GatewayHandle. - /// - [JsonProperty("gateway_handle")] - public string GatewayHandle - { - get - { - return this.gatewayHandle; - } - - set - { - this.shouldSerialize["gateway_handle"] = true; - this.gatewayHandle = value; - } - } - - /// - /// Gets or sets MaskedCardNumber. - /// - [JsonProperty("masked_card_number", NullValueHandling = NullValueHandling.Ignore)] - public string MaskedCardNumber { get; set; } - - /// - /// Gets or sets CustomerVaultToken. - /// - [JsonProperty("customer_vault_token")] - public string CustomerVaultToken - { - get - { - return this.customerVaultToken; - } - - set - { - this.shouldSerialize["customer_vault_token"] = true; - this.customerVaultToken = value; - } - } - - /// - public override string ToString() - { - var toStringOutput = new List(); - - this.ToString(toStringOutput); - - return $"UpdatedPaymentProfile : ({string.Join(", ", toStringOutput)})"; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetGatewayHandle() - { - this.shouldSerialize["gateway_handle"] = false; - } - - /// - /// Marks the field to not be serailized. - /// - public void UnsetCustomerVaultToken() - { - this.shouldSerialize["customer_vault_token"] = false; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeGatewayHandle() - { - return this.shouldSerialize["gateway_handle"]; - } - - /// - /// Checks if the field should be serialized or not. - /// - /// A boolean weather the field should be serialized or not. - public bool ShouldSerializeCustomerVaultToken() - { - return this.shouldSerialize["customer_vault_token"]; - } - - /// - public override bool Equals(object obj) - { - if (obj == null) - { - return false; - } - - if (obj == this) - { - return true; - } - return obj is UpdatedPaymentProfile other && ((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) && - ((this.FirstName == null && other.FirstName == null) || (this.FirstName?.Equals(other.FirstName) == true)) && - ((this.LastName == null && other.LastName == null) || (this.LastName?.Equals(other.LastName) == true)) && - ((this.CardType == null && other.CardType == null) || (this.CardType?.Equals(other.CardType) == true)) && - ((this.ExpirationMonth == null && other.ExpirationMonth == null) || (this.ExpirationMonth?.Equals(other.ExpirationMonth) == true)) && - ((this.ExpirationYear == null && other.ExpirationYear == null) || (this.ExpirationYear?.Equals(other.ExpirationYear) == true)) && - ((this.CustomerId == null && other.CustomerId == null) || (this.CustomerId?.Equals(other.CustomerId) == true)) && - ((this.CurrentVault == null && other.CurrentVault == null) || (this.CurrentVault?.Equals(other.CurrentVault) == true)) && - ((this.VaultToken == null && other.VaultToken == null) || (this.VaultToken?.Equals(other.VaultToken) == true)) && - ((this.BillingAddress == null && other.BillingAddress == null) || (this.BillingAddress?.Equals(other.BillingAddress) == true)) && - ((this.BillingAddress2 == null && other.BillingAddress2 == null) || (this.BillingAddress2?.Equals(other.BillingAddress2) == true)) && - ((this.BillingCity == null && other.BillingCity == null) || (this.BillingCity?.Equals(other.BillingCity) == true)) && - ((this.BillingState == null && other.BillingState == null) || (this.BillingState?.Equals(other.BillingState) == true)) && - ((this.BillingZip == null && other.BillingZip == null) || (this.BillingZip?.Equals(other.BillingZip) == true)) && - ((this.BillingCountry == null && other.BillingCountry == null) || (this.BillingCountry?.Equals(other.BillingCountry) == true)) && - ((this.PaymentType == null && other.PaymentType == null) || (this.PaymentType?.Equals(other.PaymentType) == true)) && - ((this.SiteGatewaySettingId == null && other.SiteGatewaySettingId == null) || (this.SiteGatewaySettingId?.Equals(other.SiteGatewaySettingId) == true)) && - ((this.GatewayHandle == null && other.GatewayHandle == null) || (this.GatewayHandle?.Equals(other.GatewayHandle) == true)) && - ((this.MaskedCardNumber == null && other.MaskedCardNumber == null) || (this.MaskedCardNumber?.Equals(other.MaskedCardNumber) == true)) && - ((this.CustomerVaultToken == null && other.CustomerVaultToken == null) || (this.CustomerVaultToken?.Equals(other.CustomerVaultToken) == true)); - } - - /// - /// ToString overload. - /// - /// List of strings. - protected void ToString(List toStringOutput) - { - toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id.ToString())}"); - toStringOutput.Add($"this.FirstName = {(this.FirstName == null ? "null" : this.FirstName)}"); - toStringOutput.Add($"this.LastName = {(this.LastName == null ? "null" : this.LastName)}"); - toStringOutput.Add($"this.CardType = {(this.CardType == null ? "null" : this.CardType)}"); - toStringOutput.Add($"this.ExpirationMonth = {(this.ExpirationMonth == null ? "null" : this.ExpirationMonth.ToString())}"); - toStringOutput.Add($"this.ExpirationYear = {(this.ExpirationYear == null ? "null" : this.ExpirationYear.ToString())}"); - toStringOutput.Add($"this.CustomerId = {(this.CustomerId == null ? "null" : this.CustomerId.ToString())}"); - toStringOutput.Add($"this.CurrentVault = {(this.CurrentVault == null ? "null" : this.CurrentVault.ToString())}"); - toStringOutput.Add($"this.VaultToken = {(this.VaultToken == null ? "null" : this.VaultToken)}"); - toStringOutput.Add($"this.BillingAddress = {(this.BillingAddress == null ? "null" : this.BillingAddress)}"); - toStringOutput.Add($"this.BillingAddress2 = {(this.BillingAddress2 == null ? "null" : this.BillingAddress2)}"); - toStringOutput.Add($"this.BillingCity = {(this.BillingCity == null ? "null" : this.BillingCity)}"); - toStringOutput.Add($"this.BillingState = {(this.BillingState == null ? "null" : this.BillingState)}"); - toStringOutput.Add($"this.BillingZip = {(this.BillingZip == null ? "null" : this.BillingZip)}"); - toStringOutput.Add($"this.BillingCountry = {(this.BillingCountry == null ? "null" : this.BillingCountry)}"); - toStringOutput.Add($"this.PaymentType = {(this.PaymentType == null ? "null" : this.PaymentType)}"); - toStringOutput.Add($"this.SiteGatewaySettingId = {(this.SiteGatewaySettingId == null ? "null" : this.SiteGatewaySettingId.ToString())}"); - toStringOutput.Add($"this.GatewayHandle = {(this.GatewayHandle == null ? "null" : this.GatewayHandle)}"); - toStringOutput.Add($"this.MaskedCardNumber = {(this.MaskedCardNumber == null ? "null" : this.MaskedCardNumber)}"); - toStringOutput.Add($"this.CustomerVaultToken = {(this.CustomerVaultToken == null ? "null" : this.CustomerVaultToken)}"); - } - } -} \ No newline at end of file diff --git a/AdvancedBilling.Standard/Models/Usage.cs b/AdvancedBilling.Standard/Models/Usage.cs index 5a4e544..99dfef8 100644 --- a/AdvancedBilling.Standard/Models/Usage.cs +++ b/AdvancedBilling.Standard/Models/Usage.cs @@ -42,7 +42,7 @@ public Usage() /// component_handle. /// subscription_id. public Usage( - int? id = null, + long? id = null, string memo = null, DateTimeOffset? createdAt = null, int? pricePointId = null, @@ -67,7 +67,7 @@ public Usage( /// Gets or sets Id. /// [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] - public int? Id { get; set; } + public long? Id { get; set; } /// /// Gets or sets Memo. diff --git a/AdvancedBilling.Standard/Models/VoidInvoiceEventData1.cs b/AdvancedBilling.Standard/Models/VoidRemainderEventData.cs similarity index 85% rename from AdvancedBilling.Standard/Models/VoidInvoiceEventData1.cs rename to AdvancedBilling.Standard/Models/VoidRemainderEventData.cs index b1507dc..1e47ddd 100644 --- a/AdvancedBilling.Standard/Models/VoidInvoiceEventData1.cs +++ b/AdvancedBilling.Standard/Models/VoidRemainderEventData.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) APIMatic. All rights reserved. // namespace AdvancedBilling.Standard.Models @@ -17,25 +17,25 @@ namespace AdvancedBilling.Standard.Models using Newtonsoft.Json.Converters; /// - /// VoidInvoiceEventData1. + /// VoidRemainderEventData. /// - public class VoidInvoiceEventData1 + public class VoidRemainderEventData { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public VoidInvoiceEventData1() + public VoidRemainderEventData() { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// credit_note_attributes. /// memo. /// applied_amount. /// transaction_time. - public VoidInvoiceEventData1( + public VoidRemainderEventData( Models.CreditNote creditNoteAttributes = null, string memo = null, string appliedAmount = null, @@ -81,7 +81,7 @@ public override string ToString() this.ToString(toStringOutput); - return $"VoidInvoiceEventData1 : ({string.Join(", ", toStringOutput)})"; + return $"VoidRemainderEventData : ({string.Join(", ", toStringOutput)})"; } /// @@ -96,7 +96,7 @@ public override bool Equals(object obj) { return true; } - return obj is VoidInvoiceEventData1 other && ((this.CreditNoteAttributes == null && other.CreditNoteAttributes == null) || (this.CreditNoteAttributes?.Equals(other.CreditNoteAttributes) == true)) && + return obj is VoidRemainderEventData other && ((this.CreditNoteAttributes == null && other.CreditNoteAttributes == null) || (this.CreditNoteAttributes?.Equals(other.CreditNoteAttributes) == true)) && ((this.Memo == null && other.Memo == null) || (this.Memo?.Equals(other.Memo) == true)) && ((this.AppliedAmount == null && other.AppliedAmount == null) || (this.AppliedAmount?.Equals(other.AppliedAmount) == true)) && ((this.TransactionTime == null && other.TransactionTime == null) || (this.TransactionTime?.Equals(other.TransactionTime) == true)); diff --git a/AdvancedBilling.sln b/AdvancedBilling.sln index d256bc8..870e112 100644 --- a/AdvancedBilling.sln +++ b/AdvancedBilling.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26430.14 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedBilling.Standard", "AdvancedBilling.Standard/AdvancedBilling.Standard.csproj", "{bf192de5-cc4e-49b3-ad69-59799a5f34bc}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedBilling.Standard", "AdvancedBilling.Standard/AdvancedBilling.Standard.csproj", "{18177b2d-5e31-4ba2-ad52-8f7d4407fb3b}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {bf192de5-cc4e-49b3-ad69-59799a5f34bc}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {bf192de5-cc4e-49b3-ad69-59799a5f34bc}.Debug|Any CPU.Build.0 = Debug|Any CPU - {bf192de5-cc4e-49b3-ad69-59799a5f34bc}.Release|Any CPU.ActiveCfg = Release|Any CPU - {bf192de5-cc4e-49b3-ad69-59799a5f34bc}.Release|Any CPU.Build.0 = Release|Any CPU + {18177b2d-5e31-4ba2-ad52-8f7d4407fb3b}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18177b2d-5e31-4ba2-ad52-8f7d4407fb3b}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18177b2d-5e31-4ba2-ad52-8f7d4407fb3b}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18177b2d-5e31-4ba2-ad52-8f7d4407fb3b}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Tests/CustomFieldTests.cs b/Tests/CustomFieldTests.cs index befd3ed..466e18a 100644 --- a/Tests/CustomFieldTests.cs +++ b/Tests/CustomFieldTests.cs @@ -95,14 +95,14 @@ public async Task var customerResponse = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); var subscription = new CreateSubscription { CustomerId = customerResponse.Customer.Id, ProductId = productResponse.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false }; @@ -130,7 +130,7 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( await _client.CustomFieldsController.DeleteMetadataAsync(ResourceType.Subscriptions, subscriptionResponse.Subscription.Id.ToString(), metadataName); - await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfile, + await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfileId, productResponse, _client); } diff --git a/Tests/SubscriptionComponentsTests.cs b/Tests/SubscriptionComponentsTests.cs index fad3efe..a225f40 100644 --- a/Tests/SubscriptionComponentsTests.cs +++ b/Tests/SubscriptionComponentsTests.cs @@ -20,14 +20,14 @@ public async Task AllocateComponents_InvalidQualityOnOffComponent_StatusIs422Wit var customerResponse = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); var subscription = new CreateSubscription { CustomerId = customerResponse.Customer.Id, ProductId = productResponse.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false }; @@ -42,9 +42,7 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( var onOffComponent = new OnOffComponent($"247Support{randomString}", unitPrice: OnOffComponentUnitPrice.FromString("100")); - var onOffComponentResponse = await _client.ComponentsController.CreateComponentAsync((int)productFamilyId, - ComponentKindPath.OnOffComponents, - CreateComponentBody.FromCreateOnOffComponent(new CreateOnOffComponent(onOffComponent))); + var onOffComponentResponse = await _client.ComponentsController.CreateOnOffComponentAsync((int)productFamilyId, new CreateOnOffComponent(onOffComponent)); onOffComponentResponse.Component.Id.Should().NotBeNull(); @@ -61,7 +59,7 @@ await _client.Invoking(s => s.SubscriptionComponentsController.PreviewAllocation .Where(e => e.Errors.Any(c => c.Message.Contains("Quantity: must be either 1 (on) or 0 (off).")) && e.ResponseCode == 422); - await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfile, + await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfileId, productResponse, _client); await ErrorSuppressionWrapper.RunAsync(async () => @@ -86,14 +84,14 @@ public async Task AllocateComponents_DoubleQuantityForAllocations_UpgradeChargeP var customerResponse = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); var subscription = new CreateSubscription { CustomerId = customerResponse.Customer.Id, ProductId = productResponse.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false }; @@ -109,20 +107,17 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( PricingScheme.PerUnit, unitPrice: QuantityBasedComponentUnitPrice.FromString("10,23"), allowFractionalQuantities: true); - var quantityComponentResponse = await _client.ComponentsController.CreateComponentAsync( + var quantityComponentResponse = await _client.ComponentsController.CreateQuantityBasedComponentAsync( (int)productFamilyId, - ComponentKindPath.QuantityBasedComponents, - CreateComponentBody.FromCreateQuantityBasedComponent( - new CreateQuantityBasedComponent(quantityComponent))); + new CreateQuantityBasedComponent(quantityComponent)); quantityComponentResponse.Component.Id.Should().NotBeNull(); var onOffComponent = new OnOffComponent($"247Support{randomString}", unitPrice: OnOffComponentUnitPrice.FromString("100")); - var onOffComponentResponse = await _client.ComponentsController.CreateComponentAsync((int)productFamilyId, - ComponentKindPath.OnOffComponents, - CreateComponentBody.FromCreateOnOffComponent(new CreateOnOffComponent(onOffComponent))); + var onOffComponentResponse = await _client.ComponentsController.CreateOnOffComponentAsync((int)productFamilyId, + new CreateOnOffComponent(onOffComponent)); onOffComponentResponse.Component.Id.Should().NotBeNull(); @@ -166,7 +161,7 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( quantityAllocationValue.Should().Be(quantityPreviewValue); - await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfile, + await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfileId, productResponse, _client); await ErrorSuppressionWrapper.RunAsync(async () => diff --git a/Tests/SubscriptionTests.cs b/Tests/SubscriptionTests.cs index dc68f42..817e3b1 100644 --- a/Tests/SubscriptionTests.cs +++ b/Tests/SubscriptionTests.cs @@ -33,14 +33,14 @@ public async Task CreateSubscription_BasicScenarioData_ShouldSuccess() var customerResponse = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); var subscription = new CreateSubscription { CustomerId = customerResponse.Customer.Id, ProductId = productResponse.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false }; @@ -50,7 +50,7 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( new CreateSubscriptionRequest(subscription)); subscriptionResponse.Subscription.Id.Should().NotBeNull(); - await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfile, productResponse, _client); + await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfileId, productResponse, _client); } [Fact] @@ -66,9 +66,8 @@ public async Task var meteredComponent = new MeteredComponent($"ApiCalls{randomString}", $"api call {randomString}", PricingScheme.PerUnit, unitPrice: MeteredComponentUnitPrice.FromString("1")); - var componentResponse = await _client.ComponentsController.CreateComponentAsync((int)productFamilyId, - ComponentKindPath.MeteredComponents, - CreateComponentBody.FromCreateMeteredComponent(new CreateMeteredComponent(meteredComponent))); + var componentResponse = await _client.ComponentsController.CreateMeteredComponentAsync((int)productFamilyId, + new CreateMeteredComponent(meteredComponent)); componentResponse.Component.Id.Should().NotBeNull(); @@ -93,7 +92,7 @@ public async Task var customer = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customer.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customer.Customer.Id, _client); var initialBillingDate = DateTime.Now.AddDays(20); @@ -104,7 +103,7 @@ public async Task CustomerId = customer.Customer.Id, ProductId = product.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false, Components = new List() @@ -122,7 +121,7 @@ await _client.Invoking(c => c.SubscriptionsController.CreateSubscriptionAsync( .ThrowAsync() .Where(e => e.ResponseCode == 422 && e.Errors.Any(a => a.Contains("Coupon code could not be found"))); - await CleanupUtils.ExecuteCleanupForPaymentProfileProductCustomer(customer, paymentProfile, product, _client); + await CleanupUtils.ExecuteCleanupForPaymentProfileProductCustomer(customer, paymentProfileId, product, _client); await ErrorSuppressionWrapper.RunAsync(async () => { @@ -178,20 +177,17 @@ public async Task CreateSubscription_RestrictedCouponMeteredComponentData_Should var quantityComponent = new QuantityBasedComponent($"widget{randomString}", $"widget {randomString}", PricingScheme.PerUnit, unitPrice: QuantityBasedComponentUnitPrice.FromPrecision(1)); - var restrictedComponentResponse = await _client.ComponentsController.CreateComponentAsync( + var restrictedComponentResponse = await _client.ComponentsController.CreateQuantityBasedComponentAsync( (int)productFamilyId, - ComponentKindPath.QuantityBasedComponents, - CreateComponentBody.FromCreateQuantityBasedComponent( - new CreateQuantityBasedComponent(quantityComponent))); + new CreateQuantityBasedComponent(quantityComponent)); restrictedComponentResponse.Component.Id.Should().NotBeNull(); var meteredComponent = new MeteredComponent($"ApiCalls{randomString}", $"api call {randomString}", PricingScheme.PerUnit, unitPrice: MeteredComponentUnitPrice.FromString("1")); - var componentResponse = await _client.ComponentsController.CreateComponentAsync((int)productFamilyId, - ComponentKindPath.MeteredComponents, - CreateComponentBody.FromCreateMeteredComponent(new CreateMeteredComponent(meteredComponent))); + var componentResponse = await _client.ComponentsController.CreateMeteredComponentAsync((int)productFamilyId, + new CreateMeteredComponent(meteredComponent)); componentResponse.Component.Id.Should().NotBeNull(); @@ -217,7 +213,7 @@ public async Task CreateSubscription_RestrictedCouponMeteredComponentData_Should var customer = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customer.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customer.Customer.Id, _client); var initialBillingDate = DateTime.Now.AddDays(20); @@ -226,7 +222,7 @@ public async Task CreateSubscription_RestrictedCouponMeteredComponentData_Should CustomerId = customer.Customer.Id, ProductId = product.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false, Components = new List() @@ -245,7 +241,7 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( subscriptionResponse.Subscription.Id.Should().NotBeNull(); subscriptionResponse.Subscription.State.Should().Be(SubscriptionState.AwaitingSignup); - await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customer, paymentProfile, product, _client); + await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customer, paymentProfileId, product, _client); await ErrorSuppressionWrapper.RunAsync(async () => { @@ -280,14 +276,14 @@ public async Task GetSubscription_WithDefaultData_ShouldSuccess() var customerResponse = await CreationUtils.CreateCustomer(_client); - var paymentProfile = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); + var paymentProfileId = await CreationUtils.CreatePaymentProfile(customerResponse.Customer.Id, _client); var createdSubscription = new CreateSubscription { CustomerId = customerResponse.Customer.Id, ProductId = productResponse.Product.Id, PaymentCollectionMethod = PaymentCollectionMethod.Automatic, - PaymentProfileId = paymentProfile.PaymentProfile.Id, + PaymentProfileId = paymentProfileId, DunningCommunicationDelayEnabled = false, SkipBillingManifestTaxes = false }; @@ -304,7 +300,7 @@ await _client.SubscriptionsController.CreateSubscriptionAsync( subscription.Subscription.Customer.Id.Should().Be(customerResponse.Customer.Id); subscription.Subscription.PaymentCollectionMethod.Should().Be(PaymentCollectionMethod.Automatic); - await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfile, productResponse, _client); + await CleanupUtils.ExecuteBasicSubscriptionCleanup(subscriptionResponse, customerResponse, paymentProfileId, productResponse, _client); } } } diff --git a/Tests/Utils/CleanupUtils.cs b/Tests/Utils/CleanupUtils.cs index d4fd443..86391ce 100644 --- a/Tests/Utils/CleanupUtils.cs +++ b/Tests/Utils/CleanupUtils.cs @@ -6,7 +6,7 @@ namespace AdvancedBillingTests.Utils public static class CleanupUtils { public static async Task ExecuteBasicSubscriptionCleanup(SubscriptionResponse subscriptionResponse, - CustomerResponse customerResponse, CreatePaymentProfileResponse paymentProfile, ProductResponse productResponse, AdvancedBillingClient client) + CustomerResponse customerResponse, int paymentProfileId, ProductResponse productResponse, AdvancedBillingClient client) { await ErrorSuppressionWrapper.RunAsync(async () => { @@ -14,15 +14,15 @@ await client.SubscriptionsController.PurgeSubscriptionAsync((int)subscriptionRes (int)customerResponse.Customer.Id); }); - await ExecuteCleanupForPaymentProfileProductCustomer(customerResponse, paymentProfile, productResponse, client); + await ExecuteCleanupForPaymentProfileProductCustomer(customerResponse, paymentProfileId, productResponse, client); } public static async Task ExecuteCleanupForPaymentProfileProductCustomer(CustomerResponse customerResponse, - CreatePaymentProfileResponse paymentProfile, ProductResponse productResponse, AdvancedBillingClient client) + int paymentProfileId, ProductResponse productResponse, AdvancedBillingClient client) { await ErrorSuppressionWrapper.RunAsync(async () => { - await client.PaymentProfilesController.DeleteUnusedPaymentProfileAsync(paymentProfile.ToString()); + await client.PaymentProfilesController.DeleteUnusedPaymentProfileAsync(paymentProfileId); }); await ErrorSuppressionWrapper.RunAsync(async () => diff --git a/Tests/Utils/CreationUtils.cs b/Tests/Utils/CreationUtils.cs index 92d20dd..b1013a1 100644 --- a/Tests/Utils/CreationUtils.cs +++ b/Tests/Utils/CreationUtils.cs @@ -10,7 +10,7 @@ public static class CreationUtils { private static readonly Fixture _fixture = new(); - public static async Task CreatePaymentProfile(int? customerId, AdvancedBillingClient client) + public static async Task CreatePaymentProfile(int? customerId, AdvancedBillingClient client) { var paymentProfile = new CreatePaymentProfile { @@ -28,8 +28,11 @@ public static async Task CreatePaymentProfile(int? await client.PaymentProfilesController.CreatePaymentProfileAsync( new CreatePaymentProfileRequest(paymentProfile)); - paymentProfileResponse.PaymentProfile.Id.Should().NotBeNull(); - return paymentProfileResponse; + var paymentProfileId = paymentProfileResponse.PaymentProfile.Match(x => x.Id, y => y.Id); + + paymentProfileId.Should().NotBeNull(); + + return (int)paymentProfileId!; } public static async Task CreateCustomer(AdvancedBillingClient client) diff --git a/doc/controllers/advance-invoice.md b/doc/controllers/advance-invoice.md index 3420e43..10f3e5b 100644 --- a/doc/controllers/advance-invoice.md +++ b/doc/controllers/advance-invoice.md @@ -11,8 +11,8 @@ AdvanceInvoiceController advanceInvoiceController = client.AdvanceInvoiceControl ## Methods * [Issue Advance Invoice](../../doc/controllers/advance-invoice.md#issue-advance-invoice) -* [Read Advance Invoice](../../doc/controllers/advance-invoice.md#read-advance-invoice) * [Void Advance Invoice](../../doc/controllers/advance-invoice.md#void-advance-invoice) +* [Read Advance Invoice](../../doc/controllers/advance-invoice.md#read-advance-invoice) # Issue Advance Invoice @@ -70,13 +70,15 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Read Advance Invoice +# Void Advance Invoice -Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. +Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. +A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). ```csharp -ReadAdvanceInvoiceAsync( - int subscriptionId) +VoidAdvanceInvoiceAsync( + int subscriptionId, + Models.VoidInvoiceRequest body = null) ``` ## Parameters @@ -84,6 +86,7 @@ ReadAdvanceInvoiceAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | ## Response Type @@ -95,7 +98,7 @@ ReadAdvanceInvoiceAsync( int subscriptionId = 222; try { - Invoice result = await advanceInvoiceController.ReadAdvanceInvoiceAsync(subscriptionId); + Invoice result = await advanceInvoiceController.VoidAdvanceInvoiceAsync(subscriptionId); } catch (ApiException e) { @@ -111,15 +114,13 @@ catch (ApiException e) | 404 | Not Found | `ApiException` | -# Void Advance Invoice +# Read Advance Invoice -Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. -A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). +Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. ```csharp -VoidAdvanceInvoiceAsync( - int subscriptionId, - Models.VoidInvoiceRequest body = null) +ReadAdvanceInvoiceAsync( + int subscriptionId) ``` ## Parameters @@ -127,7 +128,6 @@ VoidAdvanceInvoiceAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | ## Response Type @@ -139,7 +139,7 @@ VoidAdvanceInvoiceAsync( int subscriptionId = 222; try { - Invoice result = await advanceInvoiceController.VoidAdvanceInvoiceAsync(subscriptionId); + Invoice result = await advanceInvoiceController.ReadAdvanceInvoiceAsync(subscriptionId); } catch (ApiException e) { diff --git a/doc/controllers/api-exports.md b/doc/controllers/api-exports.md index 9c708dc..d94b314 100644 --- a/doc/controllers/api-exports.md +++ b/doc/controllers/api-exports.md @@ -11,14 +11,14 @@ APIExportsController aPIExportsController = client.APIExportsController; ## Methods * [List Exported Proforma Invoices](../../doc/controllers/api-exports.md#list-exported-proforma-invoices) -* [List Exported Invoices](../../doc/controllers/api-exports.md#list-exported-invoices) * [List Exported Subscriptions](../../doc/controllers/api-exports.md#list-exported-subscriptions) +* [List Exported Invoices](../../doc/controllers/api-exports.md#list-exported-invoices) * [Export Proforma Invoices](../../doc/controllers/api-exports.md#export-proforma-invoices) +* [Read Subscriptions Export](../../doc/controllers/api-exports.md#read-subscriptions-export) +* [Read Proforma Invoices Export](../../doc/controllers/api-exports.md#read-proforma-invoices-export) * [Export Invoices](../../doc/controllers/api-exports.md#export-invoices) * [Export Subscriptions](../../doc/controllers/api-exports.md#export-subscriptions) -* [Read Proforma Invoices Export](../../doc/controllers/api-exports.md#read-proforma-invoices-export) * [Read Invoices Export](../../doc/controllers/api-exports.md#read-invoices-export) -* [Read Subscriptions Export](../../doc/controllers/api-exports.md#read-subscriptions-export) # List Exported Proforma Invoices @@ -72,15 +72,15 @@ catch (ApiException e) | 404 | Not Found | `ApiException` | -# List Exported Invoices +# List Exported Subscriptions -This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. +This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. -Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. +Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. ```csharp -ListExportedInvoicesAsync( - Models.ListExportedInvoicesInput input) +ListExportedSubscriptionsAsync( + Models.ListExportedSubscriptionsInput input) ``` ## Parameters @@ -93,12 +93,12 @@ ListExportedInvoicesAsync( ## Response Type -[`Task>`](../../doc/models/invoice.md) +[`Task>`](../../doc/models/subscription.md) ## Example Usage ```csharp -ListExportedInvoicesInput listExportedInvoicesInput = new ListExportedInvoicesInput +ListExportedSubscriptionsInput listExportedSubscriptionsInput = new ListExportedSubscriptionsInput { BatchId = "batch_id8", PerPage = 100, @@ -107,7 +107,7 @@ ListExportedInvoicesInput listExportedInvoicesInput = new ListExportedInvoicesIn try { - List result = await aPIExportsController.ListExportedInvoicesAsync(listExportedInvoicesInput); + List result = await aPIExportsController.ListExportedSubscriptionsAsync(listExportedSubscriptionsInput); } catch (ApiException e) { @@ -123,15 +123,15 @@ catch (ApiException e) | 404 | Not Found | `ApiException` | -# List Exported Subscriptions +# List Exported Invoices -This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. +This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. -Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. +Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. ```csharp -ListExportedSubscriptionsAsync( - Models.ListExportedSubscriptionsInput input) +ListExportedInvoicesAsync( + Models.ListExportedInvoicesInput input) ``` ## Parameters @@ -144,12 +144,12 @@ ListExportedSubscriptionsAsync( ## Response Type -[`Task>`](../../doc/models/subscription.md) +[`Task>`](../../doc/models/invoice.md) ## Example Usage ```csharp -ListExportedSubscriptionsInput listExportedSubscriptionsInput = new ListExportedSubscriptionsInput +ListExportedInvoicesInput listExportedInvoicesInput = new ListExportedInvoicesInput { BatchId = "batch_id8", PerPage = 100, @@ -158,7 +158,7 @@ ListExportedSubscriptionsInput listExportedSubscriptionsInput = new ListExported try { - List result = await aPIExportsController.ListExportedSubscriptionsAsync(listExportedSubscriptionsInput); + List result = await aPIExportsController.ListExportedInvoicesAsync(listExportedInvoicesInput); } catch (ApiException e) { @@ -210,14 +210,21 @@ catch (ApiException e) | 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | -# Export Invoices +# Read Subscriptions Export -This API creates an invoices export and returns a batchjob object. +This API returns a batchjob object for subscriptions export. ```csharp -ExportInvoicesAsync() +ReadSubscriptionsExportAsync( + string batchId) ``` +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | + ## Response Type [`Task`](../../doc/models/batch-job-response.md) @@ -225,9 +232,10 @@ ExportInvoicesAsync() ## Example Usage ```csharp +string batchId = "batch_id8"; try { - BatchJobResponse result = await aPIExportsController.ExportInvoicesAsync(); + BatchJobResponse result = await aPIExportsController.ReadSubscriptionsExportAsync(batchId); } catch (ApiException e) { @@ -241,17 +249,23 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 404 | Not Found | `ApiException` | -| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | -# Export Subscriptions +# Read Proforma Invoices Export -This API creates a subscriptions export and returns a batchjob object. +This API returns a batchjob object for proforma invoices export. ```csharp -ExportSubscriptionsAsync() +ReadProformaInvoicesExportAsync( + string batchId) ``` +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | + ## Response Type [`Task`](../../doc/models/batch-job-response.md) @@ -259,9 +273,10 @@ ExportSubscriptionsAsync() ## Example Usage ```csharp +string batchId = "batch_id8"; try { - BatchJobResponse result = await aPIExportsController.ExportSubscriptionsAsync(); + BatchJobResponse result = await aPIExportsController.ReadProformaInvoicesExportAsync(batchId); } catch (ApiException e) { @@ -274,24 +289,17 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | +| 404 | Not Found | `ApiException` | -# Read Proforma Invoices Export +# Export Invoices -This API returns a batchjob object for proforma invoices export. +This API creates an invoices export and returns a batchjob object. ```csharp -ReadProformaInvoicesExportAsync( - string batchId) +ExportInvoicesAsync() ``` -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | - ## Response Type [`Task`](../../doc/models/batch-job-response.md) @@ -299,10 +307,9 @@ ReadProformaInvoicesExportAsync( ## Example Usage ```csharp -string batchId = "batch_id8"; try { - BatchJobResponse result = await aPIExportsController.ReadProformaInvoicesExportAsync(batchId); + BatchJobResponse result = await aPIExportsController.ExportInvoicesAsync(); } catch (ApiException e) { @@ -316,23 +323,17 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 404 | Not Found | `ApiException` | +| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | -# Read Invoices Export +# Export Subscriptions -This API returns a batchjob object for invoices export. +This API creates a subscriptions export and returns a batchjob object. ```csharp -ReadInvoicesExportAsync( - string batchId) +ExportSubscriptionsAsync() ``` -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | - ## Response Type [`Task`](../../doc/models/batch-job-response.md) @@ -340,10 +341,9 @@ ReadInvoicesExportAsync( ## Example Usage ```csharp -string batchId = "batch_id8"; try { - BatchJobResponse result = await aPIExportsController.ReadInvoicesExportAsync(batchId); + BatchJobResponse result = await aPIExportsController.ExportSubscriptionsAsync(); } catch (ApiException e) { @@ -356,15 +356,15 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | +| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | -# Read Subscriptions Export +# Read Invoices Export -This API returns a batchjob object for subscriptions export. +This API returns a batchjob object for invoices export. ```csharp -ReadSubscriptionsExportAsync( +ReadInvoicesExportAsync( string batchId) ``` @@ -384,7 +384,7 @@ ReadSubscriptionsExportAsync( string batchId = "batch_id8"; try { - BatchJobResponse result = await aPIExportsController.ReadSubscriptionsExportAsync(batchId); + BatchJobResponse result = await aPIExportsController.ReadInvoicesExportAsync(batchId); } catch (ApiException e) { diff --git a/doc/controllers/billing-portal.md b/doc/controllers/billing-portal.md index a57b3a3..1fb995b 100644 --- a/doc/controllers/billing-portal.md +++ b/doc/controllers/billing-portal.md @@ -10,10 +10,61 @@ BillingPortalController billingPortalController = client.BillingPortalController ## Methods +* [Revoke Billing Portal Access](../../doc/controllers/billing-portal.md#revoke-billing-portal-access) * [Enable Billing Portal for Customer](../../doc/controllers/billing-portal.md#enable-billing-portal-for-customer) * [Read Billing Portal Link](../../doc/controllers/billing-portal.md#read-billing-portal-link) * [Resend Billing Portal Invitation](../../doc/controllers/billing-portal.md#resend-billing-portal-invitation) -* [Revoke Billing Portal Access](../../doc/controllers/billing-portal.md#revoke-billing-portal-access) + + +# Revoke Billing Portal Access + +You can revoke a customer's Billing Portal invitation. + +If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. + +## Limitations + +This endpoint will only return a JSON response. + +```csharp +RevokeBillingPortalAccessAsync( + int customerId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `customerId` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +[`Task`](../../doc/models/revoked-invitation.md) + +## Example Usage + +```csharp +int customerId = 150; +try +{ + RevokedInvitation result = await billingPortalController.RevokeBillingPortalAccessAsync(customerId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "last_sent_at": "Not Invited", + "last_accepted_at": "Invite Revoked", + "uninvited_count": 8 +} +``` # Enable Billing Portal for Customer @@ -200,54 +251,3 @@ catch (ApiException e) | 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - -# Revoke Billing Portal Access - -You can revoke a customer's Billing Portal invitation. - -If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. - -## Limitations - -This endpoint will only return a JSON response. - -```csharp -RevokeBillingPortalAccessAsync( - int customerId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `customerId` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -[`Task`](../../doc/models/revoked-invitation.md) - -## Example Usage - -```csharp -int customerId = 150; -try -{ - RevokedInvitation result = await billingPortalController.RevokeBillingPortalAccessAsync(customerId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "last_sent_at": "Not Invited", - "last_accepted_at": "Invite Revoked", - "uninvited_count": 8 -} -``` - diff --git a/doc/controllers/components.md b/doc/controllers/components.md index 4a99868..790b118 100644 --- a/doc/controllers/components.md +++ b/doc/controllers/components.md @@ -10,50 +10,42 @@ ComponentsController componentsController = client.ComponentsController; ## Methods -* [Create Component](../../doc/controllers/components.md#create-component) +* [Create on Off Component](../../doc/controllers/components.md#create-on-off-component) +* [Create Prepaid Usage Component](../../doc/controllers/components.md#create-prepaid-usage-component) +* [Create Event Based Component](../../doc/controllers/components.md#create-event-based-component) +* [Create Quantity Based Component](../../doc/controllers/components.md#create-quantity-based-component) +* [Create Metered Component](../../doc/controllers/components.md#create-metered-component) +* [List Components](../../doc/controllers/components.md#list-components) +* [List Component Price Points](../../doc/controllers/components.md#list-component-price-points) +* [List All Component Price Points](../../doc/controllers/components.md#list-all-component-price-points) * [Read Component by Handle](../../doc/controllers/components.md#read-component-by-handle) -* [Read Component by Id](../../doc/controllers/components.md#read-component-by-id) -* [Update Product Family Component](../../doc/controllers/components.md#update-product-family-component) * [Archive Component](../../doc/controllers/components.md#archive-component) -* [List Components](../../doc/controllers/components.md#list-components) * [Update Component](../../doc/controllers/components.md#update-component) +* [Update Component Price Point](../../doc/controllers/components.md#update-component-price-point) +* [Archive Component Price Point](../../doc/controllers/components.md#archive-component-price-point) +* [Unarchive Component Price Point](../../doc/controllers/components.md#unarchive-component-price-point) +* [Read Component by Id](../../doc/controllers/components.md#read-component-by-id) +* [Update Product Family Component](../../doc/controllers/components.md#update-product-family-component) * [Update Default Price Point for Component](../../doc/controllers/components.md#update-default-price-point-for-component) * [List Components for Product Family](../../doc/controllers/components.md#list-components-for-product-family) * [Create Component Price Point](../../doc/controllers/components.md#create-component-price-point) -* [List Component Price Points](../../doc/controllers/components.md#list-component-price-points) * [Create Component Price Points](../../doc/controllers/components.md#create-component-price-points) -* [Update Component Price Point](../../doc/controllers/components.md#update-component-price-point) -* [Archive Component Price Point](../../doc/controllers/components.md#archive-component-price-point) -* [Unarchive Component Price Point](../../doc/controllers/components.md#unarchive-component-price-point) * [Create Currency Prices](../../doc/controllers/components.md#create-currency-prices) * [Update Currency Prices](../../doc/controllers/components.md#update-currency-prices) -* [List All Component Price Points](../../doc/controllers/components.md#list-all-component-price-points) -# Create Component +# Create on Off Component -This request will create a component definition under the specified product family. These component definitions determine what components are named, how they are measured, and how much they cost. +This request will create a component definition of kind **on_off_component** under the specified product family. On/Off component can then be added and “allocated” for a subscription. -Components can then be added and “allocated” for each subscription to a product in the product family. These component line-items affect how much a subscription will be charged, depending on the current allocations (i.e. 4 IP Addresses, or SSL “enabled”) - -This documentation covers both component definitions and component line-items. Please understand the difference. - -Please note that you may not edit components via API. To do so, please log into the application. - -### Component Documentation +On/off components are used for any flat fee, recurring add on (think $99/month for tech support or a flat add on shipping fee). For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). -For information on how to record component usage against a subscription, please see the following resources: - -+ [Proration and Component Allocations](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#applying-proration-and-recording-components) -+ [Recording component usage against a subscription](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404606587917#recording-component-usage) - ```csharp -CreateComponentAsync( +CreateOnOffComponentAsync( int productFamilyId, - Models.ComponentKindPath componentKind, - CreateComponentBody body = null) + Models.CreateOnOffComponent body = null) ``` ## Parameters @@ -61,8 +53,7 @@ CreateComponentAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentKind` | [`ComponentKindPath`](../../doc/models/component-kind-path.md) | Template, Required | The component kind | -| `body` | [`CreateComponentBody`](../../doc/models/containers/create-component-body.md) | Body, Optional | This is a container for one-of cases. | +| `body` | [`CreateOnOffComponent`](../../doc/models/create-on-off-component.md) | Body, Optional | - | ## Response Type @@ -72,33 +63,33 @@ CreateComponentAsync( ```csharp int productFamilyId = 140; -ComponentKindPath componentKind = ComponentKindPath.OnOffComponents; -CreateComponentBody body = CreateComponentBody.FromCreateMeteredComponent( - new CreateMeteredComponent +CreateOnOffComponent body = new CreateOnOffComponent +{ + OnOffComponent = new OnOffComponent { - MeteredComponent = new MeteredComponent + Name = "Annual Support Services", + Description = "Prepay for support services", + Taxable = true, + Prices = new List { - Name = "Text messages", - UnitName = "text message", - PricingScheme = PricingScheme.Stairstep, - Taxable = false, - Prices = new List + new Price { - new Price - { - StartingQuantity = PriceStartingQuantity.FromNumber(1), - UnitPrice = PriceUnitPrice.FromPrecision(1), - }, + StartingQuantity = PriceStartingQuantity.FromString("0"), + UnitPrice = PriceUnitPrice.FromString("100.00"), }, }, - } -); + DisplayOnHostedPage = true, + PublicSignupPageIds = new List + { + 320495, + }, + }, +}; try { - ComponentResponse result = await componentsController.CreateComponentAsync( + ComponentResponse result = await componentsController.CreateOnOffComponentAsync( productFamilyId, - componentKind, body ); } @@ -115,29 +106,34 @@ catch (ApiException e) { "component": { "id": 292609, - "name": "Text messages", - "pricing_scheme": "stairstep", - "unit_name": "text message", - "unit_price": null, + "name": "Test On-Off Component 46124", + "handle": "test-on-off-component-4612422802", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "10.0", "product_family_id": 528484, + "product_family_name": "Cloud Compute Servers", "price_per_unit_in_cents": null, - "kind": "metered_component", + "kind": "on_off_component", "archived": false, "taxable": false, "description": null, - "created_at": "2019-08-02T05:54:53-04:00", - "prices": [ - { - "id": 47, - "component_id": 292609, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 173, - "formatted_unit_price": "$1.00" - } - ], - "default_price_point_name": "Original" + "default_price_point_id": 2944263, + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null } } ``` @@ -146,23 +142,30 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Read Component by Handle +# Create Prepaid Usage Component -This request will return information regarding a component having the handle you provide. You can identify your components with a handle so you don't have to save or reference the IDs we generate. +This request will create a component definition of kind **prepaid_usage_component** under the specified product family. Prepaid component can then be added and “allocated” for a subscription. + +Prepaid components allow customers to pre-purchase units that can be used up over time on their subscription. In a sense, they are the mirror image of metered components; while metered components charge at the end of the period for the amount of units used, prepaid components are charged for at the time of purchase, and we subsequently keep track of the usage against the amount purchased. + +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). ```csharp -ReadComponentByHandleAsync( - string handle) +CreatePrepaidUsageComponentAsync( + int productFamilyId, + Models.CreatePrepaidComponent body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `handle` | `string` | Query, Required | The handle of the component to find | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `body` | [`CreatePrepaidComponent`](../../doc/models/create-prepaid-component.md) | Body, Optional | - | ## Response Type @@ -171,10 +174,46 @@ ReadComponentByHandleAsync( ## Example Usage ```csharp -string handle = "handle6"; +int productFamilyId = 140; +CreatePrepaidComponent body = new CreatePrepaidComponent +{ + PrepaidUsageComponent = new PrepaidUsageComponent + { + Name = "Minutes", + UnitName = "minutes", + PricingScheme = PricingScheme.PerUnit, + UnitPrice = PrepaidUsageComponentUnitPrice.FromPrecision(2), + OveragePricing = new OveragePricing + { + PricingScheme = PricingScheme.Stairstep, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(1), + UnitPrice = PriceUnitPrice.FromPrecision(3), + EndingQuantity = PriceEndingQuantity.FromNumber(100), + }, + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(101), + UnitPrice = PriceUnitPrice.FromPrecision(5), + }, + }, + }, + RolloverPrepaidRemainder = true, + RenewPrepaidAllocation = true, + ExpirationInterval = 15, + ExpirationIntervalUnit = IntervalUnit.Day, + }, +}; + try { - ComponentResponse result = await componentsController.ReadComponentByHandleAsync(handle); + ComponentResponse result = await componentsController.CreatePrepaidUsageComponentAsync( + productFamilyId, + body + ); } catch (ApiException e) { @@ -188,42 +227,85 @@ catch (ApiException e) ```json { "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, + "id": 292609, + "name": "Test Prepaid Component 98505", + "handle": "test-prepaid-component-9850584842", + "pricing_scheme": "per_unit", + "unit_name": "unit", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Test Product Family 27791", "price_per_unit_in_cents": null, - "kind": "on_off_component", + "kind": "prepaid_usage_component", "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", + "taxable": false, + "description": "Description for: Test Prepaid Component 98505", + "default_price_point_id": 2944263, + "overage_prices": [ + { + "id": 55964, + "component_id": 30427, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 2944756, + "formatted_unit_price": "$1.00", + "segment_id": null + } + ], + "prices": [ + { + "id": 55963, + "component_id": 30427, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 2944756, + "formatted_unit_price": "$1.00", + "segment_id": null + } + ], + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, "recurring": true, "upgrade_charge": null, "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null } } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + -# Read Component by Id +# Create Event Based Component -This request will return information regarding a component from a specific product family. +This request will create a component definition of kind **event_based_component** under the specified product family. Event-based component can then be added and “allocated” for a subscription. -You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. +Event-based components are similar to other component types, in that you define the component parameters (such as name and taxability) and the pricing. A key difference for the event-based component is that it must be attached to a metric. This is because the metric provides the component with the actual quantity used in computing what and how much will be billed each period for each subscription. + +So, instead of reporting usage directly for each component (as you would with metered components), the usage is derived from analysis of your events. + +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). ```csharp -ReadComponentByIdAsync( +CreateEventBasedComponentAsync( int productFamilyId, - string componentId) + Models.CreateEBBComponent body = null) ``` ## Parameters @@ -231,7 +313,7 @@ ReadComponentByIdAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | +| `body` | [`CreateEBBComponent`](../../doc/models/create-ebb-component.md) | Body, Optional | - | ## Response Type @@ -241,12 +323,33 @@ ReadComponentByIdAsync( ```csharp int productFamilyId = 140; -string componentId = "component_id8"; +CreateEBBComponent body = new CreateEBBComponent +{ + EventBasedComponent = new EBBComponent + { + Name = "Component Name", + UnitName = "string", + PricingScheme = PricingScheme.PerUnit, + EventBasedBillingMetricId = 123, + Description = "string", + Handle = "some_handle", + Taxable = true, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(1), + UnitPrice = PriceUnitPrice.FromString("0.49"), + }, + }, + }, +}; + try { - ComponentResponse result = await componentsController.ReadComponentByIdAsync( + ComponentResponse result = await componentsController.CreateEventBasedComponentAsync( productFamilyId, - componentId + body ); } catch (ApiException e) @@ -261,43 +364,71 @@ catch (ApiException e) ```json { "component": { - "id": 399853, - "name": "Annual Support Services", + "id": 1489581, + "name": "stripeCharges", + "handle": null, "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, + "unit_name": "charge", + "unit_price": null, + "product_family_id": 1517093, + "product_family_name": "Billing Plans", "price_per_unit_in_cents": null, - "kind": "on_off_component", + "kind": "event_based_component", "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, + "taxable": false, + "description": null, + "default_price_point_id": null, + "prices": [], + "price_point_count": 0, + "price_points_url": "https://staging.chargify.com/components/1489581/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": false, "upgrade_charge": null, "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" + "created_at": "2021-10-12T07:33:24-05:00", + "updated_at": "2021-10-12T07:33:24-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": null, + "item_category": null, + "accounting_code": null, + "event_based_billing_metric_id": 1163 } } ``` +## Errors -# Update Product Family Component +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -This request will update a component from a specific product family. -You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. +# Create Quantity Based Component + +This request will create a component definition of kind **quantity_based_component** under the specified product family. Quantity Based component can then be added and “allocated” for a subscription. + +When defining Quantity Based component, You can choose one of 2 types: + +#### Recurring + +Recurring quantity-based components are used to bill for the number of some unit (think monthly software user licenses or the number of pairs of socks in a box-a-month club). This is most commonly associated with billing for user licenses, number of users, number of employees, etc. + +#### One-time + +One-time quantity-based components are used to create ad hoc usage charges that do not recur. For example, at the time of signup, you might want to charge your customer a one-time fee for onboarding or other services. + +The allocated quantity for one-time quantity-based components immediately gets reset back to zero after the allocation is made. + +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). ```csharp -UpdateProductFamilyComponentAsync( +CreateQuantityBasedComponentAsync( int productFamilyId, - string componentId, - Models.UpdateComponentRequest body = null) + Models.CreateQuantityBasedComponent body = null) ``` ## Parameters @@ -305,8 +436,7 @@ UpdateProductFamilyComponentAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | -| `body` | [`UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | +| `body` | [`CreateQuantityBasedComponent`](../../doc/models/create-quantity-based-component.md) | Body, Optional | - | ## Response Type @@ -316,20 +446,29 @@ UpdateProductFamilyComponentAsync( ```csharp int productFamilyId = 140; -string componentId = "component_id8"; -UpdateComponentRequest body = new UpdateComponentRequest +CreateQuantityBasedComponent body = new CreateQuantityBasedComponent { - Component = new UpdateComponent + QuantityBasedComponent = new QuantityBasedComponent { - ItemCategory = ItemCategory.EnumBusinessSoftware, + Name = "Quantity Based Component", + UnitName = "Component", + PricingScheme = PricingScheme.PerUnit, + Description = "Example of JSON per-unit component example", + Taxable = true, + UnitPrice = QuantityBasedComponentUnitPrice.FromString("10"), + DisplayOnHostedPage = true, + AllowFractionalQuantities = true, + PublicSignupPageIds = new List + { + 323397, + }, }, }; try { - ComponentResponse result = await componentsController.UpdateProductFamilyComponentAsync( + ComponentResponse result = await componentsController.CreateQuantityBasedComponentAsync( productFamilyId, - componentId, body ); } @@ -345,27 +484,47 @@ catch (ApiException e) ```json { "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, + "id": 292609, + "name": "Text messages", + "handle": "text-messages", + "pricing_scheme": "per_unit", + "unit_name": "unit", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Cloud Compute Servers", "price_per_unit_in_cents": null, - "kind": "on_off_component", + "kind": "quantity_based_component", "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, + "taxable": false, + "description": null, + "default_price_point_id": 2944263, + "prices": [ + { + "id": 55423, + "component_id": 30002, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "10.0", + "price_point_id": 2944263, + "formatted_unit_price": "$10.00", + "segment_id": null + } + ], + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": false, "upgrade_charge": null, "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null } } ``` @@ -374,17 +533,24 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Archive Component +# Create Metered Component -Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. +This request will create a component definition of kind **metered_component** under the specified product family. Metered component can then be added and “allocated” for a subscription. + +Metered components are used to bill for any type of unit that resets to 0 at the end of the billing period (think daily Google Adwords clicks or monthly cell phone minutes). This is most commonly associated with usage-based billing and many other pricing schemes. + +Note that this is different from recurring quantity-based components, which DO NOT reset to zero at the start of every billing period. If you want to bill for a quantity of something that does not change unless you change it, then you want quantity components, instead. + +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). ```csharp -ArchiveComponentAsync( +CreateMeteredComponentAsync( int productFamilyId, - string componentId) + Models.CreateMeteredComponent body = null) ``` ## Parameters @@ -392,22 +558,40 @@ ArchiveComponentAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | +| `body` | [`CreateMeteredComponent`](../../doc/models/create-metered-component.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/component.md) +[`Task`](../../doc/models/component-response.md) ## Example Usage ```csharp int productFamilyId = 140; -string componentId = "component_id8"; +CreateMeteredComponent body = new CreateMeteredComponent +{ + MeteredComponent = new MeteredComponent + { + Name = "Text messages", + UnitName = "text message", + PricingScheme = PricingScheme.PerUnit, + Taxable = false, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(1), + UnitPrice = PriceUnitPrice.FromPrecision(1), + }, + }, + }, +}; + try { - Component result = await componentsController.ArchiveComponentAsync( + ComponentResponse result = await componentsController.CreateMeteredComponentAsync( productFamilyId, - componentId + body ); } catch (ApiException e) @@ -421,25 +605,49 @@ catch (ApiException e) ```json { - "id": 25407138, - "name": "cillum aute", - "pricing_scheme": "stairstep", - "unit_name": "nulla in", - "unit_price": "Excepteur veniam", - "product_family_id": -56705047, - "kind": "prepaid_usage_component", - "archived": true, - "taxable": false, - "description": "reprehenderit laborum qui fugiat", - "default_price_point_id": -64328176, - "price_point_count": 15252407, - "price_points_url": "dolor mollit consequat", - "tax_code": "ea nisi", - "recurring": false, - "created_at": "dolor qui deserunt tempor", - "default_price_point_name": "cupidatat Lorem non aliqua", - "product_family_name": "do elit", - "hide_date_range_on_invoice": false + "component": { + "id": 292609, + "name": "Text messages", + "handle": "text-messages", + "pricing_scheme": "per_unit", + "unit_name": "unit", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Cloud Compute Servers", + "price_per_unit_in_cents": null, + "kind": "metered_component", + "archived": false, + "taxable": false, + "description": null, + "default_price_point_id": 2944263, + "prices": [ + { + "id": 55423, + "component_id": 30002, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "10.0", + "price_point_id": 2944263, + "formatted_unit_price": "$10.00", + "segment_id": null + } + ], + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": false, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null + } } ``` @@ -447,6 +655,7 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | @@ -596,47 +805,149 @@ catch (ApiException e) ``` -# Update Component +# List Component Price Points -This request will update a component. +Use this endpoint to read current price points that are associated with a component. -You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. +You may specify the component by using either the numeric id or the `handle:gold` syntax. + +When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. + +If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. ```csharp -UpdateComponentAsync( - string componentId, - Models.UpdateComponentRequest body = null) +ListComponentPricePointsAsync( + Models.ListComponentPricePointsInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | The id or handle of the component | -| `body` | [`UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `currencyPrices` | `bool?` | Query, Optional | Include an array of currency price data | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | ## Response Type -[`Task`](../../doc/models/component-response.md) +[`Task`](../../doc/models/component-price-points-response.md) ## Example Usage ```csharp -string componentId = "component_id8"; -UpdateComponentRequest body = new UpdateComponentRequest +ListComponentPricePointsInput listComponentPricePointsInput = new ListComponentPricePointsInput { - Component = new UpdateComponent + ComponentId = 222, + Page = 2, + PerPage = 50, +Liquid error: Value cannot be null. (Parameter 'key')}; + +try +{ + ComponentPricePointsResponse result = await componentsController.ListComponentPricePointsAsync(listComponentPricePointsInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ { - ItemCategory = ItemCategory.EnumBusinessSoftware, + "id": 80, + "default": false, + "name": "Wholesale Two", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "wholesale-two", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 121, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "5.0" + } + ] }, -}; + { + "id": 81, + "default": false, + "name": "MSRP", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "msrp", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 122, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } + ] +} +``` + + +# List All Component Price Points + +This method allows to retrieve a list of Components Price Points belonging to a Site. + +```csharp +ListAllComponentPricePointsAsync( + Models.ListAllComponentPricePointsInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `filterDateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | +| `filterEndDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `filterEndDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `include` | [`ListComponentsPricePointsInclude?`](../../doc/models/list-components-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterStartDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `filterStartDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=custom,catalog`. | +| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `filterIds` | `List` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | +| `filterArchivedAt` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | + +## Response Type + +[`Task`](../../doc/models/list-components-price-points-response.md) + +## Example Usage + +```csharp +ListAllComponentPricePointsInput listAllComponentPricePointsInput = new ListAllComponentPricePointsInput +{ +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') Include = ListComponentsPricePointsInclude.CurrencyPrices, + Page = 2, + PerPage = 50, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; try { - ComponentResponse result = await componentsController.UpdateComponentAsync( - componentId, - body - ); + ListComponentsPricePointsResponse result = await componentsController.ListAllComponentPricePointsAsync(listAllComponentPricePointsInput); } catch (ApiException e) { @@ -649,29 +960,32 @@ catch (ApiException e) ```json { - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" - } + "price_points": [ + { + "id": 1, + "name": "Auto-created", + "type": "default", + "pricing_scheme": "per_unit", + "component_id": 2, + "handle": "auto-created", + "archived_at": null, + "created_at": "2021-02-21T11:05:57-05:00", + "updated_at": "2021-02-21T11:05:57-05:00", + "prices": [ + { + "id": 3, + "component_id": 2, + "starting_quantity": 0, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 1, + "formatted_unit_price": "$1.00", + "segment_id": null + } + ], + "tax_included": false + } + ] } ``` @@ -682,26 +996,20 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Update Default Price Point for Component - -Sets a new default price point for the component. This new default will apply to all new subscriptions going forward - existing subscriptions will remain on their current price point. - -See [Price Points Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-points) for more information on price points and moving subscriptions between price points. +# Read Component by Handle -Note: Custom price points are not able to be set as the default for a component. +This request will return information regarding a component having the handle you provide. You can identify your components with a handle so you don't have to save or reference the IDs we generate. ```csharp -UpdateDefaultPricePointForComponentAsync( - int componentId, - int pricePointId) +ReadComponentByHandleAsync( + string handle) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | +| `handle` | `string` | Query, Required | The handle of the component to find | ## Response Type @@ -710,14 +1018,10 @@ UpdateDefaultPricePointForComponentAsync( ## Example Usage ```csharp -int componentId = 222; -int pricePointId = 10; +string handle = "handle6"; try { - ComponentResponse result = await componentsController.UpdateDefaultPricePointForComponentAsync( - componentId, - pricePointId - ); + ComponentResponse result = await componentsController.ReadComponentByHandleAsync(handle); } catch (ApiException e) { @@ -731,78 +1035,64 @@ catch (ApiException e) ```json { "component": { - "id": 292609, - "name": "Text messages", - "pricing_scheme": "stairstep", - "unit_name": "text message", - "unit_price": null, - "product_family_id": 528484, + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, "price_per_unit_in_cents": null, - "kind": "metered_component", + "kind": "on_off_component", "archived": false, - "taxable": false, - "description": null, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, "created_at": "2019-08-02T05:54:53-04:00", - "prices": [ - { - "id": 47, - "component_id": 292609, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 173, - "formatted_unit_price": "$1.00" - } - ], - "default_price_point_name": "Original" + "default_price_point_name": "Original", + "product_family_name": "Chargify" } } ``` -# List Components for Product Family +# Archive Component -This request will return a list of components for a particular product family. +Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. ```csharp -ListComponentsForProductFamilyAsync( - Models.ListComponentsForProductFamilyInput input) +ArchiveComponentAsync( + int productFamilyId, + string componentId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family | -| `includeArchived` | `bool?` | Query, Optional | Include archived items. | -| `filterIds` | `List` | Query, Optional | Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2`. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=created_at`. | -| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional. | -| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | ## Response Type -[`Task>`](../../doc/models/component-response.md) +[`Task`](../../doc/models/component.md) ## Example Usage ```csharp -ListComponentsForProductFamilyInput listComponentsForProductFamilyInput = new ListComponentsForProductFamilyInput -{ - ProductFamilyId = 140, -Liquid error: Value cannot be null. (Parameter 'key') Page = 2, - PerPage = 50, - DateField = BasicDateField.UpdatedAt, -Liquid error: Value cannot be null. (Parameter 'key')}; - +int productFamilyId = 140; +string componentId = "component_id8"; try { - List result = await componentsController.ListComponentsForProductFamilyAsync(listComponentsForProductFamilyInput); + Component result = await componentsController.ArchiveComponentAsync( + productFamilyId, + componentId + ); } catch (ApiException e) { @@ -814,155 +1104,74 @@ catch (ApiException e) ## Example Response *(as JSON)* ```json -[ - { - "component": { - "id": 399850, - "name": "$1.00 component", - "pricing_scheme": "per_unit", - "unit_name": "Component", - "unit_price": "1.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "quantity_based_component", - "archived": false, - "taxable": false, - "description": "Component", - "default_price_point_id": 121000, - "prices": [ - { - "id": 630687, - "component_id": 399850, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 121000, - "formatted_unit_price": "$1.00" - } - ], - "price_point_count": 2, - "price_points_url": "https://general-goods.chargify.com/components/399850/price_points", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:38-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - }, - { - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:37-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - }, - { - "component": { - "id": 386937, - "name": "Cancellation fee", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "35.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": false, - "description": "", - "default_price_point_id": 108307, - "price_point_count": 1, - "price_points_url": "https://general-goods.chargify.com/components/386937/price_points", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:38-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - } -] +{ + "id": 25407138, + "name": "cillum aute", + "pricing_scheme": "stairstep", + "unit_name": "nulla in", + "unit_price": "Excepteur veniam", + "product_family_id": -56705047, + "kind": "prepaid_usage_component", + "archived": true, + "taxable": false, + "description": "reprehenderit laborum qui fugiat", + "default_price_point_id": -64328176, + "price_point_count": 15252407, + "price_points_url": "dolor mollit consequat", + "tax_code": "ea nisi", + "recurring": false, + "created_at": "2016-11-08T16:22:26-05:00", + "default_price_point_name": "cupidatat Lorem non aliqua", + "product_family_name": "do elit", + "hide_date_range_on_invoice": false +} ``` +## Errors -# Create Component Price Point +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -This endpoint can be used to create a new price point for an existing component. + +# Update Component + +This request will update a component. + +You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. ```csharp -CreateComponentPricePointAsync( - int componentId, - Models.CreateComponentPricePointRequest body = null) +UpdateComponentAsync( + string componentId, + Models.UpdateComponentRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `body` | [`CreateComponentPricePointRequest`](../../doc/models/create-component-price-point-request.md) | Body, Optional | - | +| `componentId` | `string` | Template, Required | The id or handle of the component | +| `body` | [`UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/component-price-point-response.md) +[`Task`](../../doc/models/component-response.md) ## Example Usage ```csharp -int componentId = 222; -CreateComponentPricePointRequest body = new CreateComponentPricePointRequest +string componentId = "component_id8"; +UpdateComponentRequest body = new UpdateComponentRequest { - PricePoint = CreateComponentPricePointRequestPricePoint.FromCreateComponentPricePoint( - new CreateComponentPricePoint - { - Name = "Wholesale", - PricingScheme = PricingScheme.Stairstep, - Prices = new List - { - new Price - { - StartingQuantity = PriceStartingQuantity.FromString("1"), - UnitPrice = PriceUnitPrice.FromString("5.00"), - EndingQuantity = PriceEndingQuantity.FromString("100"), - }, - new Price - { - StartingQuantity = PriceStartingQuantity.FromString("101"), - UnitPrice = PriceUnitPrice.FromString("4.00"), - }, - }, - Handle = "wholesale-handle", - UseSiteExchangeRate = false, - } - ), + Component = new UpdateComponent + { + ItemCategory = ItemCategory.EnumBusinessSoftware, + }, }; try { - ComponentPricePointResponse result = await componentsController.CreateComponentPricePointAsync( + ComponentResponse result = await componentsController.UpdateComponentAsync( componentId, body ); @@ -974,249 +1183,41 @@ catch (ApiException e) } ``` - -# List Component Price Points - -Use this endpoint to read current price points that are associated with a component. - -You may specify the component by using either the numeric id or the `handle:gold` syntax. - -When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. - -If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - -```csharp -ListComponentPricePointsAsync( - Models.ListComponentPricePointsInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `currencyPrices` | `bool?` | Query, Optional | Include an array of currency price data | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | - -## Response Type - -[`Task`](../../doc/models/component-price-points-response.md) - -## Example Usage - -```csharp -ListComponentPricePointsInput listComponentPricePointsInput = new ListComponentPricePointsInput -{ - ComponentId = 222, - Page = 2, - PerPage = 50, -Liquid error: Value cannot be null. (Parameter 'key')}; - -try -{ - ComponentPricePointsResponse result = await componentsController.ListComponentPricePointsAsync(listComponentPricePointsInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* +## Example Response *(as JSON)* ```json { - "price_points": [ - { - "id": 80, - "default": false, - "name": "Wholesale Two", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "wholesale-two", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 121, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "5.0" - } - ] - }, - { - "id": 81, - "default": false, - "name": "MSRP", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "msrp", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 122, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } - ] -} -``` - - -# Create Component Price Points - -Use this endpoint to create multiple component price points in one request. - -```csharp -CreateComponentPricePointsAsync( - string componentId, - Models.CreateComponentPricePointsRequest body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | The Chargify id of the component for which you want to fetch price points. | -| `body` | [`CreateComponentPricePointsRequest`](../../doc/models/create-component-price-points-request.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/component-price-points-response.md) - -## Example Usage - -```csharp -string componentId = "component_id8"; -CreateComponentPricePointsRequest body = new CreateComponentPricePointsRequest -{ - PricePoints = new List - { - CreateComponentPricePointsRequestPricePoints.FromCreateComponentPricePoint( - new CreateComponentPricePoint - { - Name = "Wholesale", - PricingScheme = PricingScheme.PerUnit, - Prices = new List - { - new Price - { - StartingQuantity = PriceStartingQuantity.FromNumber(1), - UnitPrice = PriceUnitPrice.FromPrecision(5), - }, - }, - Handle = "wholesale", - } - ), - CreateComponentPricePointsRequestPricePoints.FromCreateComponentPricePoint( - new CreateComponentPricePoint - { - Name = "MSRP", - PricingScheme = PricingScheme.PerUnit, - Prices = new List - { - new Price - { - StartingQuantity = PriceStartingQuantity.FromNumber(1), - UnitPrice = PriceUnitPrice.FromPrecision(4), - }, - }, - Handle = "msrp", - } - ), - CreateComponentPricePointsRequestPricePoints.FromCreateComponentPricePoint( - new CreateComponentPricePoint - { - Name = "Special Pricing", - PricingScheme = PricingScheme.PerUnit, - Prices = new List - { - new Price - { - StartingQuantity = PriceStartingQuantity.FromNumber(1), - UnitPrice = PriceUnitPrice.FromPrecision(5), - }, - }, - Handle = "special", - } - ), - }, -}; - -try -{ - ComponentPricePointsResponse result = await componentsController.CreateComponentPricePointsAsync( - componentId, - body - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } } ``` -## Example Response *(as JSON)* +## Errors -```json -{ - "price_points": [ - { - "id": 80, - "default": false, - "name": "Wholesale Two", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "wholesale-two", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 121, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "5.0" - } - ] - }, - { - "id": 81, - "default": false, - "name": "MSRP", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "msrp", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 122, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } - ] -} -``` +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | # Update Component Price Point @@ -1263,18 +1264,18 @@ UpdateComponentPricePointRequest body = new UpdateComponentPricePointRequest new UpdatePrice { Id = 1, - EndingQuantity = 100, - UnitPrice = 5, + EndingQuantity = UpdatePriceEndingQuantity.FromNumber(100), + UnitPrice = UpdatePriceUnitPrice.FromPrecision(5), }, new UpdatePrice { Id = 2, - Destroy = "true", + Destroy = true, }, new UpdatePrice { - UnitPrice = 4, - StartingQuantity = 101, + UnitPrice = UpdatePriceUnitPrice.FromPrecision(4), + StartingQuantity = UpdatePriceStartingQuantity.FromNumber(101), }, }, }, @@ -1295,6 +1296,12 @@ catch (ApiException e) } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + # Archive Component Price Point @@ -1370,38 +1377,629 @@ catch (ApiException e) } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Unarchive Component Price Point + +Use this endpoint to unarchive a component price point. + +```csharp +UnarchiveComponentPricePointAsync( + int componentId, + int pricePointId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | + +## Response Type + +[`Task`](../../doc/models/component-price-point-response.md) + +## Example Usage + +```csharp +int componentId = 222; +int pricePointId = 10; +try +{ + ComponentPricePointResponse result = await componentsController.UnarchiveComponentPricePointAsync( + componentId, + pricePointId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 79, + "default": false, + "name": "Wholesale", + "pricing_scheme": "stairstep", + "component_id": 74, + "handle": "wholesale-handle", + "archived_at": null, + "created_at": "2017-07-05T13:44:30-04:00", + "updated_at": "2017-07-05T13:44:30-04:00", + "prices": [ + { + "id": 119, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": 100, + "unit_price": "5.0" + }, + { + "id": 120, + "component_id": 74, + "starting_quantity": 101, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } +} +``` + + +# Read Component by Id + +This request will return information regarding a component from a specific product family. + +You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + +```csharp +ReadComponentByIdAsync( + int productFamilyId, + string componentId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | + +## Response Type + +[`Task`](../../doc/models/component-response.md) + +## Example Usage + +```csharp +int productFamilyId = 140; +string componentId = "component_id8"; +try +{ + ComponentResponse result = await componentsController.ReadComponentByIdAsync( + productFamilyId, + componentId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } +} +``` + + +# Update Product Family Component + +This request will update a component from a specific product family. + +You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + +```csharp +UpdateProductFamilyComponentAsync( + int productFamilyId, + string componentId, + Models.UpdateComponentRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | +| `body` | [`UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/component-response.md) + +## Example Usage + +```csharp +int productFamilyId = 140; +string componentId = "component_id8"; +UpdateComponentRequest body = new UpdateComponentRequest +{ + Component = new UpdateComponent + { + ItemCategory = ItemCategory.EnumBusinessSoftware, + }, +}; + +try +{ + ComponentResponse result = await componentsController.UpdateProductFamilyComponentAsync( + productFamilyId, + componentId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Update Default Price Point for Component + +Sets a new default price point for the component. This new default will apply to all new subscriptions going forward - existing subscriptions will remain on their current price point. + +See [Price Points Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-points) for more information on price points and moving subscriptions between price points. + +Note: Custom price points are not able to be set as the default for a component. + +```csharp +UpdateDefaultPricePointForComponentAsync( + int componentId, + int pricePointId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | + +## Response Type + +[`Task`](../../doc/models/component-response.md) + +## Example Usage + +```csharp +int componentId = 222; +int pricePointId = 10; +try +{ + ComponentResponse result = await componentsController.UpdateDefaultPricePointForComponentAsync( + componentId, + pricePointId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 292609, + "name": "Text messages", + "pricing_scheme": "stairstep", + "unit_name": "text message", + "unit_price": null, + "product_family_id": 528484, + "price_per_unit_in_cents": null, + "kind": "metered_component", + "archived": false, + "taxable": false, + "description": null, + "created_at": "2019-08-02T05:54:53-04:00", + "prices": [ + { + "id": 47, + "component_id": 292609, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 173, + "formatted_unit_price": "$1.00" + } + ], + "default_price_point_name": "Original" + } +} +``` + + +# List Components for Product Family + +This request will return a list of components for a particular product family. + +```csharp +ListComponentsForProductFamilyAsync( + Models.ListComponentsForProductFamilyInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family | +| `includeArchived` | `bool?` | Query, Optional | Include archived items. | +| `filterIds` | `List` | Query, Optional | Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2`. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=created_at`. | +| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional. | +| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`Task>`](../../doc/models/component-response.md) + +## Example Usage + +```csharp +ListComponentsForProductFamilyInput listComponentsForProductFamilyInput = new ListComponentsForProductFamilyInput +{ + ProductFamilyId = 140, +Liquid error: Value cannot be null. (Parameter 'key') Page = 2, + PerPage = 50, + DateField = BasicDateField.UpdatedAt, +Liquid error: Value cannot be null. (Parameter 'key')}; + +try +{ + List result = await componentsController.ListComponentsForProductFamilyAsync(listComponentsForProductFamilyInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "component": { + "id": 399850, + "name": "$1.00 component", + "pricing_scheme": "per_unit", + "unit_name": "Component", + "unit_price": "1.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "quantity_based_component", + "archived": false, + "taxable": false, + "description": "Component", + "default_price_point_id": 121000, + "prices": [ + { + "id": 630687, + "component_id": 399850, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 121000, + "formatted_unit_price": "$1.00" + } + ], + "price_point_count": 2, + "price_points_url": "https://general-goods.chargify.com/components/399850/price_points", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:38-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + }, + { + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:37-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + }, + { + "component": { + "id": 386937, + "name": "Cancellation fee", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "35.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": false, + "description": "", + "default_price_point_id": 108307, + "price_point_count": 1, + "price_points_url": "https://general-goods.chargify.com/components/386937/price_points", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:38-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + } +] +``` + + +# Create Component Price Point + +This endpoint can be used to create a new price point for an existing component. + +```csharp +CreateComponentPricePointAsync( + int componentId, + Models.CreateComponentPricePointRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `body` | [`CreateComponentPricePointRequest`](../../doc/models/create-component-price-point-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/component-price-point-response.md) + +## Example Usage + +```csharp +int componentId = 222; +CreateComponentPricePointRequest body = new CreateComponentPricePointRequest +{ + PricePoint = CreateComponentPricePointRequestPricePoint.FromCreateComponentPricePoint( + new CreateComponentPricePoint + { + Name = "Wholesale", + PricingScheme = PricingScheme.Stairstep, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromString("1"), + UnitPrice = PriceUnitPrice.FromString("5.00"), + EndingQuantity = PriceEndingQuantity.FromString("100"), + }, + new Price + { + StartingQuantity = PriceStartingQuantity.FromString("101"), + UnitPrice = PriceUnitPrice.FromString("4.00"), + }, + }, + Handle = "wholesale-handle", + UseSiteExchangeRate = false, + } + ), +}; + +try +{ + ComponentPricePointResponse result = await componentsController.CreateComponentPricePointAsync( + componentId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + -# Unarchive Component Price Point +# Create Component Price Points -Use this endpoint to unarchive a component price point. +Use this endpoint to create multiple component price points in one request. ```csharp -UnarchiveComponentPricePointAsync( - int componentId, - int pricePointId) +CreateComponentPricePointsAsync( + string componentId, + Models.CreateComponentPricePointsRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | +| `componentId` | `string` | Template, Required | The Chargify id of the component for which you want to fetch price points. | +| `body` | [`CreateComponentPricePointsRequest`](../../doc/models/create-component-price-points-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/component-price-point-response.md) +[`Task`](../../doc/models/component-price-points-response.md) ## Example Usage ```csharp -int componentId = 222; -int pricePointId = 10; +string componentId = "component_id8"; +CreateComponentPricePointsRequest body = new CreateComponentPricePointsRequest +{ + PricePoints = new List + { + CreateComponentPricePointsRequestPricePoints.FromCreateComponentPricePoint( + new CreateComponentPricePoint + { + Name = "Wholesale", + PricingScheme = PricingScheme.PerUnit, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(1), + UnitPrice = PriceUnitPrice.FromPrecision(5), + }, + }, + Handle = "wholesale", + } + ), + CreateComponentPricePointsRequestPricePoints.FromCreateComponentPricePoint( + new CreateComponentPricePoint + { + Name = "MSRP", + PricingScheme = PricingScheme.PerUnit, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(1), + UnitPrice = PriceUnitPrice.FromPrecision(4), + }, + }, + Handle = "msrp", + } + ), + CreateComponentPricePointsRequestPricePoints.FromCreateComponentPricePoint( + new CreateComponentPricePoint + { + Name = "Special Pricing", + PricingScheme = PricingScheme.PerUnit, + Prices = new List + { + new Price + { + StartingQuantity = PriceStartingQuantity.FromNumber(1), + UnitPrice = PriceUnitPrice.FromPrecision(5), + }, + }, + Handle = "special", + } + ), + }, +}; + try { - ComponentPricePointResponse result = await componentsController.UnarchiveComponentPricePointAsync( + ComponentPricePointsResponse result = await componentsController.CreateComponentPricePointsAsync( componentId, - pricePointId + body ); } catch (ApiException e) @@ -1415,33 +2013,48 @@ catch (ApiException e) ```json { - "price_point": { - "id": 79, - "default": false, - "name": "Wholesale", - "pricing_scheme": "stairstep", - "component_id": 74, - "handle": "wholesale-handle", - "archived_at": null, - "created_at": "2017-07-05T13:44:30-04:00", - "updated_at": "2017-07-05T13:44:30-04:00", - "prices": [ - { - "id": 119, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": 100, - "unit_price": "5.0" - }, - { - "id": 120, - "component_id": 74, - "starting_quantity": 101, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } + "price_points": [ + { + "id": 80, + "default": false, + "name": "Wholesale Two", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "wholesale-two", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 121, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "5.0" + } + ] + }, + { + "id": 81, + "default": false, + "name": "MSRP", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "msrp", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 122, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } + ] } ``` @@ -1469,7 +2082,7 @@ CreateCurrencyPricesAsync( ## Response Type -[`Task>`](../../doc/models/currency-price.md) +[`Task`](../../doc/models/component-currency-prices-response.md) ## Example Usage @@ -1496,7 +2109,7 @@ CreateCurrencyPricesRequest body = new CreateCurrencyPricesRequest try { - List result = await componentsController.CreateCurrencyPricesAsync( + ComponentCurrencyPricesResponse result = await componentsController.CreateCurrencyPricesAsync( pricePointId, body ); @@ -1508,6 +2121,29 @@ catch (ApiException e) } ``` +## Example Response *(as JSON)* + +```json +{ + "currency_prices": [ + { + "id": 100, + "currency": "EUR", + "price": "123", + "formatted_price": "€123,00", + "price_id": 32669, + "price_point_id": 25554 + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + # Update Currency Prices @@ -1530,7 +2166,7 @@ UpdateCurrencyPricesAsync( ## Response Type -[`Task>`](../../doc/models/currency-price.md) +[`Task`](../../doc/models/component-currency-prices-response.md) ## Example Usage @@ -1555,7 +2191,7 @@ UpdateCurrencyPricesRequest body = new UpdateCurrencyPricesRequest try { - List result = await componentsController.UpdateCurrencyPricesAsync( + ComponentCurrencyPricesResponse result = await componentsController.UpdateCurrencyPricesAsync( pricePointId, body ); @@ -1567,86 +2203,18 @@ catch (ApiException e) } ``` - -# List All Component Price Points - -This method allows to retrieve a list of Components Price Points belonging to a Site. - -```csharp -ListAllComponentPricePointsAsync( - Models.ListAllComponentPricePointsInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `filterDateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | -| `filterEndDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `filterEndDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `include` | [`ListComponentsPricePointsInclude?`](../../doc/models/list-components-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterStartDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `filterStartDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=custom,catalog`. | -| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `filterIds` | `List` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | -| `filterArchivedAt` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | - -## Response Type - -[`Task`](../../doc/models/list-components-price-points-response.md) - -## Example Usage - -```csharp -ListAllComponentPricePointsInput listAllComponentPricePointsInput = new ListAllComponentPricePointsInput -{ -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') Include = ListComponentsPricePointsInclude.CurrencyPrices, - Page = 2, - PerPage = 50, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; - -try -{ - ListComponentsPricePointsResponse result = await componentsController.ListAllComponentPricePointsAsync(listAllComponentPricePointsInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - ## Example Response *(as JSON)* ```json { - "price_points": [ + "currency_prices": [ { - "id": 1, - "name": "Auto-created", - "type": "default", - "pricing_scheme": "per_unit", - "component_id": 2, - "handle": "auto-created", - "archived_at": null, - "created_at": "2021-02-21T11:05:57-05:00", - "updated_at": "2021-02-21T11:05:57-05:00", - "prices": [ - { - "id": 3, - "component_id": 2, - "starting_quantity": 0, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 1, - "formatted_unit_price": "$1.00", - "segment_id": null - } - ], - "tax_included": false + "id": 100, + "currency": "EUR", + "price": "123", + "formatted_price": "€123,00", + "price_id": 32669, + "price_point_id": 25554 } ] } @@ -1656,5 +2224,5 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | diff --git a/doc/controllers/coupons.md b/doc/controllers/coupons.md index 9c7467a..ab880a7 100644 --- a/doc/controllers/coupons.md +++ b/doc/controllers/coupons.md @@ -11,18 +11,18 @@ CouponsController couponsController = client.CouponsController; ## Methods * [Create Coupon](../../doc/controllers/coupons.md#create-coupon) -* [List Coupons for Product Family](../../doc/controllers/coupons.md#list-coupons-for-product-family) -* [Read Coupon by Code](../../doc/controllers/coupons.md#read-coupon-by-code) -* [Read Coupon](../../doc/controllers/coupons.md#read-coupon) * [Update Coupon](../../doc/controllers/coupons.md#update-coupon) -* [Archive Coupon](../../doc/controllers/coupons.md#archive-coupon) * [List Coupons](../../doc/controllers/coupons.md#list-coupons) * [Read Coupon Usage](../../doc/controllers/coupons.md#read-coupon-usage) -* [Validate Coupon](../../doc/controllers/coupons.md#validate-coupon) -* [Update Coupon Currency Prices](../../doc/controllers/coupons.md#update-coupon-currency-prices) * [Create Coupon Subcodes](../../doc/controllers/coupons.md#create-coupon-subcodes) +* [Read Coupon by Code](../../doc/controllers/coupons.md#read-coupon-by-code) +* [Archive Coupon](../../doc/controllers/coupons.md#archive-coupon) * [List Coupon Subcodes](../../doc/controllers/coupons.md#list-coupon-subcodes) +* [Read Coupon](../../doc/controllers/coupons.md#read-coupon) +* [Validate Coupon](../../doc/controllers/coupons.md#validate-coupon) * [Update Coupon Subcodes](../../doc/controllers/coupons.md#update-coupon-subcodes) +* [List Coupons for Product Family](../../doc/controllers/coupons.md#list-coupons-for-product-family) +* [Update Coupon Currency Prices](../../doc/controllers/coupons.md#update-coupon-currency-prices) * [Delete Coupon Subcode](../../doc/controllers/coupons.md#delete-coupon-subcode) @@ -71,7 +71,7 @@ CreateOrUpdateCoupon body = new CreateOrUpdateCoupon { Name = "15% off", Code = "15OFF", - Percentage = CreateOrUpdatePercentageCouponPercentage.FromString("15"), + Percentage = CreateOrUpdatePercentageCouponPercentage.FromPrecision(15), Description = "15% off for life", AllowNegativeBalance = false, Recurring = false, @@ -117,205 +117,20 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# List Coupons for Product Family - -List coupons for a specific Product Family in a Site. - -If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - -```csharp -ListCouponsForProductFamilyAsync( - Models.ListCouponsForProductFamilyInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterDateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `filter[date_field]=created_at`. | -| `filterEndDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[date_field]=2011-12-15`. | -| `filterEndDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `?filter[end_datetime]=2011-12-1T10:15:30+01:00`. | -| `filterStartDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-17`. | -| `filterStartDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. | -| `filterIds` | `List` | Query, Optional | Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. | -| `filterCodes` | `List` | Query, Optional | Allows fetching coupons with matching codes based on provided values. Use in query `filter[codes]=free,free_trial`. | -| `currencyPrices` | `bool?` | Query, Optional | When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. | -| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`Task>`](../../doc/models/coupon-response.md) - -## Example Usage - -```csharp -ListCouponsForProductFamilyInput listCouponsForProductFamilyInput = new ListCouponsForProductFamilyInput -{ - ProductFamilyId = 140, - Page = 2, - PerPage = 50, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') CurrencyPrices = true, -Liquid error: Value cannot be null. (Parameter 'key')}; - -try -{ - List result = await couponsController.ListCouponsForProductFamilyAsync(listCouponsForProductFamilyInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "coupon": { - "id": 999999, - "name": "50% coupon", - "code": "50PERCENT", - "description": "50 PERCENT OFF", - "amount_in_cents": null, - "product_family_id": 527890, - "created_at": "2016-10-21T17:02:08-04:00", - "updated_at": "2016-10-21T17:06:11-04:00", - "start_date": "2016-10-21T17:02:08-04:00", - "end_date": null, - "percentage": 50, - "recurring": true, - "duration_period_count": null, - "duration_interval": 1, - "duration_interval_unit": "day", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "100", - "stackable": false, - "compounding_strategy": "compound", - "coupon_restrictions": [], - "use_site_exchange_rate": true - } - }, - { - "coupon": { - "id": 123456, - "name": "100% coupon", - "code": "100PERCENT", - "description": "100 PERCENT OFF", - "amount_in_cents": null, - "product_family_id": 527890, - "created_at": "2016-10-21T17:02:08-04:00", - "updated_at": "2016-10-21T17:06:11-04:00", - "start_date": "2016-10-21T17:02:08-04:00", - "end_date": null, - "percentage": 50, - "recurring": true, - "duration_period_count": null, - "duration_interval": 1, - "duration_interval_unit": "day", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "100", - "stackable": false, - "compounding_strategy": "compound", - "coupon_restrictions": [], - "use_site_exchange_rate": true - } - }, - { - "coupon": { - "id": 888888, - "name": "25% coupon", - "code": "25PERCENT", - "description": "25 PERCENT OFF", - "amount_in_cents": null, - "product_family_id": 527890, - "created_at": "2016-10-21T17:02:08-04:00", - "updated_at": "2016-10-21T17:06:11-04:00", - "start_date": "2016-10-21T17:02:08-04:00", - "end_date": null, - "percentage": 25, - "recurring": true, - "duration_period_count": null, - "duration_interval": 1, - "duration_interval_unit": "day", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "100", - "stackable": false, - "compounding_strategy": "compound", - "coupon_restrictions": [ - { - "id": 37, - "item_type": "Component", - "item_id": 519, - "name": "test", - "handle": null - } - ], - "use_site_exchange_rate": true - } - } -] -``` - - -# Read Coupon by Code - -You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. - -If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. - -```csharp -ReadCouponByCodeAsync( - int? productFamilyId = null, - string code = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int?` | Query, Optional | The Chargify id of the product family to which the coupon belongs | -| `code` | `string` | Query, Optional | The code of the coupon | - -## Response Type - -[`Task`](../../doc/models/coupon-response.md) - -## Example Usage - -```csharp -try -{ - CouponResponse result = await couponsController.ReadCouponByCodeAsync(); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - -# Read Coupon +# Update Coupon -You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. -If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. +## Update Coupon -When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. +You can update a Coupon via the API with a PUT request to the resource endpoint. -If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. +You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: +`{ "": boolean_value }` ```csharp -ReadCouponAsync( +UpdateCouponAsync( int productFamilyId, - int couponId) + int couponId, + Models.CreateOrUpdateCoupon body = null) ``` ## Parameters @@ -324,6 +139,7 @@ ReadCouponAsync( | --- | --- | --- | --- | | `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | | `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`CreateOrUpdateCoupon`](../../doc/models/create-or-update-coupon.md) | Body, Optional | - | ## Response Type @@ -334,11 +150,42 @@ ReadCouponAsync( ```csharp int productFamilyId = 140; int couponId = 162; +CreateOrUpdateCoupon body = new CreateOrUpdateCoupon +{ + Coupon = CreateOrUpdateCouponCoupon.FromCreateOrUpdatePercentageCoupon( + new CreateOrUpdatePercentageCoupon + { + Name = "15% off", + Code = "15OFF", + Percentage = CreateOrUpdatePercentageCouponPercentage.FromPrecision(15), + Description = "15% off for life", + AllowNegativeBalance = false, + Recurring = false, + EndDate = DateTime.ParseExact("2012-08-29T12:00:00-04:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + ProductFamilyId = "2", + Stackable = true, + CompoundingStrategy = CompoundingStrategy.Compound, + } + ), + RestrictedProducts = new Dictionary + { + ["1"] = true, + }, + RestrictedComponents = new Dictionary + { + ["1"] = true, + ["2"] = false, + }, +}; + try { - CouponResponse result = await couponsController.ReadCouponAsync( + CouponResponse result = await couponsController.UpdateCouponAsync( productFamilyId, - couponId + couponId, + body ); } catch (ApiException e) @@ -357,14 +204,14 @@ catch (ApiException e) "name": "Foo Bar", "code": "YEPPER99934", "description": "my cool coupon", - "amount_in_cents": null, + "amount_in_cents": 10000, "product_family_id": 4, - "product_family_name": "Billing Plans", "created_at": "2017-11-08T10:01:15-05:00", "updated_at": "2017-11-08T10:01:15-05:00", "start_date": "2017-11-08T10:01:15-05:00", "end_date": null, - "percentage": 33.3333, + "percentage": null, + "recurring": false, "duration_period_count": null, "duration_interval": null, "duration_interval_unit": null, @@ -379,193 +226,11 @@ catch (ApiException e) ``` -# Update Coupon +# List Coupons -## Update Coupon +You can retrieve a list of coupons. -You can update a Coupon via the API with a PUT request to the resource endpoint. - -You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: -`{ "": boolean_value }` - -```csharp -UpdateCouponAsync( - int productFamilyId, - int couponId, - Models.CreateOrUpdateCoupon body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`CreateOrUpdateCoupon`](../../doc/models/create-or-update-coupon.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/coupon-response.md) - -## Example Usage - -```csharp -int productFamilyId = 140; -int couponId = 162; -CreateOrUpdateCoupon body = new CreateOrUpdateCoupon -{ - Coupon = CreateOrUpdateCouponCoupon.FromCreateOrUpdatePercentageCoupon( - new CreateOrUpdatePercentageCoupon - { - Name = "15% off", - Code = "15OFF", - Percentage = CreateOrUpdatePercentageCouponPercentage.FromString("15"), - Description = "15% off for life", - AllowNegativeBalance = false, - Recurring = false, - EndDate = DateTime.ParseExact("2012-08-29T12:00:00-04:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), - ProductFamilyId = "2", - Stackable = true, - CompoundingStrategy = CompoundingStrategy.Compound, - } - ), - RestrictedProducts = new Dictionary - { - ["1"] = true, - }, - RestrictedComponents = new Dictionary - { - ["1"] = true, - ["2"] = false, - }, -}; - -try -{ - CouponResponse result = await couponsController.UpdateCouponAsync( - productFamilyId, - couponId, - body - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "coupon": { - "id": 67, - "name": "Foo Bar", - "code": "YEPPER99934", - "description": "my cool coupon", - "amount_in_cents": 10000, - "product_family_id": 4, - "created_at": "2017-11-08T10:01:15-05:00", - "updated_at": "2017-11-08T10:01:15-05:00", - "start_date": "2017-11-08T10:01:15-05:00", - "end_date": null, - "percentage": null, - "recurring": false, - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": null, - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "compound", - "coupon_restrictions": [] - } -} -``` - - -# Archive Coupon - -You can archive a Coupon via the API with the archive method. -Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. -The `archived_at` date and time will be assigned. - -```csharp -ArchiveCouponAsync( - int productFamilyId, - int couponId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | - -## Response Type - -[`Task`](../../doc/models/coupon-response.md) - -## Example Usage - -```csharp -int productFamilyId = 140; -int couponId = 162; -try -{ - CouponResponse result = await couponsController.ArchiveCouponAsync( - productFamilyId, - couponId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "coupon": { - "id": 67, - "name": "Foo Bar", - "code": "YEPPER99934", - "description": "my cool coupon", - "amount_in_cents": 10000, - "product_family_id": 4, - "created_at": "2017-11-08T10:01:15-05:00", - "updated_at": "2017-11-08T10:01:15-05:00", - "start_date": "2017-11-08T10:01:15-05:00", - "end_date": null, - "percentage": null, - "recurring": false, - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": "2016-12-02T13:09:33-05:00", - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "compound", - "coupon_restrictions": [] - } -} -``` - - -# List Coupons - -You can retrieve a list of coupons. - -If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. +If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. ```csharp ListCouponsAsync( @@ -642,7 +307,7 @@ catch (ApiException e) "product_family_name": "string", "start_date": "string", "end_date": "string", - "percentage": 0, + "percentage": "10", "recurring": true, "recurring_scheme": "do_not_recur", "duration_period_count": 0, @@ -750,55 +415,87 @@ catch (ApiException e) ``` -# Validate Coupon +# Create Coupon Subcodes -You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. +## Coupon Subcodes Intro -If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported: +Coupon Subcodes allow you to create a set of unique codes that allow you to expand the use of one coupon. -+ Coupon not found -+ Coupon is invalid -+ Coupon expired +For example: -If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. +Master Coupon Code: -Eg. ++ SPRING2020 -``` -https://.chargify.com/product_families/handle:/coupons/validate.?code= -``` +Coupon Subcodes: -Or: ++ SPRING90210 ++ DP80302 ++ SPRINGBALTIMORE -``` -https://.chargify.com/coupons/validate.?code=&product_family_id= -``` +Coupon subcodes can be administered in the Admin Interface or via the API. + +When creating a coupon subcode, you must specify a coupon to attach it to using the coupon_id. Valid coupon subcodes are all capital letters, contain only letters and numbers, and do not have any spaces. Lowercase letters will be capitalized before the subcode is created. + +## Coupon Subcodes Documentation + +Full documentation on how to create coupon subcodes in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#coupon-codes). + +Additionally, for documentation on how to apply a coupon to a Subscription within the Chargify UI, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#coupon). + +## Create Coupon Subcode + +This request allows you to create specific subcodes underneath an existing coupon code. + +*Note*: If you are using any of the allowed special characters ("%", "@", "+", "-", "_", and "."), you must encode them for use in the URL. + + % to %25 + @ to %40 + + to %2B + - to %2D + _ to %5F + . to %2E + +So, if the coupon subcode is `20%OFF`, the URL to delete this coupon subcode would be: `https://.chargify.com/coupons/567/codes/20%25OFF.` ```csharp -ValidateCouponAsync( - string code, - int? productFamilyId = null) +CreateCouponSubcodesAsync( + int couponId, + Models.CouponSubcodes body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `code` | `string` | Query, Required | The code of the coupon | -| `productFamilyId` | `int?` | Query, Optional | The Chargify id of the product family to which the coupon belongs | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/coupon-response.md) +[`Task`](../../doc/models/coupon-subcodes-response.md) ## Example Usage ```csharp -string code = "code8"; +int couponId = 162; +CouponSubcodes body = new CouponSubcodes +{ + Codes = new List + { + "BALTIMOREFALL", + "ORLANDOFALL", + "DETROITFALL", + }, +}; + try { - CouponResponse result = await couponsController.ValidateCouponAsync(code); -} + CouponSubcodesResponse result = await couponsController.CreateCouponSubcodesAsync( + couponId, + body + ); +} catch (ApiException e) { // TODO: Handle exception here @@ -810,89 +507,46 @@ catch (ApiException e) ```json { - "coupon": { - "id": 66, - "name": "Foo Bar", - "code": "YEPPER9993", - "description": "my cool coupon", - "amount_in_cents": 10000, - "product_family_id": 4, - "created_at": "2017-11-07T14:51:52-05:00", - "updated_at": "2017-11-07T15:14:24-05:00", - "start_date": "2017-11-07T14:51:52-05:00", - "end_date": null, - "percentage": null, - "recurring": false, - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": null, - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "full-price", - "coupon_restrictions": [] - } + "created_codes": [ + "BALTIMOREFALL", + "ORLANDOFALL", + "DETROITFALL" + ], + "duplicate_codes": [], + "invalid_codes": [] } ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | - -# Update Coupon Currency Prices +# Read Coupon by Code -This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. +You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. -Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. +If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. ```csharp -UpdateCouponCurrencyPricesAsync( - int couponId, - Models.CouponCurrencyRequest body = null) +ReadCouponByCodeAsync( + int? productFamilyId = null, + string code = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`CouponCurrencyRequest`](../../doc/models/coupon-currency-request.md) | Body, Optional | - | +| `productFamilyId` | `int?` | Query, Optional | The Chargify id of the product family to which the coupon belongs | +| `code` | `string` | Query, Optional | The code of the coupon | ## Response Type -[`Task`](../../doc/models/coupon-currency-response.md) +[`Task`](../../doc/models/coupon-response.md) ## Example Usage ```csharp -int couponId = 162; -CouponCurrencyRequest body = new CouponCurrencyRequest -{ - CurrencyPrices = new List - { - new UpdateCouponCurrency - { - Currency = "EUR", - Price = 10, - }, - new UpdateCouponCurrency - { - Currency = "GBP", - Price = 9, - }, - }, -}; - try { - CouponCurrencyResponse result = await couponsController.UpdateCouponCurrencyPricesAsync( - couponId, - body - ); + CouponResponse result = await couponsController.ReadCouponByCodeAsync(); } catch (ApiException e) { @@ -902,85 +556,39 @@ catch (ApiException e) ``` -# Create Coupon Subcodes - -## Coupon Subcodes Intro - -Coupon Subcodes allow you to create a set of unique codes that allow you to expand the use of one coupon. - -For example: - -Master Coupon Code: - -+ SPRING2020 - -Coupon Subcodes: - -+ SPRING90210 -+ DP80302 -+ SPRINGBALTIMORE - -Coupon subcodes can be administered in the Admin Interface or via the API. - -When creating a coupon subcode, you must specify a coupon to attach it to using the coupon_id. Valid coupon subcodes are all capital letters, contain only letters and numbers, and do not have any spaces. Lowercase letters will be capitalized before the subcode is created. - -## Coupon Subcodes Documentation - -Full documentation on how to create coupon subcodes in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#coupon-codes). - -Additionally, for documentation on how to apply a coupon to a Subscription within the Chargify UI, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#coupon). - -## Create Coupon Subcode - -This request allows you to create specific subcodes underneath an existing coupon code. - -*Note*: If you are using any of the allowed special characters ("%", "@", "+", "-", "_", and "."), you must encode them for use in the URL. - - % to %25 - @ to %40 - + to %2B - - to %2D - _ to %5F - . to %2E +# Archive Coupon -So, if the coupon subcode is `20%OFF`, the URL to delete this coupon subcode would be: `https://.chargify.com/coupons/567/codes/20%25OFF.` +You can archive a Coupon via the API with the archive method. +Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. +The `archived_at` date and time will be assigned. ```csharp -CreateCouponSubcodesAsync( - int couponId, - Models.CouponSubcodes body = null) +ArchiveCouponAsync( + int productFamilyId, + int couponId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | | `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/coupon-subcodes-response.md) +[`Task`](../../doc/models/coupon-response.md) ## Example Usage ```csharp +int productFamilyId = 140; int couponId = 162; -CouponSubcodes body = new CouponSubcodes -{ - Codes = new List - { - "BALTIMOREFALL", - "ORLANDOFALL", - "DETROITFALL", - }, -}; - try { - CouponSubcodesResponse result = await couponsController.CreateCouponSubcodesAsync( - couponId, - body + CouponResponse result = await couponsController.ArchiveCouponAsync( + productFamilyId, + couponId ); } catch (ApiException e) @@ -994,13 +602,29 @@ catch (ApiException e) ```json { - "created_codes": [ - "BALTIMOREFALL", - "ORLANDOFALL", - "DETROITFALL" - ], - "duplicate_codes": [], - "invalid_codes": [] + "coupon": { + "id": 67, + "name": "Foo Bar", + "code": "YEPPER99934", + "description": "my cool coupon", + "amount_in_cents": 10000, + "product_family_id": 4, + "created_at": "2017-11-08T10:01:15-05:00", + "updated_at": "2017-11-08T10:01:15-05:00", + "start_date": "2017-11-08T10:01:15-05:00", + "end_date": null, + "percentage": null, + "recurring": false, + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": "2016-12-02T13:09:33-05:00", + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "compound", + "coupon_restrictions": [] + } } ``` @@ -1077,54 +701,430 @@ catch (ApiException e) ``` -# Update Coupon Subcodes - -You can update the subcodes for the given Coupon via the API with a PUT request to the resource endpoint. -Send an array of new coupon subcodes. - -**Note**: All current subcodes for that Coupon will be deleted first, and replaced with the list of subcodes sent to this endpoint. -The response will contain: +# Read Coupon -+ The created subcodes, +You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. +If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. -+ Subcodes that were not created because they already exist, +When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. -+ Any subcodes not created because they are invalid. +If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. ```csharp -UpdateCouponSubcodesAsync( - int couponId, - Models.CouponSubcodes body = null) +ReadCouponAsync( + int productFamilyId, + int couponId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | | `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/coupon-subcodes-response.md) +[`Task`](../../doc/models/coupon-response.md) ## Example Usage ```csharp +int productFamilyId = 140; int couponId = 162; -CouponSubcodes body = new CouponSubcodes +try { - Codes = new List - { - "AAAA", - "BBBB", - "CCCC", - }, -}; + CouponResponse result = await couponsController.ReadCouponAsync( + productFamilyId, + couponId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -try +## Example Response *(as JSON)* + +```json { - CouponSubcodesResponse result = await couponsController.UpdateCouponSubcodesAsync( + "coupon": { + "id": 67, + "name": "Foo Bar", + "code": "YEPPER99934", + "description": "my cool coupon", + "amount_in_cents": null, + "product_family_id": 4, + "product_family_name": "Billing Plans", + "created_at": "2017-11-08T10:01:15-05:00", + "updated_at": "2017-11-08T10:01:15-05:00", + "start_date": "2017-11-08T10:01:15-05:00", + "end_date": null, + "percentage": "33.3333", + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": null, + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "compound", + "coupon_restrictions": [] + } +} +``` + + +# Validate Coupon + +You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. + +If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported: + ++ Coupon not found ++ Coupon is invalid ++ Coupon expired + +If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. + +Eg. + +``` +https://.chargify.com/product_families/handle:/coupons/validate.?code= +``` + +Or: + +``` +https://.chargify.com/coupons/validate.?code=&product_family_id= +``` + +```csharp +ValidateCouponAsync( + string code, + int? productFamilyId = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `code` | `string` | Query, Required | The code of the coupon | +| `productFamilyId` | `int?` | Query, Optional | The Chargify id of the product family to which the coupon belongs | + +## Response Type + +[`Task`](../../doc/models/coupon-response.md) + +## Example Usage + +```csharp +string code = "code8"; +try +{ + CouponResponse result = await couponsController.ValidateCouponAsync(code); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "coupon": { + "id": 66, + "name": "Foo Bar", + "code": "YEPPER9993", + "description": "my cool coupon", + "amount_in_cents": 10000, + "product_family_id": 4, + "created_at": "2017-11-07T14:51:52-05:00", + "updated_at": "2017-11-07T15:14:24-05:00", + "start_date": "2017-11-07T14:51:52-05:00", + "end_date": null, + "percentage": null, + "recurring": false, + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": null, + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "full-price", + "coupon_restrictions": [] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | + + +# Update Coupon Subcodes + +You can update the subcodes for the given Coupon via the API with a PUT request to the resource endpoint. +Send an array of new coupon subcodes. + +**Note**: All current subcodes for that Coupon will be deleted first, and replaced with the list of subcodes sent to this endpoint. +The response will contain: + ++ The created subcodes, + ++ Subcodes that were not created because they already exist, + ++ Any subcodes not created because they are invalid. + +```csharp +UpdateCouponSubcodesAsync( + int couponId, + Models.CouponSubcodes body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/coupon-subcodes-response.md) + +## Example Usage + +```csharp +int couponId = 162; +CouponSubcodes body = new CouponSubcodes +{ + Codes = new List + { + "AAAA", + "BBBB", + "CCCC", + }, +}; + +try +{ + CouponSubcodesResponse result = await couponsController.UpdateCouponSubcodesAsync( + couponId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + +# List Coupons for Product Family + +List coupons for a specific Product Family in a Site. + +If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + +```csharp +ListCouponsForProductFamilyAsync( + Models.ListCouponsForProductFamilyInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterDateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `filter[date_field]=created_at`. | +| `filterEndDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[date_field]=2011-12-15`. | +| `filterEndDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `?filter[end_datetime]=2011-12-1T10:15:30+01:00`. | +| `filterStartDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-17`. | +| `filterStartDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. | +| `filterIds` | `List` | Query, Optional | Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. | +| `filterCodes` | `List` | Query, Optional | Allows fetching coupons with matching codes based on provided values. Use in query `filter[codes]=free,free_trial`. | +| `currencyPrices` | `bool?` | Query, Optional | When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. | +| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`Task>`](../../doc/models/coupon-response.md) + +## Example Usage + +```csharp +ListCouponsForProductFamilyInput listCouponsForProductFamilyInput = new ListCouponsForProductFamilyInput +{ + ProductFamilyId = 140, + Page = 2, + PerPage = 50, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') CurrencyPrices = true, +Liquid error: Value cannot be null. (Parameter 'key')}; + +try +{ + List result = await couponsController.ListCouponsForProductFamilyAsync(listCouponsForProductFamilyInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "coupon": { + "id": 999999, + "name": "50% coupon", + "code": "50PERCENT", + "description": "50 PERCENT OFF", + "amount_in_cents": null, + "product_family_id": 527890, + "created_at": "2016-10-21T17:02:08-04:00", + "updated_at": "2016-10-21T17:06:11-04:00", + "start_date": "2016-10-21T17:02:08-04:00", + "end_date": null, + "percentage": "50", + "recurring": true, + "duration_period_count": null, + "duration_interval": 1, + "duration_interval_unit": "day", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "100", + "stackable": false, + "compounding_strategy": "compound", + "coupon_restrictions": [], + "use_site_exchange_rate": true + } + }, + { + "coupon": { + "id": 123456, + "name": "100% coupon", + "code": "100PERCENT", + "description": "100 PERCENT OFF", + "amount_in_cents": null, + "product_family_id": 527890, + "created_at": "2016-10-21T17:02:08-04:00", + "updated_at": "2016-10-21T17:06:11-04:00", + "start_date": "2016-10-21T17:02:08-04:00", + "end_date": null, + "percentage": "50", + "recurring": true, + "duration_period_count": null, + "duration_interval": 1, + "duration_interval_unit": "day", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "100", + "stackable": false, + "compounding_strategy": "compound", + "coupon_restrictions": [], + "use_site_exchange_rate": true + } + }, + { + "coupon": { + "id": 888888, + "name": "25% coupon", + "code": "25PERCENT", + "description": "25 PERCENT OFF", + "amount_in_cents": null, + "product_family_id": 527890, + "created_at": "2016-10-21T17:02:08-04:00", + "updated_at": "2016-10-21T17:06:11-04:00", + "start_date": "2016-10-21T17:02:08-04:00", + "end_date": null, + "percentage": "25", + "recurring": true, + "duration_period_count": null, + "duration_interval": 1, + "duration_interval_unit": "day", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "100", + "stackable": false, + "compounding_strategy": "compound", + "coupon_restrictions": [ + { + "id": 37, + "item_type": "Component", + "item_id": 519, + "name": "test", + "handle": null + } + ], + "use_site_exchange_rate": true + } + } +] +``` + + +# Update Coupon Currency Prices + +This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. + +Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. + +```csharp +UpdateCouponCurrencyPricesAsync( + int couponId, + Models.CouponCurrencyRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`CouponCurrencyRequest`](../../doc/models/coupon-currency-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/coupon-currency-response.md) + +## Example Usage + +```csharp +int couponId = 162; +CouponCurrencyRequest body = new CouponCurrencyRequest +{ + CurrencyPrices = new List + { + new UpdateCouponCurrency + { + Currency = "EUR", + Price = 10, + }, + new UpdateCouponCurrency + { + Currency = "GBP", + Price = 9, + }, + }, +}; + +try +{ + CouponCurrencyResponse result = await couponsController.UpdateCouponCurrencyPricesAsync( couponId, body ); diff --git a/doc/controllers/custom-fields.md b/doc/controllers/custom-fields.md index ad23496..62c3021 100644 --- a/doc/controllers/custom-fields.md +++ b/doc/controllers/custom-fields.md @@ -10,48 +10,63 @@ CustomFieldsController customFieldsController = client.CustomFieldsController; ## Methods -* [Create Metafields](../../doc/controllers/custom-fields.md#create-metafields) -* [List Metafields](../../doc/controllers/custom-fields.md#list-metafields) * [Update Metafield](../../doc/controllers/custom-fields.md#update-metafield) +* [Update Metadata](../../doc/controllers/custom-fields.md#update-metadata) +* [List Metafields](../../doc/controllers/custom-fields.md#list-metafields) * [Delete Metafield](../../doc/controllers/custom-fields.md#delete-metafield) -* [Create Metadata](../../doc/controllers/custom-fields.md#create-metadata) * [List Metadata](../../doc/controllers/custom-fields.md#list-metadata) -* [Update Metadata](../../doc/controllers/custom-fields.md#update-metadata) +* [Create Metafields](../../doc/controllers/custom-fields.md#create-metafields) +* [Create Metadata](../../doc/controllers/custom-fields.md#create-metadata) * [Delete Metadata](../../doc/controllers/custom-fields.md#delete-metadata) * [List Metadata for Resource Type](../../doc/controllers/custom-fields.md#list-metadata-for-resource-type) -# Create Metafields - -## Custom Fields: Metafield Intro +# Update Metafield -**Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. +Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. -+ **Metafield is the custom field** -+ **Metadata is the data populating the custom field.** +```csharp +UpdateMetafieldAsync( + Models.ResourceType resourceType, + Models.UpdateMetafieldsRequest body = null) +``` -Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields) +## Parameters -Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `body` | [`UpdateMetafieldsRequest`](../../doc/models/update-metafields-request.md) | Body, Optional | - | -## Create Metafields +## Response Type -Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. +[`Task>`](../../doc/models/metafield.md) -Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. +## Example Usage -### Metafields "On-the-Fly" +```csharp +ResourceType resourceType = ResourceType.Subscriptions; +try +{ + List result = await customFieldsController.UpdateMetafieldAsync(resourceType); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. -### Metafield Scope Warning +# Update Metadata -If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. +This method allows you to update the existing metadata associated with a subscription or customer. ```csharp -CreateMetafieldsAsync( +UpdateMetadataAsync( Models.ResourceType resourceType, - Models.CreateMetafieldsRequest body = null) + string resourceId, + Models.UpdateMetadataRequest body = null) ``` ## Parameters @@ -59,42 +74,23 @@ CreateMetafieldsAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `body` | [`CreateMetafieldsRequest`](../../doc/models/create-metafields-request.md) | Body, Optional | - | +| `resourceId` | `string` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | +| `body` | [`UpdateMetadataRequest`](../../doc/models/update-metadata-request.md) | Body, Optional | - | ## Response Type -[`Task>`](../../doc/models/metafield.md) +[`Task>`](../../doc/models/metadata.md) ## Example Usage ```csharp ResourceType resourceType = ResourceType.Subscriptions; -CreateMetafieldsRequest body = new CreateMetafieldsRequest -{ - Metafields = CreateMetafieldsRequestMetafields.FromCreateMetafield( - new CreateMetafield - { - Name = "Dropdown field", - Scope = new MetafieldScope - { - PublicShow = IncludeOption.Include, - PublicEdit = IncludeOption.Include, - }, - InputType = MetafieldInput.Dropdown, - MEnum = new List - { - "option 1", - "option 2", - }, - } - ), -}; - +string resourceId = "resource_id4"; try { - List result = await customFieldsController.CreateMetafieldsAsync( + List result = await customFieldsController.UpdateMetadataAsync( resourceType, - body + resourceId ); } catch (ApiException e) @@ -104,45 +100,6 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -[ - { - "name": "Color", - "scope": { - "hosted": [], - "csv": "0", - "statements": "0", - "invoices": "0", - "portal": "0" - }, - "data_count": 0, - "input_type": "text", - "enum": null - }, - { - "name": "Brand", - "scope": { - "hosted": [], - "csv": "0", - "statements": "0", - "invoices": "0", - "portal": "0" - }, - "data_count": 0, - "input_type": "text", - "enum": null - } -] -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - # List Metafields @@ -217,16 +174,16 @@ catch (ApiException e) ``` -# Update Metafield +# Delete Metafield -Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. +Use the following method to delete a metafield. This will remove the metafield from the Site. + +Additionally, this will remove the metafield and associated metadata with all Subscriptions on the Site. ```csharp -UpdateMetafieldAsync( +DeleteMetafieldAsync( Models.ResourceType resourceType, - string name, - string currentName = null, - Models.UpdateMetafieldsRequest body = null) + string name = null) ``` ## Parameters @@ -234,25 +191,19 @@ UpdateMetafieldAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `name` | `string` | Query, Required | Name of the custom field. | -| `currentName` | `string` | Query, Optional | This only applies when you are updating an existing record and you wish to rename the field. Note you must supply name and current_name to rename the field | -| `body` | [`UpdateMetafieldsRequest`](../../doc/models/update-metafields-request.md) | Body, Optional | - | +| `name` | `string` | Query, Optional | The name of the metafield to be deleted | ## Response Type -[`Task>`](../../doc/models/metafield.md) +`Task` ## Example Usage ```csharp ResourceType resourceType = ResourceType.Subscriptions; -string name = "name0"; try { - List result = await customFieldsController.UpdateMetafieldAsync( - resourceType, - name - ); + await customFieldsController.DeleteMetafieldAsync(resourceType); } catch (ApiException e) { @@ -261,17 +212,24 @@ catch (ApiException e) } ``` +## Errors -# Delete Metafield +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | -Use the following method to delete a metafield. This will remove the metafield from the Site. -Additionally, this will remove the metafield and associated metadata with all Subscriptions on the Site. +# List Metadata + +This request will list all of the metadata belonging to a particular resource (ie. subscription, customer) that is specified. + +## Metadata Data + +This endpoint will also display the current stats of your metadata to use as a tool for pagination. ```csharp -DeleteMetafieldAsync( - Models.ResourceType resourceType, - string name = null) +ListMetadataAsync( + Models.ListMetadataInput input) ``` ## Parameters @@ -279,19 +237,28 @@ DeleteMetafieldAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `name` | `string` | Query, Optional | The name of the metafield to be deleted | +| `resourceId` | `string` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | ## Response Type -`Task` +[`Task`](../../doc/models/paginated-metadata.md) ## Example Usage ```csharp -ResourceType resourceType = ResourceType.Subscriptions; +ListMetadataInput listMetadataInput = new ListMetadataInput +{ + ResourceType = ResourceType.Subscriptions, + ResourceId = "resource_id4", + Page = 2, + PerPage = 50, +}; + try { - await customFieldsController.DeleteMetafieldAsync(resourceType); + PaginatedMetadata result = await customFieldsController.ListMetadataAsync(listMetadataInput); } catch (ApiException e) { @@ -300,43 +267,38 @@ catch (ApiException e) } ``` -## Errors -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | - - -# Create Metadata +# Create Metafields -## Custom Fields: Metadata Intro +## Custom Fields: Metafield Intro **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. + **Metafield is the custom field** + **Metadata is the data populating the custom field.** -Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields) +Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields) -Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. +Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. -## Metadata limits +## Create Metafields -Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. +Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. -## Create Metadata +Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. -This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. +### Metafields "On-the-Fly" -### Subscription or Customer Resource +It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. -Please pay special attention to the resource you use when creating metadata. +### Metafield Scope Warning + +If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. ```csharp -CreateMetadataAsync( +CreateMetafieldsAsync( Models.ResourceType resourceType, - string resourceId, - Models.CreateMetadataRequest body = null) + Models.CreateMetafieldsRequest body = null) ``` ## Parameters @@ -344,40 +306,41 @@ CreateMetadataAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `resourceId` | `string` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `body` | [`CreateMetadataRequest`](../../doc/models/create-metadata-request.md) | Body, Optional | - | +| `body` | [`CreateMetafieldsRequest`](../../doc/models/create-metafields-request.md) | Body, Optional | - | ## Response Type -[`Task>`](../../doc/models/metadata.md) +[`Task>`](../../doc/models/metafield.md) ## Example Usage ```csharp ResourceType resourceType = ResourceType.Subscriptions; -string resourceId = "resource_id4"; -CreateMetadataRequest body = new CreateMetadataRequest +CreateMetafieldsRequest body = new CreateMetafieldsRequest { - Metadata = new List - { - new CreateMetadata - { - Name = "Color", - MValue = "Blue", - }, - new CreateMetadata + Metafields = CreateMetafieldsRequestMetafields.FromCreateMetafield( + new CreateMetafield { - Name = "Something", - MValue = "Useful", - }, - }, + Name = "Dropdown field", + Scope = new MetafieldScope + { + PublicShow = IncludeOption.Include, + PublicEdit = IncludeOption.Include, + }, + InputType = MetafieldInput.Dropdown, + MEnum = new List + { + "option 1", + "option 2", + }, + } + ), }; try { - List result = await customFieldsController.CreateMetadataAsync( + List result = await customFieldsController.CreateMetafieldsAsync( resourceType, - resourceId, body ); } @@ -388,6 +351,39 @@ catch (ApiException e) } ``` +## Example Response *(as JSON)* + +```json +[ + { + "name": "Color", + "scope": { + "hosted": [], + "csv": "0", + "statements": "0", + "invoices": "0", + "portal": "0" + }, + "data_count": 0, + "input_type": "text", + "enum": null + }, + { + "name": "Brand", + "scope": { + "hosted": [], + "csv": "0", + "statements": "0", + "invoices": "0", + "portal": "0" + }, + "data_count": 0, + "input_type": "text", + "enum": null + } +] +``` + ## Errors | HTTP Status Code | Error Description | Exception Class | @@ -395,64 +391,36 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | -# List Metadata - -This request will list all of the metadata belonging to a particular resource (ie. subscription, customer) that is specified. - -## Metadata Data - -This endpoint will also display the current stats of your metadata to use as a tool for pagination. +# Create Metadata -```csharp -ListMetadataAsync( - Models.ListMetadataInput input) -``` +## Custom Fields: Metadata Intro -## Parameters +**Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `resourceId` | `string` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | ++ **Metafield is the custom field** ++ **Metadata is the data populating the custom field.** -## Response Type +Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields) -[`Task`](../../doc/models/paginated-metadata.md) +Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. -## Example Usage +## Metadata limits -```csharp -ListMetadataInput listMetadataInput = new ListMetadataInput -{ - ResourceType = ResourceType.Subscriptions, - ResourceId = "resource_id4", - Page = 2, - PerPage = 50, -}; +Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. -try -{ - PaginatedMetadata result = await customFieldsController.ListMetadataAsync(listMetadataInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` +## Create Metadata +This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. -# Update Metadata +### Subscription or Customer Resource -This method allows you to update the existing metadata associated with a subscription or customer. +Please pay special attention to the resource you use when creating metadata. ```csharp -UpdateMetadataAsync( +CreateMetadataAsync( Models.ResourceType resourceType, string resourceId, - Models.UpdateMetadataRequest body = null) + Models.CreateMetadataRequest body = null) ``` ## Parameters @@ -461,7 +429,7 @@ UpdateMetadataAsync( | --- | --- | --- | --- | | `resourceType` | [`ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | | `resourceId` | `string` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `body` | [`UpdateMetadataRequest`](../../doc/models/update-metadata-request.md) | Body, Optional | - | +| `body` | [`CreateMetadataRequest`](../../doc/models/create-metadata-request.md) | Body, Optional | - | ## Response Type @@ -472,11 +440,29 @@ UpdateMetadataAsync( ```csharp ResourceType resourceType = ResourceType.Subscriptions; string resourceId = "resource_id4"; +CreateMetadataRequest body = new CreateMetadataRequest +{ + Metadata = new List + { + new CreateMetadata + { + Name = "Color", + MValue = "Blue", + }, + new CreateMetadata + { + Name = "Something", + MValue = "Useful", + }, + }, +}; + try { - List result = await customFieldsController.UpdateMetadataAsync( + List result = await customFieldsController.CreateMetadataAsync( resourceType, - resourceId + resourceId, + body ); } catch (ApiException e) @@ -486,6 +472,12 @@ catch (ApiException e) } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + # Delete Metadata diff --git a/doc/controllers/customers.md b/doc/controllers/customers.md index bb741ef..87d9fea 100644 --- a/doc/controllers/customers.md +++ b/doc/controllers/customers.md @@ -11,11 +11,11 @@ CustomersController customersController = client.CustomersController; ## Methods * [Create Customer](../../doc/controllers/customers.md#create-customer) -* [List Customers](../../doc/controllers/customers.md#list-customers) -* [Read Customer](../../doc/controllers/customers.md#read-customer) * [Update Customer](../../doc/controllers/customers.md#update-customer) -* [Delete Customer](../../doc/controllers/customers.md#delete-customer) * [Read Customer by Reference](../../doc/controllers/customers.md#read-customer-by-reference) +* [Read Customer](../../doc/controllers/customers.md#read-customer) +* [Delete Customer](../../doc/controllers/customers.md#delete-customer) +* [List Customers](../../doc/controllers/customers.md#list-customers) * [List Customer Subscriptions](../../doc/controllers/customers.md#list-customer-subscriptions) @@ -138,60 +138,47 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | -# List Customers - -This request will by default list all customers associated with your Site. - -## Find Customer - -Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. - -Common use cases are: - -+ Search by an email -+ Search by a Chargify ID -+ Search by an organization -+ Search by a reference value from your application -+ Search by a first or last name +# Update Customer -To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). +This method allows to update the Customer. ```csharp -ListCustomersAsync( - Models.ListCustomersInput input) +UpdateCustomerAsync( + int id, + Models.UpdateCustomerRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Direction to sort customers by time of creation | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 50. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | -| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `q` | `string` | Query, Optional | A search query by which to filter customers (can be an email, an ID, a reference, organization) | +| `id` | `int` | Template, Required | The Chargify id of the customer | +| `body` | [`UpdateCustomerRequest`](../../doc/models/update-customer-request.md) | Body, Optional | - | ## Response Type -[`Task>`](../../doc/models/customer-response.md) +[`Task`](../../doc/models/customer-response.md) ## Example Usage ```csharp -ListCustomersInput listCustomersInput = new ListCustomersInput +int id = 112; +UpdateCustomerRequest body = new UpdateCustomerRequest { - Page = 2, - PerPage = 30, - DateField = BasicDateField.UpdatedAt, + Customer = new UpdateCustomer + { + FirstName = "Martha", + LastName = "Washington", + Email = "martha.washington@example.com", + }, }; try { - List result = await customersController.ListCustomersAsync(listCustomersInput); + CustomerResponse result = await customersController.UpdateCustomerAsync( + id, + body + ); } catch (ApiException e) { @@ -203,102 +190,56 @@ catch (ApiException e) ## Example Response *(as JSON)* ```json -[ - { - "customer": { - "first_name": "Kayla", - "last_name": "Test", - "email": "kayla@example.com", - "cc_emails": "john@example.com, sue@example.com", - "organization": "", - "reference": null, - "id": 14126091, - "created_at": "2016-10-04T15:22:27-04:00", - "updated_at": "2016-10-04T15:22:30-04:00", - "address": "", - "address_2": "", - "city": "", - "state": "", - "zip": "", - "country": "", - "phone": "", - "verified": null, - "portal_customer_created_at": "2016-10-04T15:22:29-04:00", - "portal_invite_last_sent_at": "2016-10-04T15:22:30-04:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false - } - }, - { - "customer": { - "first_name": "Nick ", - "last_name": "Test", - "email": "nick@example.com", - "cc_emails": "john@example.com, sue@example.com", - "organization": "", - "reference": null, - "id": 14254093, - "created_at": "2016-10-13T16:52:51-04:00", - "updated_at": "2016-10-13T16:52:54-04:00", - "address": "", - "address_2": "", - "city": "", - "state": "", - "zip": "", - "country": "", - "phone": "", - "verified": null, - "portal_customer_created_at": "2016-10-13T16:52:54-04:00", - "portal_invite_last_sent_at": "2016-10-13T16:52:54-04:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "parent_id": 123 - } - }, - { - "customer": { - "first_name": "Don", - "last_name": "Test", - "email": "don@example.com", - "cc_emails": "john@example.com, sue@example.com", - "organization": "", - "reference": null, - "id": 14332342, - "created_at": "2016-10-19T10:49:13-04:00", - "updated_at": "2016-10-19T10:49:19-04:00", - "address": "1737 15th St", - "address_2": "", - "city": "Boulder", - "state": "CO", - "zip": "80302", - "country": "US", - "phone": "", - "verified": null, - "portal_customer_created_at": "2016-10-19T10:49:19-04:00", - "portal_invite_last_sent_at": "2016-10-19T10:49:19-04:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "parent_id": null - } +{ + "customer": { + "first_name": "Martha", + "last_name": "Washington", + "email": "martha.washington@example.com", + "cc_emails": "george.washington@example.com", + "organization": null, + "reference": null, + "id": 14967442, + "created_at": "2016-12-05T10:33:07-05:00", + "updated_at": "2016-12-05T10:38:00-05:00", + "address": null, + "address_2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "phone": null, + "verified": false, + "portal_customer_created_at": null, + "portal_invite_last_sent_at": null, + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "vat_number": "012345678" } -] +} ``` +## Errors -# Read Customer +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | -This method allows to retrieve the Customer properties by Chargify-generated Customer ID. + +# Read Customer by Reference + +Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. ```csharp -ReadCustomerAsync( - int id) +ReadCustomerByReferenceAsync( + string reference) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `id` | `int` | Template, Required | The Chargify id of the customer | +| `reference` | `string` | Query, Required | Customer reference | ## Response Type @@ -307,10 +248,10 @@ ReadCustomerAsync( ## Example Usage ```csharp -int id = 112; +string reference = "reference4"; try { - CustomerResponse result = await customersController.ReadCustomerAsync(id); + CustomerResponse result = await customersController.ReadCustomerByReferenceAsync(reference); } catch (ApiException e) { @@ -320,14 +261,13 @@ catch (ApiException e) ``` -# Update Customer +# Read Customer -This method allows to update the Customer. +This method allows to retrieve the Customer properties by Chargify-generated Customer ID. ```csharp -UpdateCustomerAsync( - int id, - Models.UpdateCustomerRequest body = null) +ReadCustomerAsync( + int id) ``` ## Parameters @@ -335,7 +275,6 @@ UpdateCustomerAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `id` | `int` | Template, Required | The Chargify id of the customer | -| `body` | [`UpdateCustomerRequest`](../../doc/models/update-customer-request.md) | Body, Optional | - | ## Response Type @@ -345,22 +284,9 @@ UpdateCustomerAsync( ```csharp int id = 112; -UpdateCustomerRequest body = new UpdateCustomerRequest -{ - Customer = new UpdateCustomer - { - FirstName = "Martha", - LastName = "Washington", - Email = "martha.washington@example.com", - }, -}; - try { - CustomerResponse result = await customersController.UpdateCustomerAsync( - id, - body - ); + CustomerResponse result = await customersController.ReadCustomerAsync(id); } catch (ApiException e) { @@ -369,44 +295,6 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -{ - "customer": { - "first_name": "Martha", - "last_name": "Washington", - "email": "martha.washington@example.com", - "cc_emails": "george.washington@example.com", - "organization": null, - "reference": null, - "id": 14967442, - "created_at": "2016-12-05T10:33:07-05:00", - "updated_at": "2016-12-05T10:38:00-05:00", - "address": null, - "address_2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "phone": null, - "verified": false, - "portal_customer_created_at": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "vat_number": "012345678" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | - # Delete Customer @@ -443,32 +331,60 @@ catch (ApiException e) ``` -# Read Customer by Reference +# List Customers -Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. +This request will by default list all customers associated with your Site. + +## Find Customer + +Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. + +Common use cases are: + ++ Search by an email ++ Search by a Chargify ID ++ Search by an organization ++ Search by a reference value from your application ++ Search by a first or last name + +To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). ```csharp -ReadCustomerByReferenceAsync( - string reference) +ListCustomersAsync( + Models.ListCustomersInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `reference` | `string` | Query, Required | Customer reference | +| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Direction to sort customers by time of creation | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 50. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | +| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `q` | `string` | Query, Optional | A search query by which to filter customers (can be an email, an ID, a reference, organization) | ## Response Type -[`Task`](../../doc/models/customer-response.md) +[`Task>`](../../doc/models/customer-response.md) ## Example Usage ```csharp -string reference = "reference4"; +ListCustomersInput listCustomersInput = new ListCustomersInput +{ + Page = 2, + PerPage = 30, + DateField = BasicDateField.UpdatedAt, +}; + try { - CustomerResponse result = await customersController.ReadCustomerByReferenceAsync(reference); + List result = await customersController.ListCustomersAsync(listCustomersInput); } catch (ApiException e) { @@ -477,6 +393,90 @@ catch (ApiException e) } ``` +## Example Response *(as JSON)* + +```json +[ + { + "customer": { + "first_name": "Kayla", + "last_name": "Test", + "email": "kayla@example.com", + "cc_emails": "john@example.com, sue@example.com", + "organization": "", + "reference": null, + "id": 14126091, + "created_at": "2016-10-04T15:22:27-04:00", + "updated_at": "2016-10-04T15:22:30-04:00", + "address": "", + "address_2": "", + "city": "", + "state": "", + "zip": "", + "country": "", + "phone": "", + "verified": null, + "portal_customer_created_at": "2016-10-04T15:22:29-04:00", + "portal_invite_last_sent_at": "2016-10-04T15:22:30-04:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false + } + }, + { + "customer": { + "first_name": "Nick ", + "last_name": "Test", + "email": "nick@example.com", + "cc_emails": "john@example.com, sue@example.com", + "organization": "", + "reference": null, + "id": 14254093, + "created_at": "2016-10-13T16:52:51-04:00", + "updated_at": "2016-10-13T16:52:54-04:00", + "address": "", + "address_2": "", + "city": "", + "state": "", + "zip": "", + "country": "", + "phone": "", + "verified": null, + "portal_customer_created_at": "2016-10-13T16:52:54-04:00", + "portal_invite_last_sent_at": "2016-10-13T16:52:54-04:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "parent_id": 123 + } + }, + { + "customer": { + "first_name": "Don", + "last_name": "Test", + "email": "don@example.com", + "cc_emails": "john@example.com, sue@example.com", + "organization": "", + "reference": null, + "id": 14332342, + "created_at": "2016-10-19T10:49:13-04:00", + "updated_at": "2016-10-19T10:49:19-04:00", + "address": "1737 15th St", + "address_2": "", + "city": "Boulder", + "state": "CO", + "zip": "80302", + "country": "US", + "phone": "", + "verified": null, + "portal_customer_created_at": "2016-10-19T10:49:19-04:00", + "portal_invite_last_sent_at": "2016-10-19T10:49:19-04:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "parent_id": null + } + } +] +``` + # List Customer Subscriptions diff --git a/doc/controllers/events-based-billing-segments.md b/doc/controllers/events-based-billing-segments.md index fa83cad..9ed4355 100644 --- a/doc/controllers/events-based-billing-segments.md +++ b/doc/controllers/events-based-billing-segments.md @@ -10,25 +10,25 @@ EventsBasedBillingSegmentsController eventsBasedBillingSegmentsController = clie ## Methods -* [Create Segment](../../doc/controllers/events-based-billing-segments.md#create-segment) * [List Segments for Price Point](../../doc/controllers/events-based-billing-segments.md#list-segments-for-price-point) -* [Update Segment](../../doc/controllers/events-based-billing-segments.md#update-segment) * [Delete Segment](../../doc/controllers/events-based-billing-segments.md#delete-segment) -* [Create Segments](../../doc/controllers/events-based-billing-segments.md#create-segments) +* [Update Segment](../../doc/controllers/events-based-billing-segments.md#update-segment) * [Update Segments](../../doc/controllers/events-based-billing-segments.md#update-segments) +* [Create Segment](../../doc/controllers/events-based-billing-segments.md#create-segment) +* [Create Segments](../../doc/controllers/events-based-billing-segments.md#create-segments) -# Create Segment +# List Segments for Price Point -This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. +This endpoint allows you to fetch Segments created for a given Price Point. They will be returned in the order of creation. + +You can pass `page` and `per_page` parameters in order to access all of the segments. By default it will return `30` records. You can set `per_page` to `200` at most. You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. ```csharp -CreateSegmentAsync( - string componentId, - string pricePointId, - Models.CreateSegmentRequest body = null) +ListSegmentsForPricePointAsync( + Models.ListSegmentsForPricePointInput input) ``` ## Parameters @@ -37,48 +37,31 @@ CreateSegmentAsync( | --- | --- | --- | --- | | `componentId` | `string` | Template, Required | ID or Handle for the Component | | `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `body` | [`CreateSegmentRequest`](../../doc/models/create-segment-request.md) | Body, Optional | - | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterSegmentProperty1Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_1` on attached Metric. If empty string is passed, this filter would be rejected. Use in query `filter[segment_property_1_value]=EU`. | +| `filterSegmentProperty2Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_2` on attached Metric. If empty string is passed, this filter would be rejected. | +| `filterSegmentProperty3Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_3` on attached Metric. If empty string is passed, this filter would be rejected. | +| `filterSegmentProperty4Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_4` on attached Metric. If empty string is passed, this filter would be rejected. | ## Response Type -[`Task`](../../doc/models/segment-response.md) +[`Task`](../../doc/models/list-segments-response.md) ## Example Usage ```csharp -string componentId = "component_id8"; -string pricePointId = "price_point_id8"; -CreateSegmentRequest body = new CreateSegmentRequest +ListSegmentsForPricePointInput listSegmentsForPricePointInput = new ListSegmentsForPricePointInput { - Segment = new CreateSegment - { - PricingScheme = PricingScheme.Volume, - SegmentProperty1Value = CreateSegmentSegmentProperty1Value.FromString("France"), - SegmentProperty2Value = CreateSegmentSegmentProperty2Value.FromString("Spain"), - Prices = new List - { - new CreateOrUpdateSegmentPrice - { - UnitPrice = CreateOrUpdateSegmentPriceUnitPrice.FromPrecision(0.19), - StartingQuantity = 1, - EndingQuantity = 10000, - }, - new CreateOrUpdateSegmentPrice - { - UnitPrice = CreateOrUpdateSegmentPriceUnitPrice.FromPrecision(0.09), - StartingQuantity = 10001, - }, - }, - }, -}; + ComponentId = "component_id8", + PricePointId = "price_point_id8", + Page = 2, + PerPage = 50, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; try { - SegmentResponse result = await eventsBasedBillingSegmentsController.CreateSegmentAsync( - componentId, - pricePointId, - body - ); + ListSegmentsResponse result = await eventsBasedBillingSegmentsController.ListSegmentsForPricePointAsync(listSegmentsForPricePointInput); } catch (ApiException e) { @@ -92,53 +75,47 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | - +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingListSegmentsErrorsException`](../../doc/models/event-based-billing-list-segments-errors-exception.md) | -# List Segments for Price Point -This endpoint allows you to fetch Segments created for a given Price Point. They will be returned in the order of creation. +# Delete Segment -You can pass `page` and `per_page` parameters in order to access all of the segments. By default it will return `30` records. You can set `per_page` to `200` at most. +This endpoint allows you to delete a Segment with specified ID. You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. ```csharp -ListSegmentsForPricePointAsync( - Models.ListSegmentsForPricePointInput input) +DeleteSegmentAsync( + string componentId, + string pricePointId, + double id) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle for the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterSegmentProperty1Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_1` on attached Metric. If empty string is passed, this filter would be rejected. Use in query `filter[segment_property_1_value]=EU`. | -| `filterSegmentProperty2Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_2` on attached Metric. If empty string is passed, this filter would be rejected. | -| `filterSegmentProperty3Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_3` on attached Metric. If empty string is passed, this filter would be rejected. | -| `filterSegmentProperty4Value` | `string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_4` on attached Metric. If empty string is passed, this filter would be rejected. | +| `componentId` | `string` | Template, Required | ID or Handle of the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle of the Price Point belonging to the Component | +| `id` | `double` | Template, Required | The ID of the Segment | ## Response Type -[`Task`](../../doc/models/list-segments-response.md) +`Task` ## Example Usage ```csharp -ListSegmentsForPricePointInput listSegmentsForPricePointInput = new ListSegmentsForPricePointInput -{ - ComponentId = "component_id8", - PricePointId = "price_point_id8", - Page = 2, - PerPage = 50, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; - +string componentId = "component_id8"; +string pricePointId = "price_point_id8"; +double id = 60; try { - ListSegmentsResponse result = await eventsBasedBillingSegmentsController.ListSegmentsForPricePointAsync(listSegmentsForPricePointInput); + await eventsBasedBillingSegmentsController.DeleteSegmentAsync( + componentId, + pricePointId, + id + ); } catch (ApiException e) { @@ -152,7 +129,7 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingListSegmentsErrorsException`](../../doc/models/event-based-billing-list-segments-errors-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | `ApiException` | # Update Segment @@ -211,43 +188,43 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | -# Delete Segment +# Update Segments -This endpoint allows you to delete a Segment with specified ID. +This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. + +If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. ```csharp -DeleteSegmentAsync( +UpdateSegmentsAsync( string componentId, string pricePointId, - double id) + Models.BulkUpdateSegments body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle of the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle of the Price Point belonging to the Component | -| `id` | `double` | Template, Required | The ID of the Segment | +| `componentId` | `string` | Template, Required | ID or Handle for the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | +| `body` | [`BulkUpdateSegments`](../../doc/models/bulk-update-segments.md) | Body, Optional | - | ## Response Type -`Task` +[`Task`](../../doc/models/list-segments-response.md) ## Example Usage ```csharp string componentId = "component_id8"; string pricePointId = "price_point_id8"; -double id = 60; try { - await eventsBasedBillingSegmentsController.DeleteSegmentAsync( + ListSegmentsResponse result = await eventsBasedBillingSegmentsController.UpdateSegmentsAsync( componentId, - pricePointId, - id + pricePointId ); } catch (ApiException e) @@ -262,22 +239,20 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | `ApiException` | - +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentException`](../../doc/models/event-based-billing-segment-exception.md) | -# Create Segments -This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. +# Create Segment -If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. +This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. ```csharp -CreateSegmentsAsync( +CreateSegmentAsync( string componentId, string pricePointId, - Models.BulkCreateSegments body = null) + Models.CreateSegmentRequest body = null) ``` ## Parameters @@ -286,22 +261,47 @@ CreateSegmentsAsync( | --- | --- | --- | --- | | `componentId` | `string` | Template, Required | ID or Handle for the Component | | `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `body` | [`BulkCreateSegments`](../../doc/models/bulk-create-segments.md) | Body, Optional | - | +| `body` | [`CreateSegmentRequest`](../../doc/models/create-segment-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/list-segments-response.md) +[`Task`](../../doc/models/segment-response.md) ## Example Usage ```csharp string componentId = "component_id8"; string pricePointId = "price_point_id8"; +CreateSegmentRequest body = new CreateSegmentRequest +{ + Segment = new CreateSegment + { + PricingScheme = PricingScheme.Volume, + SegmentProperty1Value = CreateSegmentSegmentProperty1Value.FromString("France"), + SegmentProperty2Value = CreateSegmentSegmentProperty2Value.FromString("Spain"), + Prices = new List + { + new CreateOrUpdateSegmentPrice + { + UnitPrice = CreateOrUpdateSegmentPriceUnitPrice.FromPrecision(0.19), + StartingQuantity = 1, + EndingQuantity = 10000, + }, + new CreateOrUpdateSegmentPrice + { + UnitPrice = CreateOrUpdateSegmentPriceUnitPrice.FromPrecision(0.09), + StartingQuantity = 10001, + }, + }, + }, +}; + try { - ListSegmentsResponse result = await eventsBasedBillingSegmentsController.CreateSegmentsAsync( + SegmentResponse result = await eventsBasedBillingSegmentsController.CreateSegmentAsync( componentId, - pricePointId + pricePointId, + body ); } catch (ApiException e) @@ -316,22 +316,22 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentException`](../../doc/models/event-based-billing-segment-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | -# Update Segments +# Create Segments -This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. +This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. -If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. +If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. ```csharp -UpdateSegmentsAsync( +CreateSegmentsAsync( string componentId, string pricePointId, - Models.BulkUpdateSegments body = null) + Models.BulkCreateSegments body = null) ``` ## Parameters @@ -340,7 +340,7 @@ UpdateSegmentsAsync( | --- | --- | --- | --- | | `componentId` | `string` | Template, Required | ID or Handle for the Component | | `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `body` | [`BulkUpdateSegments`](../../doc/models/bulk-update-segments.md) | Body, Optional | - | +| `body` | [`BulkCreateSegments`](../../doc/models/bulk-create-segments.md) | Body, Optional | - | ## Response Type @@ -353,7 +353,7 @@ string componentId = "component_id8"; string pricePointId = "price_point_id8"; try { - ListSegmentsResponse result = await eventsBasedBillingSegmentsController.UpdateSegmentsAsync( + ListSegmentsResponse result = await eventsBasedBillingSegmentsController.CreateSegmentsAsync( componentId, pricePointId ); diff --git a/doc/controllers/insights.md b/doc/controllers/insights.md index 4804bd6..532ac74 100644 --- a/doc/controllers/insights.md +++ b/doc/controllers/insights.md @@ -11,9 +11,9 @@ InsightsController insightsController = client.InsightsController; ## Methods * [Read Site Stats](../../doc/controllers/insights.md#read-site-stats) +* [List Mrr Per Subscription](../../doc/controllers/insights.md#list-mrr-per-subscription) * [Read Mrr](../../doc/controllers/insights.md#read-mrr) * [Read Mrr Movements](../../doc/controllers/insights.md#read-mrr-movements) -* [List Mrr Per Subscription](../../doc/controllers/insights.md#list-mrr-per-subscription) # Read Site Stats @@ -70,6 +70,60 @@ catch (ApiException e) ``` +# List Mrr Per Subscription + +**This endpoint is deprecated.** + +This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. + +```csharp +ListMrrPerSubscriptionAsync( + Models.ListMrrPerSubscriptionInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `filterSubscriptionIds` | `List` | Query, Optional | Submit ids in order to limit results. Use in query: `filter[subscription_ids]=1,2,3`. | +| `atTime` | `string` | Query, Optional | Submit a timestamp in ISO8601 format to request MRR for a historic time. Use in query: `at_time=2022-01-10T10:00:00-05:00`. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`Direction?`](../../doc/models/direction.md) | Query, Optional | Controls the order in which results are returned. Records are ordered by subscription_id in ascending order by default. Use in query `direction=desc`. | + +## Response Type + +[`Task`](../../doc/models/subscription-mrr-response.md) + +## Example Usage + +```csharp +ListMrrPerSubscriptionInput listMrrPerSubscriptionInput = new ListMrrPerSubscriptionInput +{ +Liquid error: Value cannot be null. (Parameter 'key') AtTime = "at_time=2022-01-10T10:00:00-05:00", + Page = 2, + PerPage = 50, + Direction = Direction.Desc, +}; + +try +{ + SubscriptionMRRResponse result = await insightsController.ListMrrPerSubscriptionAsync(listMrrPerSubscriptionInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 400 | Bad Request | [`SubscriptionsMrrErrorResponseException`](../../doc/models/subscriptions-mrr-error-response-exception.md) | + + # Read Mrr **This endpoint is deprecated.** @@ -247,57 +301,3 @@ catch (ApiException e) } ``` - -# List Mrr Per Subscription - -**This endpoint is deprecated.** - -This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. - -```csharp -ListMrrPerSubscriptionAsync( - Models.ListMrrPerSubscriptionInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `filterSubscriptionIds` | `List` | Query, Optional | Submit ids in order to limit results. Use in query: `filter[subscription_ids]=1,2,3`. | -| `atTime` | `string` | Query, Optional | Submit a timestamp in ISO8601 format to request MRR for a historic time. Use in query: `at_time=2022-01-10T10:00:00-05:00`. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`Direction?`](../../doc/models/direction.md) | Query, Optional | Controls the order in which results are returned. Records are ordered by subscription_id in ascending order by default. Use in query `direction=desc`. | - -## Response Type - -[`Task`](../../doc/models/subscription-mrr-response.md) - -## Example Usage - -```csharp -ListMrrPerSubscriptionInput listMrrPerSubscriptionInput = new ListMrrPerSubscriptionInput -{ -Liquid error: Value cannot be null. (Parameter 'key') AtTime = "at_time=2022-01-10T10:00:00-05:00", - Page = 2, - PerPage = 50, - Direction = Direction.Desc, -}; - -try -{ - SubscriptionMRRResponse result = await insightsController.ListMrrPerSubscriptionAsync(listMrrPerSubscriptionInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`SubscriptionsMrrErrorResponseException`](../../doc/models/subscriptions-mrr-error-response-exception.md) | - diff --git a/doc/controllers/invoices.md b/doc/controllers/invoices.md index a14e237..c7e9fe2 100644 --- a/doc/controllers/invoices.md +++ b/doc/controllers/invoices.md @@ -11,22 +11,22 @@ InvoicesController invoicesController = client.InvoicesController; ## Methods * [Refund Invoice](../../doc/controllers/invoices.md#refund-invoice) +* [List Credit Notes](../../doc/controllers/invoices.md#list-credit-notes) +* [Record Payment for Invoice](../../doc/controllers/invoices.md#record-payment-for-invoice) +* [Record External Payment for Invoices](../../doc/controllers/invoices.md#record-external-payment-for-invoices) * [List Invoices](../../doc/controllers/invoices.md#list-invoices) * [Read Invoice](../../doc/controllers/invoices.md#read-invoice) * [List Invoice Events](../../doc/controllers/invoices.md#list-invoice-events) -* [Record Payment for Invoice](../../doc/controllers/invoices.md#record-payment-for-invoice) -* [Record External Payment for Invoices](../../doc/controllers/invoices.md#record-external-payment-for-invoices) -* [List Credit Notes](../../doc/controllers/invoices.md#list-credit-notes) -* [Read Credit Note](../../doc/controllers/invoices.md#read-credit-note) -* [Record Payment for Subscription](../../doc/controllers/invoices.md#record-payment-for-subscription) -* [Reopen Invoice](../../doc/controllers/invoices.md#reopen-invoice) * [Void Invoice](../../doc/controllers/invoices.md#void-invoice) +* [Preview Customer Information Changes](../../doc/controllers/invoices.md#preview-customer-information-changes) * [List Invoice Segments](../../doc/controllers/invoices.md#list-invoice-segments) * [Create Invoice](../../doc/controllers/invoices.md#create-invoice) -* [Send Invoice](../../doc/controllers/invoices.md#send-invoice) -* [Preview Customer Information Changes](../../doc/controllers/invoices.md#preview-customer-information-changes) -* [Update Customer Information](../../doc/controllers/invoices.md#update-customer-information) * [Issue Invoice](../../doc/controllers/invoices.md#issue-invoice) +* [Read Credit Note](../../doc/controllers/invoices.md#read-credit-note) +* [Record Payment for Subscription](../../doc/controllers/invoices.md#record-payment-for-subscription) +* [Reopen Invoice](../../doc/controllers/invoices.md#reopen-invoice) +* [Update Customer Information](../../doc/controllers/invoices.md#update-customer-information) +* [Send Invoice](../../doc/controllers/invoices.md#send-invoice) # Refund Invoice @@ -89,85 +89,58 @@ catch (ApiException e) } ``` +## Errors -# List Invoices +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. + +# List Credit Notes + +Credit Notes are like inverse invoices. They reduce the amount a customer owes. + +By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. ```csharp -ListInvoicesAsync( - Models.ListInvoicesInput input) +ListCreditNotesAsync( + Models.ListCreditNotesInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `status` | [`InvoiceStatus?`](../../doc/models/invoice-status.md) | Query, Optional | The current status of the invoice. Allowed Values: draft, open, paid, pending, voided | -| `subscriptionId` | `int?` | Query, Optional | The subscription's ID. | -| `subscriptionGroupUid` | `string` | Query, Optional | The UID of the subscription group you want to fetch consolidated invoices for. This will return a paginated list of consolidated invoices for the specified group. | +| `subscriptionId` | `int?` | Query, Optional | The subscription's Chargify id | | `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | | `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`Direction?`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned invoices. | | `lineItems` | `bool?` | Query, Optional | Include line items data | | `discounts` | `bool?` | Query, Optional | Include discounts data | | `taxes` | `bool?` | Query, Optional | Include taxes data | -| `credits` | `bool?` | Query, Optional | Include credits data | -| `payments` | `bool?` | Query, Optional | Include payments data | -| `customFields` | `bool?` | Query, Optional | Include custom fields data | | `refunds` | `bool?` | Query, Optional | Include refunds data | -| `dateField` | [`InvoiceDateField?`](../../doc/models/invoice-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=issue_date`. | -| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Allowed to be used only along with date_field set to created_at or updated_at. | -| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Allowed to be used only along with date_field set to created_at or updated_at. | -| `customerIds` | `List` | Query, Optional | Allows fetching invoices with matching customer id based on provided values. Use in query `customer_ids=1,2,3`. | -| `number` | `List` | Query, Optional | Allows fetching invoices with matching invoice number based on provided values. Use in query `number=1234,1235`. | -| `productIds` | `List` | Query, Optional | Allows fetching invoices with matching line items product ids based on provided values. Use in query `product_ids=23,34`. | -| `sort` | [`InvoiceSortField?`](../../doc/models/invoice-sort-field.md) | Query, Optional | Allows specification of the order of the returned list. Use in query `sort=total_amount`. | +| `applications` | `bool?` | Query, Optional | Include applications data | ## Response Type -[`Task`](../../doc/models/list-invoices-response.md) +[`Task`](../../doc/models/list-credit-notes-response.md) ## Example Usage ```csharp -ListInvoicesInput listInvoicesInput = new ListInvoicesInput +ListCreditNotesInput listCreditNotesInput = new ListCreditNotesInput { Page = 2, PerPage = 50, - Direction = Direction.Desc, LineItems = false, Discounts = false, Taxes = false, - Credits = false, - Payments = false, - CustomFields = false, Refunds = false, - DateField = InvoiceDateField.IssueDate, - CustomerIds = new List - { - 1, - 2, - 3, - }, - Number = new List - { - "1234", - "1235", - }, - ProductIds = new List - { - 23, - 34, - }, - Sort = InvoiceSortField.TotalAmount, + Applications = false, }; try { - ListInvoicesResponse result = await invoicesController.ListInvoicesAsync(listInvoicesInput); + ListCreditNotesResponse result = await invoicesController.ListCreditNotesAsync(listCreditNotesInput); } catch (ApiException e) { @@ -180,863 +153,279 @@ catch (ApiException e) ```json { - "invoices": [ + "credit_notes": [ { - "uid": "inv_8htcd29wcq3q6", - "site_id": 51288, - "customer_id": 20153415, - "subscription_id": 23277588, - "number": "125", - "sequence_number": 125, - "issue_date": "2018-09-20", - "due_date": "2018-09-20", - "paid_date": "2018-09-20", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", + "uid": "cn_8m9vbd5kkv7kr", + "site_id": 20, + "customer_id": 3, + "subscription_id": 2, + "number": "77", + "sequence_number": 78, + "issue_date": "2018-12-31", + "applied_date": "2018-12-31", + "status": "applied", "currency": "USD", - "consolidation_level": "parent", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": 23277588, - "product_name": "Trial and setup fee", - "product_family_name": "Billing Plans", + "memo": "Refund for overpayment", "seller": { - "name": "General Goods", + "name": "Acme, Inc.", "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", + "street": "122 E Houston St", + "line2": "Suite 105", + "city": "San Antonio", + "state": "TX", + "zip": "78205", "country": "US" }, - "phone": "555-555-1212" + "phone": "555-555-1234 x137" }, "customer": { - "chargify_id": 20153415, - "first_name": "Meg", - "last_name": "Example", - "organization": "", - "email": "meg@example.com" + "chargify_id": 3, + "first_name": "Marty", + "last_name": "McFly", + "organization": "Time Travellers, Inc.", + "email": "timetraveller1985@example.com", + "reference": null }, - "memo": "Please pay within 15 days.", "billing_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Boston", + "street": "200 Billing Rd.", + "line2": "Suite 100", + "city": "Needham", "state": "MA", - "zip": "90210", + "zip": "02494", "country": "US" }, "shipping_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "90210", + "street": "100 Shipping St.", + "line2": "Apt 200", + "city": "Pleasantville", + "state": "NC", + "zip": "12345", "country": "US" }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "100.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8htcd29wcq3q6?token=n9fr5fxff5v74c7h9srg3cwd" - }, - { - "uid": "inv_8hr3546xp4h8n", - "site_id": 51288, - "customer_id": 21687686, - "subscription_id": 22007644, - "number": "124", - "sequence_number": 124, - "issue_date": "2018-09-18", - "due_date": "2018-09-18", - "paid_date": null, - "status": "open", - "collection_method": "remittance", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Trial and setup fee", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" + "subtotal_amount": "208.69341779", + "discount_amount": "20.87125167", + "tax_amount": "12.67783387", + "total_amount": "200.5", + "applied_amount": "200.5", + "remaining_amount": "0.0", + "line_items": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "title": "IP Addresses: 5 to 10 addresses", + "description": "38.2% credit", + "quantity": "0.9855", + "unit_price": "2.0", + "subtotal_amount": "1.971004", + "discount_amount": "0.19862831", + "tax_amount": "0.11963536", + "total_amount": "1.89201105", + "tiered_unit_price": false, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165 }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 21687686, - "first_name": "Charlene", - "last_name": "Tester", - "organization": "", - "email": "food@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "", - "line2": "", - "city": "", - "state": "", - "zip": "", - "country": "" - }, - "shipping_address": { - "street": "", - "line2": "", - "city": "", - "state": "", - "zip": "", - "country": "" - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "100.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546xp4h8n?token=n9fr5fxff5v74c7h9srg3cwd" - }, - { - "uid": "inv_8hr3546wdwxkr", - "site_id": 51288, - "customer_id": 21687670, - "subscription_id": 22007627, - "number": "123", - "sequence_number": 123, - "issue_date": "2018-09-18", - "due_date": "2018-09-18", - "paid_date": "2018-09-18", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Trial End - Free", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 21687670, - "first_name": "Hello", - "last_name": "World", - "organization": "123", - "email": "example@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 Anywhere Street", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "shipping_address": { - "street": "", - "line2": "", - "city": "Boston", - "state": "AL", - "zip": "02120", - "country": "US" - }, - "subtotal_amount": "0.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "0.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546wdwxkr?token=n9fr5fxff5v74c7h9srg3cwd" - }, - { - "uid": "inv_8hjtk8bz56bbp", - "site_id": 51288, - "customer_id": 20137757, - "subscription_id": 20541100, - "number": "122", - "sequence_number": 122, - "issue_date": "2018-09-10", - "due_date": "2018-09-10", - "paid_date": "2018-09-10", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "$0 Product", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20137757, - "first_name": "Sasha", - "last_name": "Example", - "organization": "", - "email": "example@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Catville", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "shipping_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Catville", - "state": "AL", - "zip": "90210", - "country": "US" - }, - "subtotal_amount": "0.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "0.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hjtk8bz56bbp?token=fb6kpjz5rcr2vttyjs4rcv6y" - } - ] -} -``` - - -# Read Invoice - -Use this endpoint to retrieve the details for an invoice. - -```csharp -ReadInvoiceAsync( - string uid) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | - -## Response Type - -[`Task`](../../doc/models/invoice.md) - -## Example Usage - -```csharp -string uid = "uid0"; -try -{ - Invoice result = await invoicesController.ReadInvoiceAsync(uid); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "inv_8gd8tdhtd3hgr", - "site_id": 51288, - "customer_id": 20194505, - "subscription_id": 20597774, - "number": "117", - "sequence_number": 117, - "issue_date": "2018-07-26", - "due_date": "2018-07-26", - "paid_date": "2018-07-26", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Monthly Product", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20194505, - "first_name": "Joe", - "last_name": "Example", - "organization": null, - "email": "joe@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "shipping_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "100.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "line_items": [ - { - "uid": "li_8gd8tdhhgk55k", - "title": "Monthly Product", - "description": "Jul 26, 2018 - Aug 26, 2018", - "quantity": "1.0", - "unit_price": "100.0", - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "tiered_unit_price": false, - "period_range_start": "2018-07-26", - "period_range_end": "2018-08-26", - "product_id": 4607632, - "product_version": 1, - "component_id": null, - "price_point_id": null - } - ], - "discounts": [], - "taxes": [], - "credits": [], - "payments": [ - { - "transaction_time": "2018-07-26T15:22:02Z", - "memo": "Joe Example - Monthly Product: Renewal payment", - "original_amount": "100.0", - "applied_amount": "100.0", - "payment_method": { - "card_brand": "bogus", - "card_expiration": "10/2020", - "last_four": null, - "masked_card_number": "XXXX-XXXX-XXXX-1", - "type": "credit_card" - }, - "transaction_id": 253028955, - "prepayment": false - } - ], - "refunds": [], - "custom_fields": [], - "public_url": "https://www.chargifypay.com/invoice/inv_8jzrw74xq8kxr?token=fb6kpjz5rcr2vttyjs4rcv6y" -} -``` - - -# List Invoice Events - -This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. - -Exposed event types are: - -+ issue_invoice -+ apply_credit_note -+ apply_payment -+ refund_invoice -+ void_invoice -+ void_remainder -+ backport_invoice -+ change_invoice_status -+ change_invoice_collection_method -+ remove_payment -+ failed_payment -+ apply_debit_note -+ create_debit_note -+ change_chargeback_status - -Invoice events are returned in ascending order. - -If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. - -Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. - -```csharp -ListInvoiceEventsAsync( - Models.ListInvoiceEventsInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `sinceDate` | `string` | Query, Optional | The timestamp in a format `YYYY-MM-DD T HH:MM:SS Z`, or `YYYY-MM-DD`(in this case, it returns data from the beginning of the day). of the event from which you want to start the search. All the events before the `since_date` timestamp are not returned in the response. | -| `sinceId` | `int?` | Query, Optional | The ID of the event from which you want to start the search(ID is not included. e.g. if ID is set to 2, then all events with ID 3 and more will be shown) This parameter is not used if since_date is defined. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | -| `invoiceUid` | `string` | Query, Optional | Providing an invoice_uid allows for scoping of the invoice events to a single invoice or credit note. | -| `withChangeInvoiceStatus` | `string` | Query, Optional | Use this parameter if you want to fetch also invoice events with change_invoice_status type. | -| `eventTypes` | [`List`](../../doc/models/invoice-event-type.md) | Query, Optional | Filter results by event_type. Supply a comma separated list of event types (listed above). Use in query: `event_types=void_invoice,void_remainder`. | - -## Response Type - -[`Task`](../../doc/models/list-invoice-events-response.md) - -## Example Usage - -```csharp -ListInvoiceEventsInput listInvoiceEventsInput = new ListInvoiceEventsInput -{ - Page = 2, - PerPage = 100, -}; - -try -{ - ListInvoiceEventsResponse result = await invoicesController.ListInvoiceEventsAsync(listInvoiceEventsInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "events": [ - { - "id": 83, - "event_type": "apply_payment", - "event_data": { - "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", - "original_amount": "168.61", - "applied_amount": "168.61", - "transaction_time": "2018-08-01T16:00:00Z", - "payment_method": { - "card_brand": "visa", - "card_expiration": "12/2022", - "last_four": null, - "masked_card_number": "XXXX-XXXX-XXXX-1111", - "type": "credit_card" - }, - "consolidation_level": "none" - }, - "timestamp": "2018-08-01T16:00:00Z", - "invoice": { - "id": 614942008934401500, - "uid": "inv_8gk5bwkct3gqt", - "site_id": 20, - "customer_id": 6, - "subscription_id": 10, - "number": "25", - "sequence_number": 25, - "transaction_time": "2018-08-01T16:00:00Z", - "created_at": "2018-08-01T16:00:00Z", - "updated_at": "2018-08-01T16:00:00Z", - "issue_date": "2018-08-01", - "due_date": "2018-08-01", - "paid_date": "2018-08-01", - "status": "paid", - "role": "renewal", - "collection_method": "automatic", - "payment_instructions": "Please make checks payable to \"Acme, Inc.\"", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_id": null, - "subscription_group_id": null, - "parent_invoice_number": null, - "product_name": "Standard Plan", - "product_family_name": "Cloud Compute Servers", - "seller": { - "name": "Acme, Inc.", - "address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "phone": "555-555-1234 x137", - "logo_url": null - }, - "customer": { - "chargify_id": 6, - "first_name": "Non-Resumable", - "last_name": "Canceled On Purpose", - "organization": null, - "email": "evan4@example.com" - }, - "payer": { - "chargify_id": 6, - "first_name": "Non-Resumable", - "last_name": "Canceled On Purpose", - "organization": null, - "email": "evan4@example.com" - }, - "recipient_emails": [], - "net_terms": 0, - "memo": "Thanks for your business! If you have any questions, please contact your account manager.", - "billing_address": { - "street": "200 Billing Rd.", - "line2": "Suite 100", - "city": "Needham", - "state": "MA", - "zip": "02494", - "country": "US" - }, - "shipping_address": { - "street": "100 Shipping St.", - "line2": "Apt 200", - "city": "Pleasantville", - "state": "NC", - "zip": "12345", - "country": "US" + { + "uid": "cnli_8kjttvjcjx8b4", + "title": "Professional Plan", + "description": "38.2% credit", + "quantity": "0.382", + "unit_price": "299.0", + "subtotal_amount": "114.21127834", + "discount_amount": "11.42112783", + "tax_amount": "6.93833516", + "total_amount": "109.72848567", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": null, + "price_point_id": null }, - "line_items": [ - { - "uid": "li_8gk5bwkct3gqk", - "title": "Standard Plan", - "description": "08/01/2018 - 09/01/2018", - "quantity": "1.0", - "unit_price": "99.0", - "subtotal_amount": "99.0", - "discount_amount": "9.9", - "tax_amount": "6.01425", - "total_amount": "95.11425", - "tiered_unit_price": false, - "period_range_start": "2018-08-01", - "period_range_end": "2018-09-01", - "transaction_id": 120, - "product_id": 84, - "product_version": 1, - "component_id": null, - "price_point_id": null, - "hide": false - }, - { - "uid": "li_8gk5bwkct3gqm", - "title": "Small Instance (Hourly)", - "description": "07/22/2018 - 08/01/2018", - "quantity": "162.0", - "unit_price": "0.09567901", - "subtotal_amount": "15.5", - "discount_amount": "1.55", - "tax_amount": "0.941625", - "total_amount": "14.891625", - "tiered_unit_price": true, - "period_range_start": "2018-07-22", - "period_range_end": "2018-08-01", - "transaction_id": 121, - "product_id": 84, - "product_version": 1, - "component_id": 76, - "price_point_id": null, - "hide": false, - "component_cost_data": { - "rates": [ - { - "component_code_id": null, - "price_point_id": 160, - "product_id": 84, - "quantity": "162.0", - "amount": "15.5", - "pricing_scheme": "tiered", - "tiers": [ - { - "starting_quantity": 1, - "ending_quantity": 100, - "quantity": "100.0", - "unit_price": "0.0", - "amount": "0.0" - }, - { - "starting_quantity": 101, - "ending_quantity": null, - "quantity": "62.0", - "unit_price": "0.25", - "amount": "15.5" - } - ] - } - ] - } - }, - { - "uid": "li_8gk5bwkct3gqn", - "title": "Large Instance (Hourly)", - "description": "07/22/2018 - 08/01/2018", - "quantity": "194.0", - "unit_price": "0.24226804", - "subtotal_amount": "47.0", - "discount_amount": "4.7", - "tax_amount": "2.85525", - "total_amount": "45.15525", - "tiered_unit_price": true, - "period_range_start": "2018-07-22", - "period_range_end": "2018-08-01", - "transaction_id": 122, - "product_id": 84, - "product_version": 1, - "component_id": 77, - "price_point_id": null, - "hide": false, - "component_cost_data": { - "rates": [ - { - "component_code_id": null, - "price_point_id": 161, - "product_id": 84, - "quantity": "194.0", - "amount": "47.0", - "pricing_scheme": "tiered", - "tiers": [ - { - "starting_quantity": 1, - "ending_quantity": 100, - "quantity": "100.0", - "unit_price": "0.0", - "amount": "0.0" - }, - { - "starting_quantity": 101, - "ending_quantity": null, - "quantity": "94.0", - "unit_price": "0.5", - "amount": "47.0" - } - ] - } - ] - } - }, - { - "uid": "li_8gk5bwkct3gqp", - "title": "IP Addresses", - "description": "08/01/2018 - 09/01/2018", - "quantity": "7.0", - "unit_price": "2.0", - "subtotal_amount": "14.0", - "discount_amount": "1.4", - "tax_amount": "0.8505", - "total_amount": "13.4505", - "tiered_unit_price": false, - "period_range_start": "2018-08-01", - "period_range_end": "2018-09-01", - "transaction_id": 123, - "product_id": 84, - "product_version": 1, - "component_id": 79, - "price_point_id": 163, - "hide": false, - "component_cost_data": { - "rates": [ - { - "component_code_id": null, - "price_point_id": 163, - "product_id": 84, - "quantity": "7.0", - "amount": "14.0", - "pricing_scheme": "per_unit", - "tiers": [ - { - "starting_quantity": 1, - "ending_quantity": null, - "quantity": "7.0", - "unit_price": "2.0", - "amount": "14.0" - } - ] - } - ] + { + "uid": "cnli_8kjttvjknzhx7", + "title": "Small Instance (Hourly)", + "description": "38.2% credit", + "quantity": "74.8676", + "unit_price": "0.12244898", + "subtotal_amount": "9.16746047", + "discount_amount": "0.91674605", + "tax_amount": "0.55692322", + "total_amount": "8.80763764", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 78, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjnmh25w", + "title": "Large Instance (Hourly)", + "description": "38.2% credit", + "quantity": "183.3492", + "unit_price": "0.39583333", + "subtotal_amount": "72.57572871", + "discount_amount": "7.25757287", + "tax_amount": "4.40897552", + "total_amount": "69.72713136", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 79, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjqn86kc", + "title": "Email Messages", + "description": "38.2% credit", + "quantity": "10076.9489", + "unit_price": "0.00031045", + "subtotal_amount": "3.12839588", + "discount_amount": "0.31322157", + "tax_amount": "0.19002427", + "total_amount": "3.00519858", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 80, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "title": "IP Addresses", + "description": "38.2% credit", + "quantity": "3.8198", + "unit_price": "2.0", + "subtotal_amount": "7.63955039", + "discount_amount": "0.76395504", + "tax_amount": "0.46410269", + "total_amount": "7.33969804", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165 + } + ], + "discounts": [ + { + "uid": "cndli_8k5jvdzct4h9y", + "title": "Multi-service discount (10%)", + "code": "MULTI3", + "source_type": "Coupon", + "source_id": 40, + "discount_type": "percentage", + "percentage": "10.0", + "eligible_amount": "208.69341779", + "discount_amount": "20.87125167", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "eligible_amount": "1.971004", + "discount_amount": "0.19862831" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "eligible_amount": "114.21127834", + "discount_amount": "11.42112783" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "eligible_amount": "9.16746047", + "discount_amount": "0.91674605" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "eligible_amount": "72.57572871", + "discount_amount": "7.25757287" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "eligible_amount": "3.12839588", + "discount_amount": "0.31322157" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "eligible_amount": "7.63955039", + "discount_amount": "0.76395504" } - } - ], - "subtotal_amount": "175.5", - "discount_amount": "17.55", - "discounts": [ - { - "uid": "dli_8gk5bwkct3gqq", - "title": "Multi-service discount (10%)", - "description": null, - "code": "MULTI3", - "source_type": "Coupon", - "source_id": 40, - "discount_type": "percentage", - "percentage": "10.0", - "eligible_amount": "175.5", - "discount_amount": "17.55", - "transaction_id": 124, - "line_item_breakouts": [ - { - "uid": "li_8gk5bwkct3gqk", - "eligible_amount": "99.0", - "discount_amount": "9.9" - }, - { - "uid": "li_8gk5bwkct3gqm", - "eligible_amount": "15.5", - "discount_amount": "1.55" - }, - { - "uid": "li_8gk5bwkct3gqn", - "eligible_amount": "47.0", - "discount_amount": "4.7" - }, - { - "uid": "li_8gk5bwkct3gqp", - "eligible_amount": "14.0", - "discount_amount": "1.4" - } - ] - } - ], - "tax_amount": "10.66", - "taxes": [ - { - "uid": "tli_8gk5bwkct3gqr", - "title": "NC Sales Tax", - "description": null, - "source_type": "Tax", - "source_id": 1, - "percentage": "6.75", - "taxable_amount": "157.95", - "tax_amount": "10.66", - "transaction_id": 125, - "line_item_breakouts": [ - { - "uid": "li_8gk5bwkct3gqk", - "taxable_amount": "89.1", - "tax_amount": "6.01425" - }, - { - "uid": "li_8gk5bwkct3gqm", - "taxable_amount": "13.95", - "tax_amount": "0.941625" - }, - { - "uid": "li_8gk5bwkct3gqn", - "taxable_amount": "42.3", - "tax_amount": "2.85525" - }, - { - "uid": "li_8gk5bwkct3gqp", - "taxable_amount": "12.6", - "tax_amount": "0.8505" - } - ], - "tax_component_breakouts": [ - { - "tax_rule_id": 1, - "percentage": "6.75", - "country_code": "US", - "subdivision_code": "NC" - } - ] - } - ], - "credit_amount": "0.0", - "refund_amount": "0.0", - "total_amount": "168.61", - "paid_amount": "168.61", - "due_amount": "0.0", - "credits": [], - "refunds": [], - "payments": [ - { - "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", - "original_amount": "168.61", - "applied_amount": "168.61", - "transaction_time": "2018-08-01T16:00:00Z", - "payment_method": { - "card_brand": "visa", - "card_expiration": "12/2022", - "last_four": null, - "masked_card_number": "XXXX-XXXX-XXXX-1111", - "type": "credit_card" + ] + } + ], + "taxes": [ + { + "uid": "cntli_8k5jvdzct4h9z", + "title": "NC Sales Tax", + "source_type": "Tax", + "source_id": 1, + "percentage": "6.75", + "taxable_amount": "187.82216613", + "tax_amount": "12.67783387", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "taxable_amount": "1.77237569", + "tax_amount": "0.11963536" }, - "transaction_id": 126, - "prepayment": false - } - ], - "custom_fields": [], - "display_settings": { - "hide_zero_subtotal_lines": false, - "include_discounts_on_lines": false + { + "uid": "cnli_8kjttvjcjx8b4", + "taxable_amount": "102.7901505", + "tax_amount": "6.93833516" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "taxable_amount": "8.25071442", + "tax_amount": "0.55692322" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "taxable_amount": "65.31815584", + "tax_amount": "4.40897552" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "taxable_amount": "2.81517432", + "tax_amount": "0.19002427" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "taxable_amount": "6.87559535", + "tax_amount": "0.46410269" + } + ] + } + ], + "applications": [ + { + "uid": "cdt_8m9vbdbdwd28n", + "transaction_time": "2018-12-31T21:19:28Z", + "invoice_uid": "inv_8k5jvdzct4hb2", + "memo": "Refund for overpayment", + "applied_amount": "200.5" } - } + ], + "refunds": [ + { + "transaction_id": 329, + "payment_id": 39, + "memo": "Refund for overpayment", + "original_amount": "524.9", + "applied_amount": "200.5" + } + ] } - ], - "page": 48, - "per_page": 1, - "total_pages": 102 + ] } ``` @@ -1249,51 +638,84 @@ catch (ApiException e) | 422 | Unprocessable Entity | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# List Credit Notes - -Credit Notes are like inverse invoices. They reduce the amount a customer owes. +# List Invoices -By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. +By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. ```csharp -ListCreditNotesAsync( - Models.ListCreditNotesInput input) +ListInvoicesAsync( + Models.ListInvoicesInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int?` | Query, Optional | The subscription's Chargify id | +| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `status` | [`InvoiceStatus?`](../../doc/models/invoice-status.md) | Query, Optional | The current status of the invoice. Allowed Values: draft, open, paid, pending, voided | +| `subscriptionId` | `int?` | Query, Optional | The subscription's ID. | +| `subscriptionGroupUid` | `string` | Query, Optional | The UID of the subscription group you want to fetch consolidated invoices for. This will return a paginated list of consolidated invoices for the specified group. | | `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | | `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`Direction?`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned invoices. | | `lineItems` | `bool?` | Query, Optional | Include line items data | | `discounts` | `bool?` | Query, Optional | Include discounts data | | `taxes` | `bool?` | Query, Optional | Include taxes data | +| `credits` | `bool?` | Query, Optional | Include credits data | +| `payments` | `bool?` | Query, Optional | Include payments data | +| `customFields` | `bool?` | Query, Optional | Include custom fields data | | `refunds` | `bool?` | Query, Optional | Include refunds data | -| `applications` | `bool?` | Query, Optional | Include applications data | +| `dateField` | [`InvoiceDateField?`](../../doc/models/invoice-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=issue_date`. | +| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Allowed to be used only along with date_field set to created_at or updated_at. | +| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Allowed to be used only along with date_field set to created_at or updated_at. | +| `customerIds` | `List` | Query, Optional | Allows fetching invoices with matching customer id based on provided values. Use in query `customer_ids=1,2,3`. | +| `number` | `List` | Query, Optional | Allows fetching invoices with matching invoice number based on provided values. Use in query `number=1234,1235`. | +| `productIds` | `List` | Query, Optional | Allows fetching invoices with matching line items product ids based on provided values. Use in query `product_ids=23,34`. | +| `sort` | [`InvoiceSortField?`](../../doc/models/invoice-sort-field.md) | Query, Optional | Allows specification of the order of the returned list. Use in query `sort=total_amount`. | ## Response Type -[`Task`](../../doc/models/list-credit-notes-response.md) +[`Task`](../../doc/models/list-invoices-response.md) ## Example Usage ```csharp -ListCreditNotesInput listCreditNotesInput = new ListCreditNotesInput +ListInvoicesInput listInvoicesInput = new ListInvoicesInput { Page = 2, PerPage = 50, + Direction = Direction.Desc, LineItems = false, Discounts = false, Taxes = false, + Credits = false, + Payments = false, + CustomFields = false, Refunds = false, - Applications = false, + DateField = InvoiceDateField.IssueDate, + CustomerIds = new List + { + 1, + 2, + 3, + }, + Number = new List + { + "1234", + "1235", + }, + ProductIds = new List + { + 23, + 34, + }, + Sort = InvoiceSortField.TotalAmount, }; try { - ListCreditNotesResponse result = await invoicesController.ListCreditNotesAsync(listCreditNotesInput); + ListInvoicesResponse result = await invoicesController.ListInvoicesAsync(listInvoicesInput); } catch (ApiException e) { @@ -1306,289 +728,282 @@ catch (ApiException e) ```json { - "credit_notes": [ + "invoices": [ { - "uid": "cn_8m9vbd5kkv7kr", - "site_id": 20, - "customer_id": 3, - "subscription_id": 2, - "number": "77", - "sequence_number": 78, - "issue_date": "2018-12-31", - "applied_date": "2018-12-31", - "status": "applied", + "uid": "inv_8htcd29wcq3q6", + "site_id": 51288, + "customer_id": 20153415, + "subscription_id": 23277588, + "number": "125", + "sequence_number": 125, + "issue_date": "2018-09-20", + "due_date": "2018-09-20", + "paid_date": "2018-09-20", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", "currency": "USD", - "memo": "Refund for overpayment", + "consolidation_level": "parent", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": 23277588, + "product_name": "Trial and setup fee", + "product_family_name": "Billing Plans", "seller": { - "name": "Acme, Inc.", + "name": "General Goods", "address": { - "street": "122 E Houston St", - "line2": "Suite 105", - "city": "San Antonio", - "state": "TX", - "zip": "78205", + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", "country": "US" }, - "phone": "555-555-1234 x137" + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20153415, + "first_name": "Meg", + "last_name": "Example", + "organization": "", + "email": "meg@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "shipping_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "100.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8htcd29wcq3q6?token=n9fr5fxff5v74c7h9srg3cwd" + }, + { + "uid": "inv_8hr3546xp4h8n", + "site_id": 51288, + "customer_id": 21687686, + "subscription_id": 22007644, + "number": "124", + "sequence_number": 124, + "issue_date": "2018-09-18", + "due_date": "2018-09-18", + "paid_date": null, + "status": "open", + "collection_method": "remittance", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Trial and setup fee", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 21687686, + "first_name": "Charlene", + "last_name": "Tester", + "organization": "", + "email": "food@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "", + "line2": "", + "city": "", + "state": "", + "zip": "", + "country": "" + }, + "shipping_address": { + "street": "", + "line2": "", + "city": "", + "state": "", + "zip": "", + "country": "" + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "100.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546xp4h8n?token=n9fr5fxff5v74c7h9srg3cwd" + }, + { + "uid": "inv_8hr3546wdwxkr", + "site_id": 51288, + "customer_id": 21687670, + "subscription_id": 22007627, + "number": "123", + "sequence_number": 123, + "issue_date": "2018-09-18", + "due_date": "2018-09-18", + "paid_date": "2018-09-18", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Trial End - Free", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" }, "customer": { - "chargify_id": 3, - "first_name": "Marty", - "last_name": "McFly", - "organization": "Time Travellers, Inc.", - "email": "timetraveller1985@example.com", - "reference": null + "chargify_id": 21687670, + "first_name": "Hello", + "last_name": "World", + "organization": "123", + "email": "example@example.com" }, + "memo": "Please pay within 15 days.", "billing_address": { - "street": "200 Billing Rd.", - "line2": "Suite 100", - "city": "Needham", + "street": "123 Anywhere Street", + "line2": "", + "city": "Boston", "state": "MA", - "zip": "02494", + "zip": "02120", "country": "US" }, "shipping_address": { - "street": "100 Shipping St.", - "line2": "Apt 200", - "city": "Pleasantville", - "state": "NC", - "zip": "12345", + "street": "", + "line2": "", + "city": "Boston", + "state": "AL", + "zip": "02120", "country": "US" }, - "subtotal_amount": "208.69341779", - "discount_amount": "20.87125167", - "tax_amount": "12.67783387", - "total_amount": "200.5", - "applied_amount": "200.5", - "remaining_amount": "0.0", - "line_items": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "title": "IP Addresses: 5 to 10 addresses", - "description": "38.2% credit", - "quantity": "0.9855", - "unit_price": "2.0", - "subtotal_amount": "1.971004", - "discount_amount": "0.19862831", - "tax_amount": "0.11963536", - "total_amount": "1.89201105", - "tiered_unit_price": false, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165 - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "title": "Professional Plan", - "description": "38.2% credit", - "quantity": "0.382", - "unit_price": "299.0", - "subtotal_amount": "114.21127834", - "discount_amount": "11.42112783", - "tax_amount": "6.93833516", - "total_amount": "109.72848567", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": null, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjknzhx7", - "title": "Small Instance (Hourly)", - "description": "38.2% credit", - "quantity": "74.8676", - "unit_price": "0.12244898", - "subtotal_amount": "9.16746047", - "discount_amount": "0.91674605", - "tax_amount": "0.55692322", - "total_amount": "8.80763764", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 78, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjnmh25w", - "title": "Large Instance (Hourly)", - "description": "38.2% credit", - "quantity": "183.3492", - "unit_price": "0.39583333", - "subtotal_amount": "72.57572871", - "discount_amount": "7.25757287", - "tax_amount": "4.40897552", - "total_amount": "69.72713136", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 79, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjqn86kc", - "title": "Email Messages", - "description": "38.2% credit", - "quantity": "10076.9489", - "unit_price": "0.00031045", - "subtotal_amount": "3.12839588", - "discount_amount": "0.31322157", - "tax_amount": "0.19002427", - "total_amount": "3.00519858", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 80, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "title": "IP Addresses", - "description": "38.2% credit", - "quantity": "3.8198", - "unit_price": "2.0", - "subtotal_amount": "7.63955039", - "discount_amount": "0.76395504", - "tax_amount": "0.46410269", - "total_amount": "7.33969804", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165 - } - ], - "discounts": [ - { - "uid": "cndli_8k5jvdzct4h9y", - "title": "Multi-service discount (10%)", - "code": "MULTI3", - "source_type": "Coupon", - "source_id": 40, - "discount_type": "percentage", - "percentage": "10.0", - "eligible_amount": "208.69341779", - "discount_amount": "20.87125167", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "eligible_amount": "1.971004", - "discount_amount": "0.19862831" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "eligible_amount": "114.21127834", - "discount_amount": "11.42112783" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "eligible_amount": "9.16746047", - "discount_amount": "0.91674605" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "eligible_amount": "72.57572871", - "discount_amount": "7.25757287" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "eligible_amount": "3.12839588", - "discount_amount": "0.31322157" - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "eligible_amount": "7.63955039", - "discount_amount": "0.76395504" - } - ] - } - ], - "taxes": [ - { - "uid": "cntli_8k5jvdzct4h9z", - "title": "NC Sales Tax", - "source_type": "Tax", - "source_id": 1, - "percentage": "6.75", - "taxable_amount": "187.82216613", - "tax_amount": "12.67783387", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "taxable_amount": "1.77237569", - "tax_amount": "0.11963536" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "taxable_amount": "102.7901505", - "tax_amount": "6.93833516" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "taxable_amount": "8.25071442", - "tax_amount": "0.55692322" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "taxable_amount": "65.31815584", - "tax_amount": "4.40897552" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "taxable_amount": "2.81517432", - "tax_amount": "0.19002427" - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "taxable_amount": "6.87559535", - "tax_amount": "0.46410269" - } - ] - } - ], - "applications": [ - { - "uid": "cdt_8m9vbdbdwd28n", - "transaction_time": "2018-12-31T21:19:28Z", - "invoice_uid": "inv_8k5jvdzct4hb2", - "memo": "Refund for overpayment", - "applied_amount": "200.5" - } - ], - "refunds": [ - { - "transaction_id": 329, - "payment_id": 39, - "memo": "Refund for overpayment", - "original_amount": "524.9", - "applied_amount": "200.5" - } - ] + "subtotal_amount": "0.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "0.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546wdwxkr?token=n9fr5fxff5v74c7h9srg3cwd" + }, + { + "uid": "inv_8hjtk8bz56bbp", + "site_id": 51288, + "customer_id": 20137757, + "subscription_id": 20541100, + "number": "122", + "sequence_number": 122, + "issue_date": "2018-09-10", + "due_date": "2018-09-10", + "paid_date": "2018-09-10", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "$0 Product", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20137757, + "first_name": "Sasha", + "last_name": "Example", + "organization": "", + "email": "example@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Catville", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "shipping_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Catville", + "state": "AL", + "zip": "90210", + "country": "US" + }, + "subtotal_amount": "0.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "0.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hjtk8bz56bbp?token=fb6kpjz5rcr2vttyjs4rcv6y" } ] } ``` -# Read Credit Note +# Read Invoice -Use this endpoint to retrieve the details for a credit note. +Use this endpoint to retrieve the details for an invoice. ```csharp -ReadCreditNoteAsync( +ReadInvoiceAsync( string uid) ``` @@ -1596,19 +1011,201 @@ ReadCreditNoteAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier of the credit note | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | + +## Response Type + +[`Task`](../../doc/models/invoice.md) + +## Example Usage + +```csharp +string uid = "uid0"; +try +{ + Invoice result = await invoicesController.ReadInvoiceAsync(uid); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "inv_8gd8tdhtd3hgr", + "site_id": 51288, + "customer_id": 20194505, + "subscription_id": 20597774, + "number": "117", + "sequence_number": 117, + "issue_date": "2018-07-26", + "due_date": "2018-07-26", + "paid_date": "2018-07-26", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Monthly Product", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20194505, + "first_name": "Joe", + "last_name": "Example", + "organization": null, + "email": "joe@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "shipping_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "100.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "line_items": [ + { + "uid": "li_8gd8tdhhgk55k", + "title": "Monthly Product", + "description": "Jul 26, 2018 - Aug 26, 2018", + "quantity": "1.0", + "unit_price": "100.0", + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "tiered_unit_price": false, + "period_range_start": "2018-07-26", + "period_range_end": "2018-08-26", + "product_id": 4607632, + "product_version": 1, + "component_id": null, + "price_point_id": null + } + ], + "discounts": [], + "taxes": [], + "credits": [], + "payments": [ + { + "transaction_time": "2018-07-26T15:22:02Z", + "memo": "Joe Example - Monthly Product: Renewal payment", + "original_amount": "100.0", + "applied_amount": "100.0", + "payment_method": { + "card_brand": "bogus", + "card_expiration": "10/2020", + "last_four": null, + "masked_card_number": "XXXX-XXXX-XXXX-1", + "type": "credit_card" + }, + "transaction_id": 253028955, + "prepayment": false + } + ], + "refunds": [], + "custom_fields": [], + "public_url": "https://www.chargifypay.com/invoice/inv_8jzrw74xq8kxr?token=fb6kpjz5rcr2vttyjs4rcv6y" +} +``` + + +# List Invoice Events + +This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. + +Exposed event types are: + ++ issue_invoice ++ apply_credit_note ++ apply_payment ++ refund_invoice ++ void_invoice ++ void_remainder ++ backport_invoice ++ change_invoice_status ++ change_invoice_collection_method ++ remove_payment ++ failed_payment ++ apply_debit_note ++ create_debit_note ++ change_chargeback_status + +Invoice events are returned in ascending order. + +If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. + +Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. + +```csharp +ListInvoiceEventsAsync( + Models.ListInvoiceEventsInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `sinceDate` | `string` | Query, Optional | The timestamp in a format `YYYY-MM-DD T HH:MM:SS Z`, or `YYYY-MM-DD`(in this case, it returns data from the beginning of the day). of the event from which you want to start the search. All the events before the `since_date` timestamp are not returned in the response. | +| `sinceId` | `int?` | Query, Optional | The ID of the event from which you want to start the search(ID is not included. e.g. if ID is set to 2, then all events with ID 3 and more will be shown) This parameter is not used if since_date is defined. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | +| `invoiceUid` | `string` | Query, Optional | Providing an invoice_uid allows for scoping of the invoice events to a single invoice or credit note. | +| `withChangeInvoiceStatus` | `string` | Query, Optional | Use this parameter if you want to fetch also invoice events with change_invoice_status type. | +| `eventTypes` | [`List`](../../doc/models/invoice-event-type.md) | Query, Optional | Filter results by event_type. Supply a comma separated list of event types (listed above). Use in query: `event_types=void_invoice,void_remainder`. | ## Response Type -[`Task`](../../doc/models/credit-note.md) +[`Task`](../../doc/models/list-invoice-events-response.md) ## Example Usage ```csharp -string uid = "uid0"; +ListInvoiceEventsInput listInvoiceEventsInput = new ListInvoiceEventsInput +{ + Page = 2, + PerPage = 100, +}; + try { - CreditNote result = await invoicesController.ReadCreditNoteAsync(uid); + ListInvoiceEventsResponse result = await invoicesController.ListInvoiceEventsAsync(listInvoiceEventsInput); } catch (ApiException e) { @@ -1621,325 +1218,414 @@ catch (ApiException e) ```json { - "uid": "cn_8m9vbd5kkv7kr", - "site_id": 20, - "customer_id": 3, - "subscription_id": 2, - "number": "77", - "sequence_number": 78, - "issue_date": "2018-12-31", - "applied_date": "2018-12-31", - "status": "applied", - "currency": "USD", - "memo": "Refund for overpayment", - "seller": { - "name": "Acme, Inc.", - "address": { - "street": "122 E Houston St", - "line2": "Suite 105", - "city": "San Antonio", - "state": "TX", - "zip": "78205", - "country": "US" - }, - "phone": "555-555-1234 x137" - }, - "customer": { - "chargify_id": 3, - "first_name": "Marty", - "last_name": "McFly", - "organization": "Time Travellers, Inc.", - "email": "timetraveller1985@example.com", - "reference": null - }, - "billing_address": { - "street": "200 Billing Rd.", - "line2": "Suite 100", - "city": "Needham", - "state": "MA", - "zip": "02494", - "country": "US" - }, - "shipping_address": { - "street": "100 Shipping St.", - "line2": "Apt 200", - "city": "Pleasantville", - "state": "NC", - "zip": "12345", - "country": "US" - }, - "subtotal_amount": "208.69341779", - "discount_amount": "20.87125167", - "tax_amount": "12.67783387", - "total_amount": "200.5", - "applied_amount": "200.5", - "remaining_amount": "0.0", - "line_items": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "title": "IP Addresses: 5 to 10 addresses", - "description": "38.2% credit", - "quantity": "0.9855", - "unit_price": "2.0", - "subtotal_amount": "1.971004", - "discount_amount": "0.19862831", - "tax_amount": "0.11963536", - "total_amount": "1.89201105", - "tiered_unit_price": false, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165 - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "title": "Professional Plan", - "description": "38.2% credit", - "quantity": "0.382", - "unit_price": "299.0", - "subtotal_amount": "114.21127834", - "discount_amount": "11.42112783", - "tax_amount": "6.93833516", - "total_amount": "109.72848567", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": null, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjknzhx7", - "title": "Small Instance (Hourly)", - "description": "38.2% credit", - "quantity": "74.8676", - "unit_price": "0.12244898", - "subtotal_amount": "9.16746047", - "discount_amount": "0.91674605", - "tax_amount": "0.55692322", - "total_amount": "8.80763764", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 78, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjnmh25w", - "title": "Large Instance (Hourly)", - "description": "38.2% credit", - "quantity": "183.3492", - "unit_price": "0.39583333", - "subtotal_amount": "72.57572871", - "discount_amount": "7.25757287", - "tax_amount": "4.40897552", - "total_amount": "69.72713136", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 79, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjqn86kc", - "title": "Email Messages", - "description": "38.2% credit", - "quantity": "10076.9489", - "unit_price": "0.00031045", - "subtotal_amount": "3.12839588", - "discount_amount": "0.31322157", - "tax_amount": "0.19002427", - "total_amount": "3.00519858", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 80, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "title": "IP Addresses", - "description": "38.2% credit", - "quantity": "3.8198", - "unit_price": "2.0", - "subtotal_amount": "7.63955039", - "discount_amount": "0.76395504", - "tax_amount": "0.46410269", - "total_amount": "7.33969804", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165 - } - ], - "discounts": [ + "events": [ { - "uid": "cndli_8k5jvdzct4h9y", - "title": "Multi-service discount (10%)", - "code": "MULTI3", - "source_type": "Coupon", - "source_id": 40, - "discount_type": "percentage", - "percentage": "10.0", - "eligible_amount": "208.69341779", - "discount_amount": "20.87125167", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "eligible_amount": "1.971004", - "discount_amount": "0.19862831" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "eligible_amount": "114.21127834", - "discount_amount": "11.42112783" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "eligible_amount": "9.16746047", - "discount_amount": "0.91674605" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "eligible_amount": "72.57572871", - "discount_amount": "7.25757287" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "eligible_amount": "3.12839588", - "discount_amount": "0.31322157" + "id": 83, + "event_type": "apply_payment", + "event_data": { + "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", + "original_amount": "168.61", + "applied_amount": "168.61", + "transaction_time": "2018-08-01T16:00:00Z", + "payment_method": { + "card_brand": "visa", + "card_expiration": "12/2022", + "last_four": null, + "masked_card_number": "XXXX-XXXX-XXXX-1111", + "type": "credit_card" }, - { - "uid": "cnli_8kjttvjtxxbdd", - "eligible_amount": "7.63955039", - "discount_amount": "0.76395504" - } - ] - } - ], - "taxes": [ - { - "uid": "cntli_8k5jvdzct4h9z", - "title": "NC Sales Tax", - "source_type": "Tax", - "source_id": 1, - "percentage": "6.75", - "taxable_amount": "187.82216613", - "tax_amount": "12.67783387", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "taxable_amount": "1.77237569", - "tax_amount": "0.11963536" + "consolidation_level": "none" + }, + "timestamp": "2018-08-01T16:00:00Z", + "invoice": { + "id": 614942008934401500, + "uid": "inv_8gk5bwkct3gqt", + "site_id": 20, + "customer_id": 6, + "subscription_id": 10, + "number": "25", + "sequence_number": 25, + "transaction_time": "2018-08-01T16:00:00Z", + "created_at": "2018-08-01T16:00:00Z", + "updated_at": "2018-08-01T16:00:00Z", + "issue_date": "2018-08-01", + "due_date": "2018-08-01", + "paid_date": "2018-08-01", + "status": "paid", + "role": "renewal", + "collection_method": "automatic", + "payment_instructions": "Please make checks payable to \"Acme, Inc.\"", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_id": null, + "subscription_group_id": null, + "parent_invoice_number": null, + "product_name": "Standard Plan", + "product_family_name": "Cloud Compute Servers", + "seller": { + "name": "Acme, Inc.", + "address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "phone": "555-555-1234 x137", + "logo_url": null }, - { - "uid": "cnli_8kjttvjcjx8b4", - "taxable_amount": "102.7901505", - "tax_amount": "6.93833516" + "customer": { + "chargify_id": 6, + "first_name": "Non-Resumable", + "last_name": "Canceled On Purpose", + "organization": null, + "email": "evan4@example.com" }, - { - "uid": "cnli_8kjttvjknzhx7", - "taxable_amount": "8.25071442", - "tax_amount": "0.55692322" + "payer": { + "chargify_id": 6, + "first_name": "Non-Resumable", + "last_name": "Canceled On Purpose", + "organization": null, + "email": "evan4@example.com" }, - { - "uid": "cnli_8kjttvjnmh25w", - "taxable_amount": "65.31815584", - "tax_amount": "4.40897552" + "recipient_emails": [], + "net_terms": 0, + "memo": "Thanks for your business! If you have any questions, please contact your account manager.", + "billing_address": { + "street": "200 Billing Rd.", + "line2": "Suite 100", + "city": "Needham", + "state": "MA", + "zip": "02494", + "country": "US" }, - { - "uid": "cnli_8kjttvjqn86kc", - "taxable_amount": "2.81517432", - "tax_amount": "0.19002427" + "shipping_address": { + "street": "100 Shipping St.", + "line2": "Apt 200", + "city": "Pleasantville", + "state": "NC", + "zip": "12345", + "country": "US" }, - { - "uid": "cnli_8kjttvjtxxbdd", - "taxable_amount": "6.87559535", - "tax_amount": "0.46410269" + "line_items": [ + { + "uid": "li_8gk5bwkct3gqk", + "title": "Standard Plan", + "description": "08/01/2018 - 09/01/2018", + "quantity": "1.0", + "unit_price": "99.0", + "subtotal_amount": "99.0", + "discount_amount": "9.9", + "tax_amount": "6.01425", + "total_amount": "95.11425", + "tiered_unit_price": false, + "period_range_start": "2018-08-01", + "period_range_end": "2018-09-01", + "transaction_id": 120, + "product_id": 84, + "product_version": 1, + "component_id": null, + "price_point_id": null, + "hide": false + }, + { + "uid": "li_8gk5bwkct3gqm", + "title": "Small Instance (Hourly)", + "description": "07/22/2018 - 08/01/2018", + "quantity": "162.0", + "unit_price": "0.09567901", + "subtotal_amount": "15.5", + "discount_amount": "1.55", + "tax_amount": "0.941625", + "total_amount": "14.891625", + "tiered_unit_price": true, + "period_range_start": "2018-07-22", + "period_range_end": "2018-08-01", + "transaction_id": 121, + "product_id": 84, + "product_version": 1, + "component_id": 76, + "price_point_id": null, + "hide": false, + "component_cost_data": { + "rates": [ + { + "component_code_id": null, + "price_point_id": 160, + "product_id": 84, + "quantity": "162.0", + "amount": "15.5", + "pricing_scheme": "tiered", + "tiers": [ + { + "starting_quantity": 1, + "ending_quantity": 100, + "quantity": "100.0", + "unit_price": "0.0", + "amount": "0.0" + }, + { + "starting_quantity": 101, + "ending_quantity": null, + "quantity": "62.0", + "unit_price": "0.25", + "amount": "15.5" + } + ] + } + ] + } + }, + { + "uid": "li_8gk5bwkct3gqn", + "title": "Large Instance (Hourly)", + "description": "07/22/2018 - 08/01/2018", + "quantity": "194.0", + "unit_price": "0.24226804", + "subtotal_amount": "47.0", + "discount_amount": "4.7", + "tax_amount": "2.85525", + "total_amount": "45.15525", + "tiered_unit_price": true, + "period_range_start": "2018-07-22", + "period_range_end": "2018-08-01", + "transaction_id": 122, + "product_id": 84, + "product_version": 1, + "component_id": 77, + "price_point_id": null, + "hide": false, + "component_cost_data": { + "rates": [ + { + "component_code_id": null, + "price_point_id": 161, + "product_id": 84, + "quantity": "194.0", + "amount": "47.0", + "pricing_scheme": "tiered", + "tiers": [ + { + "starting_quantity": 1, + "ending_quantity": 100, + "quantity": "100.0", + "unit_price": "0.0", + "amount": "0.0" + }, + { + "starting_quantity": 101, + "ending_quantity": null, + "quantity": "94.0", + "unit_price": "0.5", + "amount": "47.0" + } + ] + } + ] + } + }, + { + "uid": "li_8gk5bwkct3gqp", + "title": "IP Addresses", + "description": "08/01/2018 - 09/01/2018", + "quantity": "7.0", + "unit_price": "2.0", + "subtotal_amount": "14.0", + "discount_amount": "1.4", + "tax_amount": "0.8505", + "total_amount": "13.4505", + "tiered_unit_price": false, + "period_range_start": "2018-08-01", + "period_range_end": "2018-09-01", + "transaction_id": 123, + "product_id": 84, + "product_version": 1, + "component_id": 79, + "price_point_id": 163, + "hide": false, + "component_cost_data": { + "rates": [ + { + "component_code_id": null, + "price_point_id": 163, + "product_id": 84, + "quantity": "7.0", + "amount": "14.0", + "pricing_scheme": "per_unit", + "tiers": [ + { + "starting_quantity": 1, + "ending_quantity": null, + "quantity": "7.0", + "unit_price": "2.0", + "amount": "14.0" + } + ] + } + ] + } + } + ], + "subtotal_amount": "175.5", + "discount_amount": "17.55", + "discounts": [ + { + "uid": "dli_8gk5bwkct3gqq", + "title": "Multi-service discount (10%)", + "description": null, + "code": "MULTI3", + "source_type": "Coupon", + "source_id": 40, + "discount_type": "percentage", + "percentage": "10.0", + "eligible_amount": "175.5", + "discount_amount": "17.55", + "transaction_id": 124, + "line_item_breakouts": [ + { + "uid": "li_8gk5bwkct3gqk", + "eligible_amount": "99.0", + "discount_amount": "9.9" + }, + { + "uid": "li_8gk5bwkct3gqm", + "eligible_amount": "15.5", + "discount_amount": "1.55" + }, + { + "uid": "li_8gk5bwkct3gqn", + "eligible_amount": "47.0", + "discount_amount": "4.7" + }, + { + "uid": "li_8gk5bwkct3gqp", + "eligible_amount": "14.0", + "discount_amount": "1.4" + } + ] + } + ], + "tax_amount": "10.66", + "taxes": [ + { + "uid": "tli_8gk5bwkct3gqr", + "title": "NC Sales Tax", + "description": null, + "source_type": "Tax", + "source_id": 1, + "percentage": "6.75", + "taxable_amount": "157.95", + "tax_amount": "10.66", + "transaction_id": 125, + "line_item_breakouts": [ + { + "uid": "li_8gk5bwkct3gqk", + "taxable_amount": "89.1", + "tax_amount": "6.01425" + }, + { + "uid": "li_8gk5bwkct3gqm", + "taxable_amount": "13.95", + "tax_amount": "0.941625" + }, + { + "uid": "li_8gk5bwkct3gqn", + "taxable_amount": "42.3", + "tax_amount": "2.85525" + }, + { + "uid": "li_8gk5bwkct3gqp", + "taxable_amount": "12.6", + "tax_amount": "0.8505" + } + ], + "tax_component_breakouts": [ + { + "tax_rule_id": 1, + "percentage": "6.75", + "country_code": "US", + "subdivision_code": "NC" + } + ] + } + ], + "credit_amount": "0.0", + "refund_amount": "0.0", + "total_amount": "168.61", + "paid_amount": "168.61", + "due_amount": "0.0", + "credits": [], + "refunds": [], + "payments": [ + { + "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", + "original_amount": "168.61", + "applied_amount": "168.61", + "transaction_time": "2018-08-01T16:00:00Z", + "payment_method": { + "card_brand": "visa", + "card_expiration": "12/2022", + "last_four": null, + "masked_card_number": "XXXX-XXXX-XXXX-1111", + "type": "credit_card" + }, + "transaction_id": 126, + "prepayment": false + } + ], + "custom_fields": [], + "display_settings": { + "hide_zero_subtotal_lines": false, + "include_discounts_on_lines": false } - ] - } - ], - "applications": [ - { - "uid": "cdt_8m9vbdbdwd28n", - "transaction_time": "2018-12-31T21:19:28Z", - "invoice_uid": "inv_8k5jvdzct4hb2", - "memo": "Refund for overpayment", - "applied_amount": "200.5" + } } ], - "refunds": [ - { - "transaction_id": 329, - "payment_id": 39, - "memo": "Refund for overpayment", - "original_amount": "524.9", - "applied_amount": "200.5" - } - ] + "page": 48, + "per_page": 1, + "total_pages": 102 } ``` -# Record Payment for Subscription - -Record an external payment made against a subscription that will pay partially or in full one or more invoices. - -Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. - -Excess payment will result in the creation of a prepayment on the Invoice Account. +# Void Invoice -Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. +This endpoint allows you to void any invoice with the "open" or "canceled" status. It will also allow voiding of an invoice with the "pending" status if it is not a consolidated invoice. ```csharp -RecordPaymentForSubscriptionAsync( - int subscriptionId, - Models.RecordPaymentRequest body = null) +VoidInvoiceAsync( + string uid, + Models.VoidInvoiceRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`RecordPaymentRequest`](../../doc/models/record-payment-request.md) | Body, Optional | - | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/payment-response.md) +[`Task`](../../doc/models/invoice.md) ## Example Usage ```csharp -int subscriptionId = 222; -RecordPaymentRequest body = new RecordPaymentRequest +string uid = "uid0"; +VoidInvoiceRequest body = new VoidInvoiceRequest { - Payment = new CreatePayment + MVoid = new VoidInvoice { - Amount = "10.0", - Memo = "to pay the bills", - PaymentDetails = "check number 8675309", - PaymentMethod = "check", + Reason = "Duplicate invoice", }, }; try { - PaymentResponse result = await invoicesController.RecordPaymentForSubscriptionAsync( - subscriptionId, + Invoice result = await invoicesController.VoidInvoiceAsync( + uid, body ); } @@ -1950,56 +1636,22 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -{ - "paid_invoices": [ - { - "invoice_uid": "xyz_012345678", - "status": "paid", - "due_amount": "0.0", - "paid_amount": "50.0" - }, - { - "invoice_uid": "xyz_012345678", - "status": "paid", - "due_amount": "0.0", - "paid_amount": "50.0" - } - ], - "prepayment": { - "subscription_id": "123456", - "amount_in_cents": "5000", - "ending_balance_in_cents": "5000" - } -} -``` - ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Reopen Invoice - -This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). - -Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways: - -- Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.) -- Recording a payment directly against the invoice - -A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. +# Preview Customer Information Changes -### Reopening Consolidated Invoices +Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. -When reopening a consolidated invoice, all of its canceled segments will also be reopened. +The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. ```csharp -ReopenInvoiceAsync( +PreviewCustomerInformationChangesAsync( string uid) ``` @@ -2011,7 +1663,7 @@ ReopenInvoiceAsync( ## Response Type -[`Task`](../../doc/models/invoice.md) +[`Task`](../../doc/models/customer-changes-preview-response.md) ## Example Usage @@ -2019,7 +1671,7 @@ ReopenInvoiceAsync( string uid = "uid0"; try { - Invoice result = await invoicesController.ReopenInvoiceAsync(uid); + CustomerChangesPreviewResponse result = await invoicesController.PreviewCustomerInformationChangesAsync(uid); } catch (ApiException e) { @@ -2028,58 +1680,56 @@ catch (ApiException e) } ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Void Invoice - -This endpoint allows you to void any invoice with the "open" or "canceled" status. It will also allow voiding of an invoice with the "pending" status if it is not a consolidated invoice. - -```csharp -VoidInvoiceAsync( - string uid, - Models.VoidInvoiceRequest body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/invoice.md) - -## Example Usage +## Example Response *(as JSON)* -```csharp -string uid = "uid0"; -VoidInvoiceRequest body = new VoidInvoiceRequest +```json { - MVoid = new VoidInvoice - { - Reason = "Duplicate invoice", + "changes": { + "payer": { + "before": { + "last_name": "Beatty" + }, + "after": { + "last_name": "Doe" + } + }, + "shipping_address": { + "before": { + "line2": "Suite 703" + }, + "after": { + "line2": "Suite 702" + } + }, + "billing_address": { + "before": { + "line2": "Suite 703" + }, + "after": { + "line2": "Suite 702" + } }, -}; - -try -{ - Invoice result = await invoicesController.VoidInvoiceAsync( - uid, - body - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); + "custom_fields": { + "before": [ + { + "owner_id": 1002, + "owner_type": "Customer", + "name": "Color", + "value": "blue", + "metadatum_id": 20 + } + ], + "after": [ + { + "owner_id": 1002, + "owner_type": "Customer", + "name": "Color", + "value": "green", + "metadatum_id": 20 + } + ] + } + } } ``` @@ -2087,7 +1737,7 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | +| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | @@ -2475,320 +2125,690 @@ When creating ad hoc invoice, new discounts can be applied in following way: "invoice": { "line_items": [ { - "product_id": "handle:gold-product", - "quantity": 1 + "product_id": "handle:gold-product", + "quantity": 1 + } + ], + "coupons": [ + { + "code": "COUPONCODE", + "percentage": 50.0 + } + ] + } +} +``` + +If You want to use existing coupon for discount creation, only `code` and optional `product_family_id` is needed + +```json +... + "coupons": [ + { + "code": "FREESETUP", + "product_family_id": 1 + } + ] +... +``` + +### Coupon options + +#### Code + +Coupon `code` will be displayed on invoice discount section. +Coupon code can only contain uppercase letters, numbers, and allowed special characters. +Lowercase letters will be converted to uppercase. It can be used to select an existing coupon from the catalog, or as an ad hoc coupon when passed with `percentage` or `amount`. + +#### Percentage + +Coupon `percentage` can take values from 0 to 100 and up to 4 decimal places. It cannot be used with `amount`. Only for ad hoc coupons, will be ignored if `code` is used to select an existing coupon from the catalog. + +#### Amount + +Coupon `amount` takes number value. It cannot be used with `percentage`. Used only when not matching existing coupon by `code`. + +#### Description + +Optional `description` will be displayed with coupon `code`. Used only when not matching existing coupon by `code`. + +#### Product Family id + +Optional `product_family_id` handle (with handle: prefix) or id is used to match existing coupon within site, when codes are not unique. + +#### Compounding Strategy + +Optional `compounding_strategy` for percentage coupons, can take values `compound` or `full-price`. + +For amount coupons, discounts will be always calculated against the original item price, before other discounts are applied. + +`compound` strategy: +Percentage-based discounts will be calculated against the remaining price, after prior discounts have been calculated. It is set by default. + +`full-price` strategy: +Percentage-based discounts will always be calculated against the original item price, before other discounts are applied. + +### Line Item Options + +#### Period Date Range + +A custom period date range can be defined for each line item with the `period_range_start` and `period_range_end` parameters. Dates must be sent in the `YYYY-MM-DD` format. +`period_range_end` must be greater or equal `period_range_start`. + +#### Taxes + +The `taxable` parameter can be sent as `true` if taxes should be calculated for a specific line item. For this to work, the site should be configured to use and calculate taxes. Further, if the site uses Avalara for tax calculations, a `tax_code` parameter should also be sent. For existing catalog items: products/components taxes cannot be overwritten. + +#### Price Point + +Price point handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `price_point_id` for components with `component_id` or `product_price_point_id` for products with `product_id` parameter. If price point is passed `unit_price` cannot be used. It can be used only with catalog items products and components. + +#### Description + +Optional `description` parameter, it will overwrite default generated description for line item. + +### Invoice Options + +#### Issue Date + +By default, invoices will be created with a issue date set to today. `issue_date` parameter can be send to alter that. Only dates in the past can be send. `issue_date` should be send in `YYYY-MM-DD` format. + +#### Net Terms + +By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the `net_terms` parameter can be sent indicating the number of days in advance the due date should be. + +#### Addresses + +The seller, shipping and billing addresses can be sent to override the site's defaults. Each address requires to send a `first_name` at a minimum in order to work. Please see below for the details on which parameters can be sent for each address object. + +#### Memo and Payment Instructions + +A custom memo can be sent with the `memo` parameter to override the site's default. Likewise, custom payment instructions can be sent with the `payment_instrucions` parameter. + +#### Status + +By default, invoices will be created with open status. Possible alternative is `draft`. + +```csharp +CreateInvoiceAsync( + int subscriptionId, + Models.CreateInvoiceRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`CreateInvoiceRequest`](../../doc/models/create-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/invoice-response.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +CreateInvoiceRequest body = new CreateInvoiceRequest +{ + Invoice = new CreateInvoice + { + LineItems = new List + { + new CreateInvoiceItem + { + Title = "A Product", + Quantity = CreateInvoiceItemQuantity.FromPrecision(12), + UnitPrice = CreateInvoiceItemUnitPrice.FromString("150.00"), + }, + }, + }, +}; + +try +{ + InvoiceResponse result = await invoicesController.CreateInvoiceAsync( + subscriptionId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "invoice": { + "uid": "inv_98nbmb93gxjz8", + "site_id": 5, + "customer_id": 13, + "subscription_id": 17, + "number": "1", + "sequence_number": 1, + "issue_date": "2020-12-02", + "due_date": "2020-12-02", + "paid_date": null, + "status": "open", + "collection_method": "remittance", + "payment_instructions": "", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Digitized discrete initiative", + "product_family_name": "Networked bottom-line orchestration", + "role": "adhoc", + "seller": { + "name": "Steuber, West and Hegmann 1", + "address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "phone": "(766) 316-0492" + }, + "customer": { + "chargify_id": 13, + "first_name": "Dean", + "last_name": "Adams", + "organization": null, + "email": "brandi1@example.com", + "vat_number": null, + "reference": null + }, + "memo": "", + "billing_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "shipping_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "subtotal_amount": "1800.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "1800.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "1800.0", + "line_items": [ + { + "uid": "li_98nbmb9jgz84c", + "title": "Some product", + "description": "12/02/2020 - 12/02/2020", + "quantity": "12.0", + "unit_price": "150.0", + "subtotal_amount": "1800.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "1800.0", + "tiered_unit_price": false, + "period_range_start": "2020-12-02", + "period_range_end": "2020-12-02", + "product_id": null, + "product_version": null, + "product_price_point_id": null, + "component_id": null, + "price_point_id": null } ], - "coupons": [ - { - "code": "COUPONCODE", - "percentage": 50.0 - } - ] + "discounts": [], + "taxes": [], + "credits": [], + "payments": [], + "refunds": [], + "custom_fields": [], + "public_url": "https://www.test-chargifypay.com/invoice/inv_98nbmb93gxjz8?token=rmfmwvbdy4xmyw5f29j5gc6x" } } ``` -If You want to use existing coupon for discount creation, only `code` and optional `product_family_id` is needed - -```json -... - "coupons": [ - { - "code": "FREESETUP", - "product_family_id": 1 - } - ] -... -``` - -### Coupon options - -#### Code - -Coupon `code` will be displayed on invoice discount section. -Coupon code can only contain uppercase letters, numbers, and allowed special characters. -Lowercase letters will be converted to uppercase. It can be used to select an existing coupon from the catalog, or as an ad hoc coupon when passed with `percentage` or `amount`. - -#### Percentage - -Coupon `percentage` can take values from 0 to 100 and up to 4 decimal places. It cannot be used with `amount`. Only for ad hoc coupons, will be ignored if `code` is used to select an existing coupon from the catalog. - -#### Amount - -Coupon `amount` takes number value. It cannot be used with `percentage`. Used only when not matching existing coupon by `code`. - -#### Description - -Optional `description` will be displayed with coupon `code`. Used only when not matching existing coupon by `code`. - -#### Product Family id - -Optional `product_family_id` handle (with handle: prefix) or id is used to match existing coupon within site, when codes are not unique. - -#### Compounding Strategy - -Optional `compounding_strategy` for percentage coupons, can take values `compound` or `full-price`. - -For amount coupons, discounts will be always calculated against the original item price, before other discounts are applied. - -`compound` strategy: -Percentage-based discounts will be calculated against the remaining price, after prior discounts have been calculated. It is set by default. +## Errors -`full-price` strategy: -Percentage-based discounts will always be calculated against the original item price, before other discounts are applied. +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | -### Line Item Options -#### Period Date Range +# Issue Invoice -A custom period date range can be defined for each line item with the `period_range_start` and `period_range_end` parameters. Dates must be sent in the `YYYY-MM-DD` format. -`period_range_end` must be greater or equal `period_range_start`. +This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. -#### Taxes +You cannot issue a pending child invoice that was created for a member subscription in a group. -The `taxable` parameter can be sent as `true` if taxes should be calculated for a specific line item. For this to work, the site should be configured to use and calculate taxes. Further, if the site uses Avalara for tax calculations, a `tax_code` parameter should also be sent. For existing catalog items: products/components taxes cannot be overwritten. +For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. -#### Price Point +For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value: -Price point handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `price_point_id` for components with `component_id` or `product_price_point_id` for products with `product_id` parameter. If price point is passed `unit_price` cannot be used. It can be used only with catalog items products and components. +- `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. +- `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. +- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). -#### Description +```csharp +IssueInvoiceAsync( + string uid, + Models.IssueInvoiceRequest body = null) +``` -Optional `description` parameter, it will overwrite default generated description for line item. +## Parameters -### Invoice Options +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`IssueInvoiceRequest`](../../doc/models/issue-invoice-request.md) | Body, Optional | - | -#### Issue Date +## Response Type -By default, invoices will be created with a issue date set to today. `issue_date` parameter can be send to alter that. Only dates in the past can be send. `issue_date` should be send in `YYYY-MM-DD` format. +[`Task`](../../doc/models/invoice.md) -#### Net Terms +## Example Usage -By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the `net_terms` parameter can be sent indicating the number of days in advance the due date should be. +```csharp +string uid = "uid0"; +IssueInvoiceRequest body = new IssueInvoiceRequest +{ + OnFailedPayment = FailedPaymentAction.LeaveOpenInvoice, +}; -#### Addresses +try +{ + Invoice result = await invoicesController.IssueInvoiceAsync( + uid, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -The seller, shipping and billing addresses can be sent to override the site's defaults. Each address requires to send a `first_name` at a minimum in order to work. Please see below for the details on which parameters can be sent for each address object. +## Errors -#### Memo and Payment Instructions +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -A custom memo can be sent with the `memo` parameter to override the site's default. Likewise, custom payment instructions can be sent with the `payment_instrucions` parameter. -#### Status +# Read Credit Note -By default, invoices will be created with open status. Possible alternative is `draft`. +Use this endpoint to retrieve the details for a credit note. ```csharp -CreateInvoiceAsync( - int subscriptionId, - Models.CreateInvoiceRequest body = null) +ReadCreditNoteAsync( + string uid) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`CreateInvoiceRequest`](../../doc/models/create-invoice-request.md) | Body, Optional | - | +| `uid` | `string` | Template, Required | The unique identifier of the credit note | ## Response Type -[`Task`](../../doc/models/invoice-response.md) +[`Task`](../../doc/models/credit-note.md) ## Example Usage ```csharp -int subscriptionId = 222; -CreateInvoiceRequest body = new CreateInvoiceRequest +string uid = "uid0"; +try { - Invoice = new CreateInvoice - { - LineItems = new List - { - new CreateInvoiceItem - { - Title = "A Product", - Quantity = CreateInvoiceItemQuantity.FromPrecision(12), - UnitPrice = CreateInvoiceItemUnitPrice.FromString("150.00"), - }, - }, + CreditNote result = await invoicesController.ReadCreditNoteAsync(uid); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "cn_8m9vbd5kkv7kr", + "site_id": 20, + "customer_id": 3, + "subscription_id": 2, + "number": "77", + "sequence_number": 78, + "issue_date": "2018-12-31", + "applied_date": "2018-12-31", + "status": "applied", + "currency": "USD", + "memo": "Refund for overpayment", + "seller": { + "name": "Acme, Inc.", + "address": { + "street": "122 E Houston St", + "line2": "Suite 105", + "city": "San Antonio", + "state": "TX", + "zip": "78205", + "country": "US" + }, + "phone": "555-555-1234 x137" + }, + "customer": { + "chargify_id": 3, + "first_name": "Marty", + "last_name": "McFly", + "organization": "Time Travellers, Inc.", + "email": "timetraveller1985@example.com", + "reference": null + }, + "billing_address": { + "street": "200 Billing Rd.", + "line2": "Suite 100", + "city": "Needham", + "state": "MA", + "zip": "02494", + "country": "US" + }, + "shipping_address": { + "street": "100 Shipping St.", + "line2": "Apt 200", + "city": "Pleasantville", + "state": "NC", + "zip": "12345", + "country": "US" + }, + "subtotal_amount": "208.69341779", + "discount_amount": "20.87125167", + "tax_amount": "12.67783387", + "total_amount": "200.5", + "applied_amount": "200.5", + "remaining_amount": "0.0", + "line_items": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "title": "IP Addresses: 5 to 10 addresses", + "description": "38.2% credit", + "quantity": "0.9855", + "unit_price": "2.0", + "subtotal_amount": "1.971004", + "discount_amount": "0.19862831", + "tax_amount": "0.11963536", + "total_amount": "1.89201105", + "tiered_unit_price": false, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165 }, -}; - -try -{ - InvoiceResponse result = await invoicesController.CreateInvoiceAsync( - subscriptionId, - body - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "invoice": { - "uid": "inv_98nbmb93gxjz8", - "site_id": 5, - "customer_id": 13, - "subscription_id": 17, - "number": "1", - "sequence_number": 1, - "issue_date": "2020-12-02", - "due_date": "2020-12-02", - "paid_date": null, - "status": "open", - "collection_method": "remittance", - "payment_instructions": "", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Digitized discrete initiative", - "product_family_name": "Networked bottom-line orchestration", - "role": "adhoc", - "seller": { - "name": "Steuber, West and Hegmann 1", - "address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "phone": "(766) 316-0492" + { + "uid": "cnli_8kjttvjcjx8b4", + "title": "Professional Plan", + "description": "38.2% credit", + "quantity": "0.382", + "unit_price": "299.0", + "subtotal_amount": "114.21127834", + "discount_amount": "11.42112783", + "tax_amount": "6.93833516", + "total_amount": "109.72848567", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": null, + "price_point_id": null }, - "customer": { - "chargify_id": 13, - "first_name": "Dean", - "last_name": "Adams", - "organization": null, - "email": "brandi1@example.com", - "vat_number": null, - "reference": null + { + "uid": "cnli_8kjttvjknzhx7", + "title": "Small Instance (Hourly)", + "description": "38.2% credit", + "quantity": "74.8676", + "unit_price": "0.12244898", + "subtotal_amount": "9.16746047", + "discount_amount": "0.91674605", + "tax_amount": "0.55692322", + "total_amount": "8.80763764", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 78, + "price_point_id": null }, - "memo": "", - "billing_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null + { + "uid": "cnli_8kjttvjnmh25w", + "title": "Large Instance (Hourly)", + "description": "38.2% credit", + "quantity": "183.3492", + "unit_price": "0.39583333", + "subtotal_amount": "72.57572871", + "discount_amount": "7.25757287", + "tax_amount": "4.40897552", + "total_amount": "69.72713136", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 79, + "price_point_id": null }, - "shipping_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null + { + "uid": "cnli_8kjttvjqn86kc", + "title": "Email Messages", + "description": "38.2% credit", + "quantity": "10076.9489", + "unit_price": "0.00031045", + "subtotal_amount": "3.12839588", + "discount_amount": "0.31322157", + "tax_amount": "0.19002427", + "total_amount": "3.00519858", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 80, + "price_point_id": null }, - "subtotal_amount": "1800.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "1800.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "1800.0", - "line_items": [ - { - "uid": "li_98nbmb9jgz84c", - "title": "Some product", - "description": "12/02/2020 - 12/02/2020", - "quantity": "12.0", - "unit_price": "150.0", - "subtotal_amount": "1800.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "1800.0", - "tiered_unit_price": false, - "period_range_start": "2020-12-02", - "period_range_end": "2020-12-02", - "product_id": null, - "product_version": null, - "product_price_point_id": null, - "component_id": null, - "price_point_id": null - } - ], - "discounts": [], - "taxes": [], - "credits": [], - "payments": [], - "refunds": [], - "custom_fields": [], - "public_url": "https://www.test-chargifypay.com/invoice/inv_98nbmb93gxjz8?token=rmfmwvbdy4xmyw5f29j5gc6x" - } + { + "uid": "cnli_8kjttvjtxxbdd", + "title": "IP Addresses", + "description": "38.2% credit", + "quantity": "3.8198", + "unit_price": "2.0", + "subtotal_amount": "7.63955039", + "discount_amount": "0.76395504", + "tax_amount": "0.46410269", + "total_amount": "7.33969804", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165 + } + ], + "discounts": [ + { + "uid": "cndli_8k5jvdzct4h9y", + "title": "Multi-service discount (10%)", + "code": "MULTI3", + "source_type": "Coupon", + "source_id": 40, + "discount_type": "percentage", + "percentage": "10.0", + "eligible_amount": "208.69341779", + "discount_amount": "20.87125167", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "eligible_amount": "1.971004", + "discount_amount": "0.19862831" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "eligible_amount": "114.21127834", + "discount_amount": "11.42112783" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "eligible_amount": "9.16746047", + "discount_amount": "0.91674605" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "eligible_amount": "72.57572871", + "discount_amount": "7.25757287" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "eligible_amount": "3.12839588", + "discount_amount": "0.31322157" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "eligible_amount": "7.63955039", + "discount_amount": "0.76395504" + } + ] + } + ], + "taxes": [ + { + "uid": "cntli_8k5jvdzct4h9z", + "title": "NC Sales Tax", + "source_type": "Tax", + "source_id": 1, + "percentage": "6.75", + "taxable_amount": "187.82216613", + "tax_amount": "12.67783387", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "taxable_amount": "1.77237569", + "tax_amount": "0.11963536" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "taxable_amount": "102.7901505", + "tax_amount": "6.93833516" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "taxable_amount": "8.25071442", + "tax_amount": "0.55692322" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "taxable_amount": "65.31815584", + "tax_amount": "4.40897552" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "taxable_amount": "2.81517432", + "tax_amount": "0.19002427" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "taxable_amount": "6.87559535", + "tax_amount": "0.46410269" + } + ] + } + ], + "applications": [ + { + "uid": "cdt_8m9vbdbdwd28n", + "transaction_time": "2018-12-31T21:19:28Z", + "invoice_uid": "inv_8k5jvdzct4hb2", + "memo": "Refund for overpayment", + "applied_amount": "200.5" + } + ], + "refunds": [ + { + "transaction_id": 329, + "payment_id": 39, + "memo": "Refund for overpayment", + "original_amount": "524.9", + "applied_amount": "200.5" + } + ] } ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`NestedErrorResponseException`](../../doc/models/nested-error-response-exception.md) | +# Record Payment for Subscription -# Send Invoice +Record an external payment made against a subscription that will pay partially or in full one or more invoices. -This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. +Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. -Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. +Excess payment will result in the creation of a prepayment on the Invoice Account. -On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. +Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. ```csharp -SendInvoiceAsync( - string uid, - Models.SendInvoiceRequest body = null) +RecordPaymentForSubscriptionAsync( + int subscriptionId, + Models.RecordPaymentRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`SendInvoiceRequest`](../../doc/models/send-invoice-request.md) | Body, Optional | - | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`RecordPaymentRequest`](../../doc/models/record-payment-request.md) | Body, Optional | - | ## Response Type -`Task` +[`Task`](../../doc/models/payment-response.md) ## Example Usage ```csharp -string uid = "uid0"; -SendInvoiceRequest body = new SendInvoiceRequest +int subscriptionId = 222; +RecordPaymentRequest body = new RecordPaymentRequest { - RecipientEmails = new List - { - "user0@example.com", - }, - CcRecipientEmails = new List - { - "user1@example.com", - }, - BccRecipientEmails = new List + Payment = new CreatePayment { - "user2@example.com", + Amount = "10.0", + Memo = "to pay the bills", + PaymentDetails = "check number 8675309", + PaymentMethod = "check", }, }; try { - await invoicesController.SendInvoiceAsync( - uid, + PaymentResponse result = await invoicesController.RecordPaymentForSubscriptionAsync( + subscriptionId, body ); } @@ -2799,6 +2819,32 @@ catch (ApiException e) } ``` +## Example Response *(as JSON)* + +```json +{ + "paid_invoices": [ + { + "invoice_uid": "xyz_012345678", + "status": "paid", + "due_amount": "0.0", + "paid_amount": "50.0" + }, + { + "invoice_uid": "xyz_012345678", + "status": "paid", + "due_amount": "0.0", + "paid_amount": "50.0" + } + ], + "prepayment": { + "subscription_id": "123456", + "amount_in_cents": "5000", + "ending_balance_in_cents": "5000" + } +} +``` + ## Errors | HTTP Status Code | Error Description | Exception Class | @@ -2806,14 +2852,23 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Preview Customer Information Changes +# Reopen Invoice -Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. +This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). -The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. +Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways: + +- Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.) +- Recording a payment directly against the invoice + +A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. + +### Reopening Consolidated Invoices + +When reopening a consolidated invoice, all of its canceled segments will also be reopened. ```csharp -PreviewCustomerInformationChangesAsync( +ReopenInvoiceAsync( string uid) ``` @@ -2825,7 +2880,7 @@ PreviewCustomerInformationChangesAsync( ## Response Type -[`Task`](../../doc/models/customer-changes-preview-response.md) +[`Task`](../../doc/models/invoice.md) ## Example Usage @@ -2833,7 +2888,7 @@ PreviewCustomerInformationChangesAsync( string uid = "uid0"; try { - CustomerChangesPreviewResponse result = await invoicesController.PreviewCustomerInformationChangesAsync(uid); + Invoice result = await invoicesController.ReopenInvoiceAsync(uid); } catch (ApiException e) { @@ -2842,64 +2897,11 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -{ - "changes": { - "payer": { - "before": { - "last_name": "Beatty" - }, - "after": { - "last_name": "Doe" - } - }, - "shipping_address": { - "before": { - "line2": "Suite 703" - }, - "after": { - "line2": "Suite 702" - } - }, - "billing_address": { - "before": { - "line2": "Suite 703" - }, - "after": { - "line2": "Suite 702" - } - }, - "custom_fields": { - "before": [ - { - "owner_id": 1002, - "owner_type": "Customer", - "name": "Color", - "value": "blue", - "metadatum_id": 20 - } - ], - "after": [ - { - "owner_id": 1002, - "owner_type": "Customer", - "name": "Color", - "value": "green", - "metadatum_id": 20 - } - ] - } - } -} -``` - ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | @@ -2997,7 +2999,7 @@ catch (ApiException e) "line_items": [ { "description": "qui", - "price_point_id": -95020509, + "price_point_id": 123, "tax_amount": "occaecat deserunt veniam", "subtotal_amount": "commodo consequat tempor et Duis" }, @@ -3008,15 +3010,15 @@ catch (ApiException e) { "price_point_id": 94750853, "product_id": 79058036, - "tax_amount": "Duis", - "subtotal_amount": "irure officia ipsum" + "tax_amount": "1.0", + "subtotal_amount": "128.5" }, { "unit_price": "eiusmod consequat ut nostrud", "tax_amount": "quis nulla proident" }, { - "period_range_end": "ut dolor", + "period_range_end": "2022-02-02", "product_id": 57352537, "description": "minim in dolore Ut Excepteur", "uid": "sit qui in ullamco anim" @@ -3049,7 +3051,7 @@ catch (ApiException e) "credits": [ { "uid": "exercitation eiusmod", - "transaction_time": "Lorem ea", + "transaction_time": "2024-01-23T13:51:27Z", "credit_note_number": "qui fugiat labore laborum", "credit_note_uid": "ipsum sunt" }, @@ -3071,7 +3073,7 @@ catch (ApiException e) "memo": "enim Excepteur Lorem magna sit" }, { - "transaction_time": "deserunt", + "transaction_time": "2024-01-23T13:51:27Z", "prepayment": false, "payment_method": { "details": "labore ut et", @@ -3136,24 +3138,18 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Issue Invoice - -This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. - -You cannot issue a pending child invoice that was created for a member subscription in a group. +# Send Invoice -For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. +This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. -For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value: +Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. -- `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. -- `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. -- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). +On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. ```csharp -IssueInvoiceAsync( +SendInvoiceAsync( string uid, - Models.IssueInvoiceRequest body = null) + Models.SendInvoiceRequest body = null) ``` ## Parameters @@ -3161,24 +3157,35 @@ IssueInvoiceAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`IssueInvoiceRequest`](../../doc/models/issue-invoice-request.md) | Body, Optional | - | +| `body` | [`SendInvoiceRequest`](../../doc/models/send-invoice-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/invoice.md) +`Task` ## Example Usage ```csharp string uid = "uid0"; -IssueInvoiceRequest body = new IssueInvoiceRequest +SendInvoiceRequest body = new SendInvoiceRequest { - OnFailedPayment = FailedPaymentAction.LeaveOpenInvoice, + RecipientEmails = new List + { + "user0@example.com", + }, + CcRecipientEmails = new List + { + "user1@example.com", + }, + BccRecipientEmails = new List + { + "user2@example.com", + }, }; try { - Invoice result = await invoicesController.IssueInvoiceAsync( + await invoicesController.SendInvoiceAsync( uid, body ); @@ -3194,6 +3201,5 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | diff --git a/doc/controllers/offers.md b/doc/controllers/offers.md index d194bf4..0ce59a5 100644 --- a/doc/controllers/offers.md +++ b/doc/controllers/offers.md @@ -10,11 +10,116 @@ OffersController offersController = client.OffersController; ## Methods -* [Create Offer](../../doc/controllers/offers.md#create-offer) -* [List Offers](../../doc/controllers/offers.md#list-offers) * [Read Offers](../../doc/controllers/offers.md#read-offers) -* [Archive Offer](../../doc/controllers/offers.md#archive-offer) * [Unarchive Offer](../../doc/controllers/offers.md#unarchive-offer) +* [Archive Offer](../../doc/controllers/offers.md#archive-offer) +* [Create Offer](../../doc/controllers/offers.md#create-offer) +* [List Offers](../../doc/controllers/offers.md#list-offers) + + +# Read Offers + +This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. + +```csharp +ReadOffersAsync( + int offerId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `offerId` | `int` | Template, Required | The Chargify id of the offer | + +## Response Type + +[`Task`](../../doc/models/offer-response.md) + +## Example Usage + +```csharp +int offerId = 130; +try +{ + OfferResponse result = await offersController.ReadOffersAsync(offerId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + +# Unarchive Offer + +Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. + +```csharp +UnarchiveOfferAsync( + int offerId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `offerId` | `int` | Template, Required | The Chargify id of the offer | + +## Response Type + +`Task` + +## Example Usage + +```csharp +int offerId = 130; +try +{ + await offersController.UnarchiveOfferAsync(offerId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + +# Archive Offer + +Archive an existing offer. Please provide an `offer_id` in order to archive the correct item. + +```csharp +ArchiveOfferAsync( + int offerId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `offerId` | `int` | Template, Required | The Chargify id of the offer | + +## Response Type + +`Task` + +## Example Usage + +```csharp +int offerId = 130; +try +{ + await offersController.ArchiveOfferAsync(offerId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` # Create Offer @@ -132,7 +237,7 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorMapResponseException`](../../doc/models/error-map-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | # List Offers @@ -233,108 +338,3 @@ catch (ApiException e) } ``` - -# Read Offers - -This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. - -```csharp -ReadOffersAsync( - int offerId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `offerId` | `int` | Template, Required | The Chargify id of the offer | - -## Response Type - -[`Task`](../../doc/models/offer-response.md) - -## Example Usage - -```csharp -int offerId = 130; -try -{ - OfferResponse result = await offersController.ReadOffersAsync(offerId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - -# Archive Offer - -Archive an existing offer. Please provide an `offer_id` in order to archive the correct item. - -```csharp -ArchiveOfferAsync( - int offerId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `offerId` | `int` | Template, Required | The Chargify id of the offer | - -## Response Type - -`Task` - -## Example Usage - -```csharp -int offerId = 130; -try -{ - await offersController.ArchiveOfferAsync(offerId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - -# Unarchive Offer - -Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. - -```csharp -UnarchiveOfferAsync( - int offerId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `offerId` | `int` | Template, Required | The Chargify id of the offer | - -## Response Type - -`Task` - -## Example Usage - -```csharp -int offerId = 130; -try -{ - await offersController.UnarchiveOfferAsync(offerId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - diff --git a/doc/controllers/payment-profiles.md b/doc/controllers/payment-profiles.md index f56a920..a3ea563 100644 --- a/doc/controllers/payment-profiles.md +++ b/doc/controllers/payment-profiles.md @@ -10,18 +10,238 @@ PaymentProfilesController paymentProfilesController = client.PaymentProfilesCont ## Methods +* [Update Payment Profile](../../doc/controllers/payment-profiles.md#update-payment-profile) +* [Delete Subscription Group Payment Profile](../../doc/controllers/payment-profiles.md#delete-subscription-group-payment-profile) +* [Send Request Update Payment Email](../../doc/controllers/payment-profiles.md#send-request-update-payment-email) * [Create Payment Profile](../../doc/controllers/payment-profiles.md#create-payment-profile) * [List Payment Profiles](../../doc/controllers/payment-profiles.md#list-payment-profiles) * [Read Payment Profile](../../doc/controllers/payment-profiles.md#read-payment-profile) -* [Update Payment Profile](../../doc/controllers/payment-profiles.md#update-payment-profile) -* [Delete Unused Payment Profile](../../doc/controllers/payment-profiles.md#delete-unused-payment-profile) * [Delete Subscriptions Payment Profile](../../doc/controllers/payment-profiles.md#delete-subscriptions-payment-profile) -* [Verify Bank Account](../../doc/controllers/payment-profiles.md#verify-bank-account) -* [Delete Subscription Group Payment Profile](../../doc/controllers/payment-profiles.md#delete-subscription-group-payment-profile) * [Update Subscription Default Payment Profile](../../doc/controllers/payment-profiles.md#update-subscription-default-payment-profile) +* [Delete Unused Payment Profile](../../doc/controllers/payment-profiles.md#delete-unused-payment-profile) +* [Verify Bank Account](../../doc/controllers/payment-profiles.md#verify-bank-account) * [Update Subscription Group Default Payment Profile](../../doc/controllers/payment-profiles.md#update-subscription-group-default-payment-profile) * [Read One Time Token](../../doc/controllers/payment-profiles.md#read-one-time-token) -* [Send Request Update Payment Email](../../doc/controllers/payment-profiles.md#send-request-update-payment-email) + + +# Update Payment Profile + +## Partial Card Updates + +In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. + +In this case, the following JSON is acceptable: + +``` +{ + "payment_profile": { + "first_name": "Kelly", + "last_name": "Test", + "billing_address": "789 Juniper Court", + "billing_city": "Boulder", + "billing_state": "CO", + "billing_zip": "80302", + "billing_country": "US", + "billing_address_2": null + } +} +``` + +The result will be that you have updated the billing information for the card, yet retained the original card number data. + +## Specific notes on updating payment profiles + +- Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. + +- If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. + +- A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. + +- Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. + +- If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + +```csharp +UpdatePaymentProfileAsync( + int paymentProfileId, + Models.UpdatePaymentProfileRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | +| `body` | [`UpdatePaymentProfileRequest`](../../doc/models/update-payment-profile-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```csharp +int paymentProfileId = 198; +UpdatePaymentProfileRequest body = new UpdatePaymentProfileRequest +{ + PaymentProfile = new UpdatePaymentProfile + { + FirstName = "Graham", + LastName = "Test", + FullNumber = "4111111111111111", + CardType = CardType.Master, + ExpirationMonth = "04", + ExpirationYear = "2030", + CurrentVault = CurrentVault.Bogus, + BillingAddress = "456 Juniper Court", + BillingCity = "Boulder", + BillingState = "CO", + BillingZip = "80302", + BillingCountry = "US", + BillingAddress2 = "billing_address_22", + }, +}; + +try +{ + PaymentProfileResponse result = await paymentProfilesController.UpdatePaymentProfileAsync( + paymentProfileId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "id": 10088716, + "first_name": "Test", + "last_name": "Subscription", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2022, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorStringMapResponseException`](../../doc/models/error-string-map-response-exception.md) | + + +# Delete Subscription Group Payment Profile + +This will delete a Payment Profile belonging to a Subscription Group. + +**Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. + +```csharp +DeleteSubscriptionGroupPaymentProfileAsync( + string uid, + int paymentProfileId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +`Task` + +## Example Usage + +```csharp +string uid = "uid0"; +int paymentProfileId = 198; +try +{ + await paymentProfilesController.DeleteSubscriptionGroupPaymentProfileAsync( + uid, + paymentProfileId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + +# Send Request Update Payment Email + +You can send a "request payment update" email to the customer associated with the subscription. + +If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. + +Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. + +These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. + +```csharp +SendRequestUpdatePaymentEmailAsync( + int subscriptionId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +`Task` + +## Example Usage + +```csharp +int subscriptionId = 222; +try +{ + await paymentProfilesController.SendRequestUpdatePaymentEmailAsync(subscriptionId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | # Create Payment Profile @@ -284,7 +504,7 @@ CreatePaymentProfileAsync( ## Response Type -[`Task`](../../doc/models/create-payment-profile-response.md) +[`Task`](../../doc/models/payment-profile-response.md) ## Example Usage @@ -298,14 +518,14 @@ CreatePaymentProfileRequest body = new CreatePaymentProfileRequest BankName = "Best Bank", BankRoutingNumber = "021000089", BankAccountNumber = "111111111111", - BankAccountType = "checking", - BankAccountHolderType = "business", + BankAccountType = BankAccountType.Checking, + BankAccountHolderType = BankAccountHolderType.Business, }, }; try { - CreatePaymentProfileResponse result = await paymentProfilesController.CreatePaymentProfileAsync(body); + PaymentProfileResponse result = await paymentProfilesController.CreatePaymentProfileAsync(body); } catch (ApiException e) { @@ -322,6 +542,7 @@ catch (ApiException e) "first_name": "Jessica", "last_name": "Test", "card_type": "visa", + "masked_card_number": "XXXX-XXXX-XXXX-1111", "expiration_month": 10, "expiration_year": 2018, "customer_id": 19195410, @@ -369,7 +590,7 @@ ListPaymentProfilesAsync( ## Response Type -[`Task>`](../../doc/models/list-payment-profiles-response.md) +[`Task>`](../../doc/models/payment-profile-response.md) ## Example Usage @@ -382,7 +603,7 @@ ListPaymentProfilesInput listPaymentProfilesInput = new ListPaymentProfilesInput try { - List result = await paymentProfilesController.ListPaymentProfilesAsync(listPaymentProfilesInput); + List result = await paymentProfilesController.ListPaymentProfilesAsync(listPaymentProfilesInput); } catch (ApiException e) { @@ -416,6 +637,7 @@ catch (ApiException e) "bank_account_type": "checking", "bank_account_holder_type": "personal", "payment_type": "bank_account", + "verified": true, "site_gateway_setting_id": 1, "gateway_handle": "handle" } @@ -441,6 +663,7 @@ catch (ApiException e) "bank_account_type": "checking", "bank_account_holder_type": "personal", "payment_type": "bank_account", + "verified": true, "site_gateway_setting_id": 1, "gateway_handle": "handle" } @@ -489,26 +712,26 @@ Example response for Bank Account: ```csharp ReadPaymentProfileAsync( - string paymentProfileId) + int paymentProfileId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `paymentProfileId` | `string` | Template, Required | The Chargify id of the payment profile | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | ## Response Type -[`Task`](../../doc/models/read-payment-profile-response.md) +[`Task`](../../doc/models/payment-profile-response.md) ## Example Usage ```csharp -string paymentProfileId = "payment_profile_id2"; +int paymentProfileId = 198; try { - ReadPaymentProfileResponse result = await paymentProfilesController.ReadPaymentProfileAsync(paymentProfileId); + PaymentProfileResponse result = await paymentProfilesController.ReadPaymentProfileAsync(paymentProfileId); } catch (ApiException e) { @@ -546,90 +769,91 @@ catch (ApiException e) } ``` +## Errors -# Update Payment Profile +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | -## Partial Card Updates -In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. +# Delete Subscriptions Payment Profile -In this case, the following JSON is acceptable: +This will delete a payment profile belonging to the customer on the subscription. + ++ If the customer has multiple subscriptions, the payment profile will be removed from all of them. -``` -{ - "payment_profile": { - "first_name": "Kelly", - "last_name": "Test", - "billing_address": "789 Juniper Court", - "billing_city": "Boulder", - "billing_state": "CO", - "billing_zip": "80302", - "billing_country": "US", - "billing_address_2": null - } -} ++ If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). + +```csharp +DeleteSubscriptionsPaymentProfileAsync( + int subscriptionId, + int paymentProfileId) ``` -The result will be that you have updated the billing information for the card, yet retained the original card number data. +## Parameters -## Specific notes on updating payment profiles +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | -- Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. +## Response Type -- If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. +`Task` -- A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. +## Example Usage -- Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. +```csharp +int subscriptionId = 222; +int paymentProfileId = 198; +try +{ + await paymentProfilesController.DeleteSubscriptionsPaymentProfileAsync( + subscriptionId, + paymentProfileId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -- If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + +# Update Subscription Default Payment Profile + +This will change the default payment profile on the subscription to the existing payment profile with the id specified. + +You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. ```csharp -UpdatePaymentProfileAsync( - string paymentProfileId, - Models.UpdatePaymentProfileRequest body = null) +UpdateSubscriptionDefaultPaymentProfileAsync( + int subscriptionId, + int paymentProfileId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `paymentProfileId` | `string` | Template, Required | The Chargify id of the payment profile | -| `body` | [`UpdatePaymentProfileRequest`](../../doc/models/update-payment-profile-request.md) | Body, Optional | - | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | ## Response Type -[`Task`](../../doc/models/update-payment-profile-response.md) +[`Task`](../../doc/models/payment-profile-response.md) ## Example Usage ```csharp -string paymentProfileId = "payment_profile_id2"; -UpdatePaymentProfileRequest body = new UpdatePaymentProfileRequest -{ - PaymentProfile = new UpdatePaymentProfile - { - FirstName = "Graham", - LastName = "Test", - FullNumber = "4111111111111111", - CardType = CardType.Master, - ExpirationMonth = "04", - ExpirationYear = "2030", - CurrentVault = CurrentVault.Bogus, - BillingAddress = "456 Juniper Court", - BillingCity = "Boulder", - BillingState = "CO", - BillingZip = "80302", - BillingCountry = "US", - BillingAddress2 = "billing_address_22", - }, -}; - +int subscriptionId = 222; +int paymentProfileId = 198; try { - UpdatePaymentProfileResponse result = await paymentProfilesController.UpdatePaymentProfileAsync( - paymentProfileId, - body + PaymentProfileResponse result = await paymentProfilesController.UpdateSubscriptionDefaultPaymentProfileAsync( + subscriptionId, + paymentProfileId ); } catch (ApiException e) @@ -644,21 +868,21 @@ catch (ApiException e) ```json { "payment_profile": { - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", + "id": 10211899, + "first_name": "Amelia", + "last_name": "Example", "masked_card_number": "XXXX-XXXX-XXXX-1", "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, + "expiration_month": 2, + "expiration_year": 2018, + "customer_id": 14399371, "current_vault": "bogus", "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", + "billing_address": "", + "billing_city": "", + "billing_state": "", + "billing_zip": "", + "billing_country": "", "customer_vault_token": null, "billing_address_2": "", "payment_type": "credit_card", @@ -668,6 +892,13 @@ catch (ApiException e) } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + # Delete Unused Payment Profile @@ -677,14 +908,14 @@ If the payment profile is in use by one or more subscriptions or groups, a 422 a ```csharp DeleteUnusedPaymentProfileAsync( - string paymentProfileId) + int paymentProfileId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `paymentProfileId` | `string` | Template, Required | The Chargify id of the payment profile | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | ## Response Type @@ -693,7 +924,7 @@ DeleteUnusedPaymentProfileAsync( ## Example Usage ```csharp -string paymentProfileId = "payment_profile_id2"; +int paymentProfileId = 198; try { await paymentProfilesController.DeleteUnusedPaymentProfileAsync(paymentProfileId); @@ -709,54 +940,10 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Delete Subscriptions Payment Profile - -This will delete a payment profile belonging to the customer on the subscription. - -+ If the customer has multiple subscriptions, the payment profile will be removed from all of them. - -+ If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). - -```csharp -DeleteSubscriptionsPaymentProfileAsync( - int subscriptionId, - string paymentProfileId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `paymentProfileId` | `string` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -`Task` - -## Example Usage - -```csharp -int subscriptionId = 222; -string paymentProfileId = "payment_profile_id2"; -try -{ - await paymentProfilesController.DeleteSubscriptionsPaymentProfileAsync( - subscriptionId, - paymentProfileId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - # Verify Bank Account Submit the two small deposit amounts the customer received in their bank account in order to verify the bank account. (Stripe only) @@ -841,127 +1028,6 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Delete Subscription Group Payment Profile - -This will delete a Payment Profile belonging to a Subscription Group. - -**Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. - -```csharp -DeleteSubscriptionGroupPaymentProfileAsync( - string uid, - string paymentProfileId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `paymentProfileId` | `string` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -`Task` - -## Example Usage - -```csharp -string uid = "uid0"; -string paymentProfileId = "payment_profile_id2"; -try -{ - await paymentProfilesController.DeleteSubscriptionGroupPaymentProfileAsync( - uid, - paymentProfileId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - -# Update Subscription Default Payment Profile - -This will change the default payment profile on the subscription to the existing payment profile with the id specified. - -You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. - -```csharp -UpdateSubscriptionDefaultPaymentProfileAsync( - int subscriptionId, - int paymentProfileId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -[`Task`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```csharp -int subscriptionId = 222; -int paymentProfileId = 198; -try -{ - PaymentProfileResponse result = await paymentProfilesController.UpdateSubscriptionDefaultPaymentProfileAsync( - subscriptionId, - paymentProfileId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "id": 10211899, - "first_name": "Amelia", - "last_name": "Example", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 2, - "expiration_year": 2018, - "customer_id": 14399371, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "", - "billing_city": "", - "billing_state": "", - "billing_zip": "", - "billing_country": "", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - # Update Subscription Group Default Payment Profile This will change the default payment profile on the subscription group to the existing payment profile with the id specified. @@ -973,7 +1039,7 @@ The new payment profile must belong to the subscription group's customer, otherw ```csharp UpdateSubscriptionGroupDefaultPaymentProfileAsync( string uid, - string paymentProfileId) + int paymentProfileId) ``` ## Parameters @@ -981,7 +1047,7 @@ UpdateSubscriptionGroupDefaultPaymentProfileAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `uid` | `string` | Template, Required | The uid of the subscription group | -| `paymentProfileId` | `string` | Template, Required | The Chargify id of the payment profile | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | ## Response Type @@ -991,7 +1057,7 @@ UpdateSubscriptionGroupDefaultPaymentProfileAsync( ```csharp string uid = "uid0"; -string paymentProfileId = "payment_profile_id2"; +int paymentProfileId = 198; try { PaymentProfileResponse result = await paymentProfilesController.UpdateSubscriptionGroupDefaultPaymentProfileAsync( @@ -1086,51 +1152,3 @@ catch (ApiException e) | --- | --- | --- | | 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - -# Send Request Update Payment Email - -You can send a "request payment update" email to the customer associated with the subscription. - -If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. - -Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. - -These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. - -```csharp -SendRequestUpdatePaymentEmailAsync( - int subscriptionId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -`Task` - -## Example Usage - -```csharp -int subscriptionId = 222; -try -{ - await paymentProfilesController.SendRequestUpdatePaymentEmailAsync(subscriptionId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - diff --git a/doc/controllers/product-families.md b/doc/controllers/product-families.md index 8890d49..bdff119 100644 --- a/doc/controllers/product-families.md +++ b/doc/controllers/product-families.md @@ -10,57 +10,46 @@ ProductFamiliesController productFamiliesController = client.ProductFamiliesCont ## Methods -* [List Products for Product Family](../../doc/controllers/product-families.md#list-products-for-product-family) -* [Create Product Family](../../doc/controllers/product-families.md#create-product-family) * [List Product Families](../../doc/controllers/product-families.md#list-product-families) +* [Create Product Family](../../doc/controllers/product-families.md#create-product-family) +* [List Products for Product Family](../../doc/controllers/product-families.md#list-products-for-product-family) * [Read Product Family](../../doc/controllers/product-families.md#read-product-family) -# List Products for Product Family +# List Product Families -This method allows to retrieve a list of Products belonging to a Product Family. +This method allows to retrieve a list of Product Families for a site. ```csharp -ListProductsForProductFamilyAsync( - Models.ListProductsForProductFamilyInput input) +ListProductFamiliesAsync( + Models.ListProductFamiliesInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | | `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | | `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | | `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | | `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | | `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `includeArchived` | `bool?` | Query, Optional | Include archived products | -| `include` | [`ListProductsInclude?`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | -| `filterPrepaidProductPricePointProductPricePointId` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | -| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | ## Response Type -[`Task>`](../../doc/models/product-response.md) +[`Task>`](../../doc/models/product-family-response.md) ## Example Usage ```csharp -ListProductsForProductFamilyInput listProductsForProductFamilyInput = new ListProductsForProductFamilyInput +ListProductFamiliesInput listProductFamiliesInput = new ListProductFamiliesInput { - ProductFamilyId = 140, - Page = 2, - PerPage = 50, DateField = BasicDateField.UpdatedAt, - Include = ListProductsInclude.PrepaidProductPricePoint, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; +}; try { - List result = await productFamiliesController.ListProductsForProductFamilyAsync(listProductsForProductFamilyInput); + List result = await productFamiliesController.ListProductFamiliesAsync(listProductFamiliesInput); } catch (ApiException e) { @@ -74,106 +63,30 @@ catch (ApiException e) ```json [ { - "product": { - "id": 3801242, - "name": "Free product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-04-21T16:08:39-04:00", - "updated_at": "2016-08-03T11:27:53-04:00", - "price_in_cents": 10000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": 0, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 4, - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 283460, - "return_url": null, - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/smcc4j3d2w6h/zero-dollar-product" - } - ], - "product_price_point_name": "Default", - "use_site_exchange_rate": true + "product_family": { + "id": 37, + "name": "Acme Projects", + "description": null, + "handle": "acme-projects", + "accounting_code": null, + "created_at": "2013-02-20T15:05:51-07:00", + "updated_at": "2013-02-20T15:05:51-07:00" } }, { - "product": { - "id": 3858146, - "name": "Calendar Billing Product", - "handle": "calendar-billing-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-07-05T13:07:38-04:00", - "updated_at": "2016-07-05T13:07:38-04:00", - "price_in_cents": 10000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 289193, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/gxdbfxzxhcjq/calendar-billing-product" - } - ], - "product_price_point_name": "Default", - "use_site_exchange_rate": true + "product_family": { + "id": 155, + "name": "Bat Family", + "description": "Another family.", + "handle": "bat-family", + "accounting_code": null, + "created_at": "2014-04-16T12:41:13-06:00", + "updated_at": "2014-04-16T12:41:13-06:00" } } ] ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | - # Create Product Family @@ -240,40 +153,51 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# List Product Families +# List Products for Product Family -This method allows to retrieve a list of Product Families for a site. +This method allows to retrieve a list of Products belonging to a Product Family. ```csharp -ListProductFamiliesAsync( - Models.ListProductFamiliesInput input) +ListProductsForProductFamilyAsync( + Models.ListProductsForProductFamilyInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | | `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | | `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | | `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | | `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | | `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `includeArchived` | `bool?` | Query, Optional | Include archived products | +| `include` | [`ListProductsInclude?`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | +| `filterPrepaidProductPricePointProductPricePointId` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | +| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | ## Response Type -[`Task>`](../../doc/models/product-family-response.md) +[`Task>`](../../doc/models/product-response.md) ## Example Usage ```csharp -ListProductFamiliesInput listProductFamiliesInput = new ListProductFamiliesInput +ListProductsForProductFamilyInput listProductsForProductFamilyInput = new ListProductsForProductFamilyInput { + ProductFamilyId = 140, + Page = 2, + PerPage = 50, DateField = BasicDateField.UpdatedAt, -}; + Include = ListProductsInclude.PrepaidProductPricePoint, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; try { - List result = await productFamiliesController.ListProductFamiliesAsync(listProductFamiliesInput); + List result = await productFamiliesController.ListProductsForProductFamilyAsync(listProductsForProductFamilyInput); } catch (ApiException e) { @@ -287,30 +211,106 @@ catch (ApiException e) ```json [ { - "product_family": { - "id": 37, - "name": "Acme Projects", - "description": null, - "handle": "acme-projects", - "accounting_code": null, - "created_at": "2013-02-20T15:05:51-07:00", - "updated_at": "2013-02-20T15:05:51-07:00" + "product": { + "id": 3801242, + "name": "Free product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-04-21T16:08:39-04:00", + "updated_at": "2016-08-03T11:27:53-04:00", + "price_in_cents": 10000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": 0, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 4, + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 283460, + "return_url": null, + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/smcc4j3d2w6h/zero-dollar-product" + } + ], + "product_price_point_name": "Default", + "use_site_exchange_rate": true } }, { - "product_family": { - "id": 155, - "name": "Bat Family", - "description": "Another family.", - "handle": "bat-family", - "accounting_code": null, - "created_at": "2014-04-16T12:41:13-06:00", - "updated_at": "2014-04-16T12:41:13-06:00" + "product": { + "id": 3858146, + "name": "Calendar Billing Product", + "handle": "calendar-billing-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-07-05T13:07:38-04:00", + "updated_at": "2016-07-05T13:07:38-04:00", + "price_in_cents": 10000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 289193, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/gxdbfxzxhcjq/calendar-billing-product" + } + ], + "product_price_point_name": "Default", + "use_site_exchange_rate": true } } ] ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | + # Read Product Family diff --git a/doc/controllers/product-price-points.md b/doc/controllers/product-price-points.md index 3cdd899..9e02c54 100644 --- a/doc/controllers/product-price-points.md +++ b/doc/controllers/product-price-points.md @@ -11,16 +11,16 @@ ProductPricePointsController productPricePointsController = client.ProductPriceP ## Methods * [Create Product Price Point](../../doc/controllers/product-price-points.md#create-product-price-point) -* [List Product Price Points](../../doc/controllers/product-price-points.md#list-product-price-points) -* [Update Product Price Point](../../doc/controllers/product-price-points.md#update-product-price-point) -* [Read Product Price Point](../../doc/controllers/product-price-points.md#read-product-price-point) * [Archive Product Price Point](../../doc/controllers/product-price-points.md#archive-product-price-point) * [Unarchive Product Price Point](../../doc/controllers/product-price-points.md#unarchive-product-price-point) +* [List All Product Price Points](../../doc/controllers/product-price-points.md#list-all-product-price-points) +* [Update Product Currency Prices](../../doc/controllers/product-price-points.md#update-product-currency-prices) * [Promote Product Price Point to Default](../../doc/controllers/product-price-points.md#promote-product-price-point-to-default) * [Create Product Price Points](../../doc/controllers/product-price-points.md#create-product-price-points) * [Create Product Currency Prices](../../doc/controllers/product-price-points.md#create-product-currency-prices) -* [Update Product Currency Prices](../../doc/controllers/product-price-points.md#update-product-currency-prices) -* [List All Product Price Points](../../doc/controllers/product-price-points.md#list-all-product-price-points) +* [List Product Price Points](../../doc/controllers/product-price-points.md#list-product-price-points) +* [Update Product Price Point](../../doc/controllers/product-price-points.md#update-product-price-point) +* [Read Product Price Point](../../doc/controllers/product-price-points.md#read-product-price-point) # Create Product Price Point @@ -117,100 +117,22 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ProductPricePointErrorResponseException`](../../doc/models/product-price-point-error-response-exception.md) | -# List Product Price Points - -Use this endpoint to retrieve a list of product price points. - -```csharp -ListProductPricePointsAsync( - Models.ListProductPricePointsInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | [`ListProductPricePointsInputProductId`](../../doc/models/containers/list-product-price-points-input-product-id.md) | Template, Required | This is a container for one-of cases. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | -| `currencyPrices` | `bool?` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | -| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | - -## Response Type - -[`Task`](../../doc/models/list-product-price-points-response.md) - -## Example Usage - -```csharp -ListProductPricePointsInput listProductPricePointsInput = new ListProductPricePointsInput -{ - ProductId = ListProductPricePointsInputProductId.FromNumber(124), - Page = 2, - PerPage = 10, -Liquid error: Value cannot be null. (Parameter 'key')}; - -try -{ - ListProductPricePointsResponse result = await productPricePointsController.ListProductPricePointsAsync(listProductPricePointsInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } - ] -} -``` - - -# Update Product Price Point - -Use this endpoint to update a product price point. +# Archive Product Price Point -Note: Custom product price points are not able to be updated. +Use this endpoint to archive a product price point. ```csharp -UpdateProductPricePointAsync( - UpdateProductPricePointProductId productId, - UpdateProductPricePointPricePointId pricePointId, - Models.UpdateProductPricePointRequest body = null) +ArchiveProductPricePointAsync( + ArchiveProductPricePointProductId productId, + ArchiveProductPricePointPricePointId pricePointId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productId` | [`UpdateProductPricePointProductId`](../../doc/models/containers/update-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | -| `pricePointId` | [`UpdateProductPricePointPricePointId`](../../doc/models/containers/update-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | -| `body` | [`UpdateProductPricePointRequest`](../../doc/models/update-product-price-point-request.md) | Body, Optional | - | +| `productId` | [`ArchiveProductPricePointProductId`](../../doc/models/containers/archive-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `pricePointId` | [`ArchiveProductPricePointPricePointId`](../../doc/models/containers/archive-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | ## Response Type @@ -219,25 +141,15 @@ UpdateProductPricePointAsync( ## Example Usage ```csharp -UpdateProductPricePointProductId productId = UpdateProductPricePointProductId.FromNumber(124); - -UpdateProductPricePointPricePointId pricePointId = UpdateProductPricePointPricePointId.FromNumber(188); +ArchiveProductPricePointProductId productId = ArchiveProductPricePointProductId.FromNumber(124); -UpdateProductPricePointRequest body = new UpdateProductPricePointRequest -{ - PricePoint = new UpdateProductPricePoint - { - Handle = "educational", - PriceInCents = 1250L, - }, -}; +ArchiveProductPricePointPricePointId pricePointId = ArchiveProductPricePointPricePointId.FromNumber(188); try { - ProductPricePointResponse result = await productPricePointsController.UpdateProductPricePointAsync( + ProductPricePointResponse result = await productPricePointsController.ArchiveProductPricePointAsync( productId, - pricePointId, - body + pricePointId ); } catch (ApiException e) @@ -274,25 +186,29 @@ catch (ApiException e) } ``` +## Errors -# Read Product Price Point +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -Use this endpoint to retrieve details for a specific product price point. + +# Unarchive Product Price Point + +Use this endpoint to unarchive an archived product price point. ```csharp -ReadProductPricePointAsync( - ReadProductPricePointProductId productId, - ReadProductPricePointPricePointId pricePointId, - bool? currencyPrices = null) +UnarchiveProductPricePointAsync( + int productId, + int pricePointId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productId` | [`ReadProductPricePointProductId`](../../doc/models/containers/read-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | -| `pricePointId` | [`ReadProductPricePointPricePointId`](../../doc/models/containers/read-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | -| `currencyPrices` | `bool?` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | +| `productId` | `int` | Template, Required | The Chargify id of the product to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the product price point | ## Response Type @@ -301,13 +217,11 @@ ReadProductPricePointAsync( ## Example Usage ```csharp -ReadProductPricePointProductId productId = ReadProductPricePointProductId.FromNumber(124); - -ReadProductPricePointPricePointId pricePointId = ReadProductPricePointPricePointId.FromNumber(188); - +int productId = 202; +int pricePointId = 10; try { - ProductPricePointResponse result = await productPricePointsController.ReadProductPricePointAsync( + ProductPricePointResponse result = await productPricePointsController.UnarchiveProductPricePointAsync( productId, pricePointId ); @@ -347,40 +261,49 @@ catch (ApiException e) ``` -# Archive Product Price Point +# List All Product Price Points -Use this endpoint to archive a product price point. +This method allows retrieval of a list of Products Price Points belonging to a Site. ```csharp -ArchiveProductPricePointAsync( - ArchiveProductPricePointProductId productId, - ArchiveProductPricePointPricePointId pricePointId) +ListAllProductPricePointsAsync( + Models.ListAllProductPricePointsInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productId` | [`ArchiveProductPricePointProductId`](../../doc/models/containers/archive-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | -| `pricePointId` | [`ArchiveProductPricePointPricePointId`](../../doc/models/containers/archive-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | +| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `filterArchivedAt` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | +| `filterDateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | +| `filterEndDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `filterEndDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `filterIds` | `List` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | +| `filterStartDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `filterStartDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=catalog,custom`. | +| `include` | [`ListProductsPricePointsInclude?`](../../doc/models/list-products-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | ## Response Type -[`Task`](../../doc/models/product-price-point-response.md) +[`Task`](../../doc/models/list-product-price-points-response.md) ## Example Usage ```csharp -ArchiveProductPricePointProductId productId = ArchiveProductPricePointProductId.FromNumber(124); - -ArchiveProductPricePointPricePointId pricePointId = ArchiveProductPricePointPricePointId.FromNumber(188); +ListAllProductPricePointsInput listAllProductPricePointsInput = new ListAllProductPricePointsInput +{ +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') Include = ListProductsPricePointsInclude.CurrencyPrices, + Page = 2, + PerPage = 50, +}; try { - ProductPricePointResponse result = await productPricePointsController.ArchiveProductPricePointAsync( - productId, - pricePointId - ); + ListProductPricePointsResponse result = await productPricePointsController.ListAllProductPricePointsAsync(listAllProductPricePointsInput); } catch (ApiException e) { @@ -393,26 +316,29 @@ catch (ApiException e) ```json { - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } + "price_points": [ + { + "id": 0, + "name": "My pricepoint", + "handle": "handle", + "price_in_cents": 10, + "interval": 5, + "interval_unit": "month", + "trial_price_in_cents": 10, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "introductory_offer": true, + "initial_charge_in_cents": 0, + "initial_charge_after_trial": true, + "expiration_interval": 0, + "expiration_interval_unit": "month", + "product_id": 1230, + "created_at": "2021-04-02T17:52:09-04:00", + "updated_at": "2021-04-02T17:52:09-04:00", + "use_site_exchange_rate": true + } + ] } ``` @@ -423,37 +349,57 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Unarchive Product Price Point +# Update Product Currency Prices -Use this endpoint to unarchive an archived product price point. +This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. + +When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. + +Note: Currency Prices are not able to be updated for custom product price points. ```csharp -UnarchiveProductPricePointAsync( - int productId, - int pricePointId) +UpdateProductCurrencyPricesAsync( + int productPricePointId, + Models.UpdateCurrencyPricesRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the product price point | +| `productPricePointId` | `int` | Template, Required | The Chargify id of the product price point | +| `body` | [`UpdateCurrencyPricesRequest`](../../doc/models/update-currency-prices-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/product-price-point-response.md) +[`Task`](../../doc/models/currency-prices-response.md) ## Example Usage ```csharp -int productId = 202; -int pricePointId = 10; +int productPricePointId = 234; +UpdateCurrencyPricesRequest body = new UpdateCurrencyPricesRequest +{ + CurrencyPrices = new List + { + new UpdateCurrencyPrice + { + Id = 200, + Price = 15, + }, + new UpdateCurrencyPrice + { + Id = 201, + Price = 5, + }, + }, +}; + try { - ProductPricePointResponse result = await productPricePointsController.UnarchiveProductPricePointAsync( - productId, - pricePointId + CurrencyPricesResponse result = await productPricePointsController.UpdateProductCurrencyPricesAsync( + productPricePointId, + body ); } catch (ApiException e) @@ -467,29 +413,25 @@ catch (ApiException e) ```json { - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } + "currency_prices": [ + { + "id": 123, + "currency": "EUR", + "price": 100, + "formatted_price": "€123,00", + "product_price_point_id": 32669, + "role": "baseline" + } + ] } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + # Promote Product Price Point to Default @@ -725,7 +667,7 @@ CreateProductCurrencyPricesAsync( ## Response Type -[`Task`](../../doc/models/product-price-point-currency-price.md) +[`Task`](../../doc/models/currency-prices-response.md) ## Example Usage @@ -758,7 +700,7 @@ CreateProductCurrencyPricesRequest body = new CreateProductCurrencyPricesRequest try { - ProductPricePointCurrencyPrice result = await productPricePointsController.CreateProductCurrencyPricesAsync( + CurrencyPricesResponse result = await productPricePointsController.CreateProductCurrencyPricesAsync( productPricePointId, body ); @@ -776,9 +718,9 @@ catch (ApiException e) { "currency_prices": [ { - "id": 123, + "id": 100, "currency": "EUR", - "price": 100, + "price": 123, "formatted_price": "€123,00", "product_price_point_id": 32669, "role": "baseline" @@ -791,61 +733,45 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorMapResponseException`](../../doc/models/error-map-response-exception.md) | - +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | -# Update Product Currency Prices - -This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. -When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. +# List Product Price Points -Note: Currency Prices are not able to be updated for custom product price points. +Use this endpoint to retrieve a list of product price points. ```csharp -UpdateProductCurrencyPricesAsync( - int productPricePointId, - Models.UpdateCurrencyPricesRequest body = null) +ListProductPricePointsAsync( + Models.ListProductPricePointsInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productPricePointId` | `int` | Template, Required | The Chargify id of the product price point | -| `body` | [`UpdateCurrencyPricesRequest`](../../doc/models/update-currency-prices-request.md) | Body, Optional | - | +| `productId` | [`ListProductPricePointsInputProductId`](../../doc/models/containers/list-product-price-points-input-product-id.md) | Template, Required | This is a container for one-of cases. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | +| `currencyPrices` | `bool?` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | +| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | ## Response Type -[`Task`](../../doc/models/product-price-point-currency-price.md) +[`Task`](../../doc/models/list-product-price-points-response.md) ## Example Usage ```csharp -int productPricePointId = 234; -UpdateCurrencyPricesRequest body = new UpdateCurrencyPricesRequest +ListProductPricePointsInput listProductPricePointsInput = new ListProductPricePointsInput { - CurrencyPrices = new List - { - new UpdateCurrencyPrice - { - Id = 200, - Price = 15, - }, - new UpdateCurrencyPrice - { - Id = 201, - Price = 5, - }, - }, -}; + ProductId = ListProductPricePointsInputProductId.FromNumber(124), + Page = 2, + PerPage = 10, +Liquid error: Value cannot be null. (Parameter 'key')}; try { - ProductPricePointCurrencyPrice result = await productPricePointsController.UpdateProductCurrencyPricesAsync( - productPricePointId, - body - ); + ListProductPricePointsResponse result = await productPricePointsController.ListProductPricePointsAsync(listProductPricePointsInput); } catch (ApiException e) { @@ -858,69 +784,80 @@ catch (ApiException e) ```json { - "currency_prices": [ + "price_points": [ { - "id": 123, - "currency": "EUR", - "price": 100, - "formatted_price": "€123,00", - "product_price_point_id": 32669, - "role": "baseline" + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" } ] } ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorMapResponseException`](../../doc/models/error-map-response-exception.md) | +# Update Product Price Point -# List All Product Price Points +Use this endpoint to update a product price point. -This method allows retrieval of a list of Products Price Points belonging to a Site. +Note: Custom product price points are not able to be updated. ```csharp -ListAllProductPricePointsAsync( - Models.ListAllProductPricePointsInput input) +UpdateProductPricePointAsync( + UpdateProductPricePointProductId productId, + UpdateProductPricePointPricePointId pricePointId, + Models.UpdateProductPricePointRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `filterArchivedAt` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | -| `filterDateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | -| `filterEndDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `filterEndDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `filterIds` | `List` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | -| `filterStartDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `filterStartDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `filterType` | [`List`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=catalog,custom`. | -| `include` | [`ListProductsPricePointsInclude?`](../../doc/models/list-products-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `productId` | [`UpdateProductPricePointProductId`](../../doc/models/containers/update-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `pricePointId` | [`UpdateProductPricePointPricePointId`](../../doc/models/containers/update-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | +| `body` | [`UpdateProductPricePointRequest`](../../doc/models/update-product-price-point-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/list-product-price-points-response.md) +[`Task`](../../doc/models/product-price-point-response.md) ## Example Usage ```csharp -ListAllProductPricePointsInput listAllProductPricePointsInput = new ListAllProductPricePointsInput +UpdateProductPricePointProductId productId = UpdateProductPricePointProductId.FromNumber(124); + +UpdateProductPricePointPricePointId pricePointId = UpdateProductPricePointPricePointId.FromNumber(188); + +UpdateProductPricePointRequest body = new UpdateProductPricePointRequest { -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') Include = ListProductsPricePointsInclude.CurrencyPrices, - Page = 2, - PerPage = 50, + PricePoint = new UpdateProductPricePoint + { + Handle = "educational", + PriceInCents = 1250L, + }, }; try { - ListProductPricePointsResponse result = await productPricePointsController.ListAllProductPricePointsAsync(listAllProductPricePointsInput); + ProductPricePointResponse result = await productPricePointsController.UpdateProductPricePointAsync( + productId, + pricePointId, + body + ); } catch (ApiException e) { @@ -933,35 +870,98 @@ catch (ApiException e) ```json { - "price_points": [ - { - "id": 0, - "name": "My pricepoint", - "handle": "handle", - "price_in_cents": 10, - "interval": 5, - "interval_unit": "month", - "trial_price_in_cents": 10, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "introductory_offer": true, - "initial_charge_in_cents": 0, - "initial_charge_after_trial": true, - "expiration_interval": 0, - "expiration_interval_unit": "month", - "product_id": 1230, - "created_at": "2021-04-02T17:52:09-04:00", - "updated_at": "2021-04-02T17:52:09-04:00", - "use_site_exchange_rate": true - } - ] + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } } ``` -## Errors -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +# Read Product Price Point + +Use this endpoint to retrieve details for a specific product price point. + +```csharp +ReadProductPricePointAsync( + ReadProductPricePointProductId productId, + ReadProductPricePointPricePointId pricePointId, + bool? currencyPrices = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | [`ReadProductPricePointProductId`](../../doc/models/containers/read-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `pricePointId` | [`ReadProductPricePointPricePointId`](../../doc/models/containers/read-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | +| `currencyPrices` | `bool?` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | + +## Response Type + +[`Task`](../../doc/models/product-price-point-response.md) + +## Example Usage + +```csharp +ReadProductPricePointProductId productId = ReadProductPricePointProductId.FromNumber(124); + +ReadProductPricePointPricePointId pricePointId = ReadProductPricePointPricePointId.FromNumber(188); + +try +{ + ProductPricePointResponse result = await productPricePointsController.ReadProductPricePointAsync( + productId, + pricePointId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } +} +``` diff --git a/doc/controllers/products.md b/doc/controllers/products.md index 4ee96a3..3a2fcc0 100644 --- a/doc/controllers/products.md +++ b/doc/controllers/products.md @@ -10,33 +10,30 @@ ProductsController productsController = client.ProductsController; ## Methods -* [Create Product](../../doc/controllers/products.md#create-product) -* [Read Product](../../doc/controllers/products.md#read-product) -* [Update Product](../../doc/controllers/products.md#update-product) * [Archive Product](../../doc/controllers/products.md#archive-product) * [Read Product by Handle](../../doc/controllers/products.md#read-product-by-handle) * [List Products](../../doc/controllers/products.md#list-products) +* [Read Product](../../doc/controllers/products.md#read-product) +* [Update Product](../../doc/controllers/products.md#update-product) +* [Create Product](../../doc/controllers/products.md#create-product) -# Create Product +# Archive Product -Use this method to create a product within your Chargify site. +Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. -+ [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709) -+ [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations) +This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. ```csharp -CreateProductAsync( - int productFamilyId, - Models.CreateOrUpdateProductRequest body = null) +ArchiveProductAsync( + int productId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | -| `body` | [`CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | +| `productId` | `int` | Template, Required | The Chargify id of the product | ## Response Type @@ -45,30 +42,10 @@ CreateProductAsync( ## Example Usage ```csharp -int productFamilyId = 140; -CreateOrUpdateProductRequest body = new CreateOrUpdateProductRequest -{ - Product = new CreateOrUpdateProduct - { - Name = "Gold Plan", - Description = "This is our gold plan.", - PriceInCents = 1000L, - Interval = 1, - IntervalUnit = IntervalUnit.Month, - Handle = "gold", - AccountingCode = "123", - RequireCreditCard = true, - AutoCreateSignupPage = true, - TaxCode = "D0000000", - }, -}; - +int productId = 202; try { - ProductResponse result = await productsController.CreateProductAsync( - productFamilyId, - body - ); + ProductResponse result = await productsController.ArchiveProductAsync(productId); } catch (ApiException e) { @@ -82,45 +59,40 @@ catch (ApiException e) ```json { "product": { - "id": 4364984, - "name": "Gold Plan", - "handle": "gold", - "description": "This is our gold plan.", - "accounting_code": "123", + "id": 4535638, + "name": "Business Monthly", + "handle": null, + "description": "Business Monthly", + "accounting_code": "", "request_credit_card": true, - "created_at": "2016-11-04T16:31:15-04:00", - "updated_at": "2016-11-04T16:31:15-04:00", - "price_in_cents": 1000, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-08-25T10:25:31-05:00", + "updated_at": "2018-01-16T13:02:44-06:00", + "price_in_cents": 4900, "interval": 1, "interval_unit": "month", - "expiration_interval_unit": null, "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": null, - "archived_at": null, - "require_credit_card": true, - "return_params": null, + "trial_price_in_cents": 0, + "trial_interval": 1, + "trial_interval_unit": "day", + "archived_at": "2018-01-16T13:02:44-06:00", + "require_credit_card": false, + "return_params": "", "taxable": false, - "update_return_url": null, + "update_return_url": "", + "tax_code": "", "initial_charge_after_trial": false, "version_number": 1, - "update_return_params": null, + "update_return_params": "", "product_family": { - "id": 527890, - "name": "Acme Projects", + "id": 1025627, + "name": "Acme Products", "description": "", - "handle": "billing-plans", + "handle": "acme-products", "accounting_code": null }, - "public_signup_pages": [ - { - "id": 301078, - "return_url": null, - "return_params": null, - "url": "https://general-goods.chargify.com/subscribe/ftgbpq7f5qpr/gold" - } - ], + "public_signup_pages": [], "product_price_point_name": "Default" } } @@ -133,20 +105,20 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Read Product +# Read Product by Handle -This endpoint allows you to read the current details of a product that you've created in Chargify. +This method allows to retrieve a Product object by its `api_handle`. ```csharp -ReadProductAsync( - int productId) +ReadProductByHandleAsync( + string apiHandle) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product | +| `apiHandle` | `string` | Template, Required | The handle of the product | ## Response Type @@ -155,10 +127,10 @@ ReadProductAsync( ## Example Usage ```csharp -int productId = 202; +string apiHandle = "api_handle6"; try { - ProductResponse result = await productsController.ReadProductAsync(productId); + ProductResponse result = await productsController.ReadProductByHandleAsync(apiHandle); } catch (ApiException e) { @@ -172,82 +144,114 @@ catch (ApiException e) ```json { "product": { - "id": 4535635, - "name": "Paid Annual Seats", - "handle": "paid-annual-seats", - "description": "Paid annual seats for our commercial enterprise product", - "accounting_code": "paid-annual-seats", + "id": 3903594, + "name": "No cost product", + "handle": "no-cost-product", + "description": "", + "accounting_code": "", "request_credit_card": true, - "expiration_interval": 1, - "expiration_interval_unit": "day", - "created_at": "2017-08-25T10:25:31-05:00", - "updated_at": "2018-01-16T12:58:04-06:00", - "price_in_cents": 10000, - "interval": 12, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-09-02T17:11:29-04:00", + "updated_at": "2016-11-30T11:46:13-05:00", + "price_in_cents": 0, + "interval": 1, "interval_unit": "month", - "initial_charge_in_cents": 4900, - "trial_price_in_cents": 1000, - "trial_interval": 14, - "trial_interval_unit": "day", + "initial_charge_in_cents": null, + "trial_price_in_cents": 5, + "trial_interval": 1, + "trial_interval_unit": "month", "archived_at": null, - "require_credit_card": true, - "return_params": "id={subscription_id}&ref={customer_reference}", - "taxable": true, - "update_return_url": "http://www.example.com", - "tax_code": "D0000000", + "require_credit_card": false, + "return_params": "reference=5678", + "taxable": false, + "update_return_url": "", "initial_charge_after_trial": false, - "version_number": 4, - "update_return_params": "id={subscription_id}&ref={customer_reference}", + "version_number": 1, + "update_return_params": "reference=5678", "product_family": { - "id": 1025627, - "name": "Acme Products", + "id": 527890, + "name": "Acme Projects", "description": "", - "handle": "acme-products", + "handle": "billing-plans", "accounting_code": null }, - "public_signup_pages": [], + "public_signup_pages": [ + { + "id": 281174, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/xgdxtk4vhtbz/no-cost-product" + }, + { + "id": 282270, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/xxqmrgtsbd9k/no-cost-product" + }, + { + "id": 291587, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/pvhwss7zjjnh/no-cost-product" + }, + { + "id": 294832, + "return_url": "http://www.example.com/", + "return_params": "engine=md7a", + "url": "https://general-goods.chargify.com/subscribe/m6tbcq4mcgpw/no-cost-product" + } + ], "product_price_point_name": "Default" } } ``` -# Update Product - -Use this method to change aspects of an existing product. - -### Input Attributes Update Notes - -+ `update_return_params` The parameters we will append to your `update_return_url`. See Return URLs and Parameters - -### Product Price Point +# List Products -Updating a product using this endpoint will create a new price point and set it as the default price point for this product. If you should like to update an existing product price point, that must be done separately. +This method allows to retrieve a list of Products belonging to a Site. ```csharp -UpdateProductAsync( - int productId, - Models.CreateOrUpdateProductRequest body = null) +ListProductsAsync( + Models.ListProductsInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product | -| `body` | [`CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | +| `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | +| `endDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `endDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | +| `startDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `startDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `includeArchived` | `bool?` | Query, Optional | Include archived products. Use in query: `include_archived=true`. | +| `include` | [`ListProductsInclude?`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | +| `filterPrepaidProductPricePointProductPricePointId` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | +| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | ## Response Type -[`Task`](../../doc/models/product-response.md) +[`Task>`](../../doc/models/product-response.md) ## Example Usage ```csharp -int productId = 202; +ListProductsInput listProductsInput = new ListProductsInput +{ + DateField = BasicDateField.UpdatedAt, + Page = 2, + PerPage = 50, + IncludeArchived = true, + Include = ListProductsInclude.PrepaidProductPricePoint, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; + try { - ProductResponse result = await productsController.UpdateProductAsync(productId); + List result = await productsController.ListProductsAsync(listProductsInput); } catch (ApiException e) { @@ -259,66 +263,70 @@ catch (ApiException e) ## Example Response *(as JSON)* ```json -{ - "product": { - "id": 4365034, - "name": "Platinum Plan", - "handle": "platinum", - "description": "This is our platinum plan.", - "accounting_code": "123", - "request_credit_card": true, - "created_at": "2016-11-04T16:34:29-04:00", - "updated_at": "2016-11-04T16:37:11-04:00", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": null, - "archived_at": null, - "require_credit_card": true, - "return_params": null, - "taxable": false, - "update_return_url": null, - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": null, - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 301079, - "return_url": null, - "return_params": null, - "url": "https://general-goods.chargify.com/subscribe/wgyd96tb5pj9/platinum" - } - ], - "product_price_point_name": "Original" +[ + { + "product": { + "id": 0, + "name": "string", + "handle": "string", + "description": "string", + "accounting_code": "string", + "request_credit_card": true, + "expiration_interval": 0, + "expiration_interval_unit": "month", + "created_at": "2023-11-23T10:28:34-05:00", + "updated_at": "2023-11-23T10:28:34-05:00", + "price_in_cents": 0, + "interval": 0, + "interval_unit": "month", + "initial_charge_in_cents": 0, + "trial_price_in_cents": 0, + "trial_interval": 0, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "string", + "taxable": true, + "update_return_url": "string", + "initial_charge_after_trial": true, + "version_number": 0, + "update_return_params": "string", + "product_family": { + "id": 0, + "name": "string", + "handle": "string", + "accounting_code": null, + "description": "string", + "created_at": "string", + "updated_at": "string" + }, + "public_signup_pages": [ + { + "id": 0, + "return_url": "string", + "return_params": "string", + "url": "string" + } + ], + "product_price_point_name": "string", + "request_billing_address": true, + "require_billing_address": true, + "require_shipping_address": true, + "use_site_exchange_rate": true, + "tax_code": "string", + "default_product_price_point_id": 0 + } } -} +] ``` -## Errors -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Archive Product - -Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. +# Read Product -This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. +This endpoint allows you to read the current details of a product that you've created in Chargify. ```csharp -ArchiveProductAsync( +ReadProductAsync( int productId) ``` @@ -338,7 +346,7 @@ ArchiveProductAsync( int productId = 202; try { - ProductResponse result = await productsController.ArchiveProductAsync(productId); + ProductResponse result = await productsController.ReadProductAsync(productId); } catch (ApiException e) { @@ -352,32 +360,32 @@ catch (ApiException e) ```json { "product": { - "id": 4535638, - "name": "Business Monthly", - "handle": null, - "description": "Business Monthly", - "accounting_code": "", + "id": 4535635, + "name": "Paid Annual Seats", + "handle": "paid-annual-seats", + "description": "Paid annual seats for our commercial enterprise product", + "accounting_code": "paid-annual-seats", "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", + "expiration_interval": 1, + "expiration_interval_unit": "day", "created_at": "2017-08-25T10:25:31-05:00", - "updated_at": "2018-01-16T13:02:44-06:00", - "price_in_cents": 4900, - "interval": 1, + "updated_at": "2018-01-16T12:58:04-06:00", + "price_in_cents": 10000, + "interval": 12, "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": 0, - "trial_interval": 1, + "initial_charge_in_cents": 4900, + "trial_price_in_cents": 1000, + "trial_interval": 14, "trial_interval_unit": "day", - "archived_at": "2018-01-16T13:02:44-06:00", - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", + "archived_at": null, + "require_credit_card": true, + "return_params": "id={subscription_id}&ref={customer_reference}", + "taxable": true, + "update_return_url": "http://www.example.com", + "tax_code": "D0000000", "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", + "version_number": 4, + "update_return_params": "id={subscription_id}&ref={customer_reference}", "product_family": { "id": 1025627, "name": "Acme Products", @@ -391,27 +399,31 @@ catch (ApiException e) } ``` -## Errors -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +# Update Product +Use this method to change aspects of an existing product. -# Read Product by Handle +### Input Attributes Update Notes -This method allows to retrieve a Product object by its `api_handle`. ++ `update_return_params` The parameters we will append to your `update_return_url`. See Return URLs and Parameters + +### Product Price Point + +Updating a product using this endpoint will create a new price point and set it as the default price point for this product. If you should like to update an existing product price point, that must be done separately. ```csharp -ReadProductByHandleAsync( - string apiHandle) +UpdateProductAsync( + int productId, + Models.CreateOrUpdateProductRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `apiHandle` | `string` | Template, Required | The handle of the product | +| `productId` | `int` | Template, Required | The Chargify id of the product | +| `body` | [`CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | ## Response Type @@ -420,10 +432,10 @@ ReadProductByHandleAsync( ## Example Usage ```csharp -string apiHandle = "api_handle6"; +int productId = 202; try { - ProductResponse result = await productsController.ReadProductByHandleAsync(apiHandle); + ProductResponse result = await productsController.UpdateProductAsync(productId); } catch (ApiException e) { @@ -437,31 +449,29 @@ catch (ApiException e) ```json { "product": { - "id": 3903594, - "name": "No cost product", - "handle": "no-cost-product", - "description": "", - "accounting_code": "", + "id": 4365034, + "name": "Platinum Plan", + "handle": "platinum", + "description": "This is our platinum plan.", + "accounting_code": "123", "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-09-02T17:11:29-04:00", - "updated_at": "2016-11-30T11:46:13-05:00", - "price_in_cents": 0, + "created_at": "2016-11-04T16:34:29-04:00", + "updated_at": "2016-11-04T16:37:11-04:00", + "price_in_cents": 1000, "interval": 1, "interval_unit": "month", "initial_charge_in_cents": null, - "trial_price_in_cents": 5, - "trial_interval": 1, - "trial_interval_unit": "month", + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": null, "archived_at": null, - "require_credit_card": false, - "return_params": "reference=5678", + "require_credit_card": true, + "return_params": null, "taxable": false, - "update_return_url": "", + "update_return_url": null, "initial_charge_after_trial": false, "version_number": 1, - "update_return_params": "reference=5678", + "update_return_params": null, "product_family": { "id": 527890, "name": "Acme Projects", @@ -471,80 +481,75 @@ catch (ApiException e) }, "public_signup_pages": [ { - "id": 281174, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/xgdxtk4vhtbz/no-cost-product" - }, - { - "id": 282270, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/xxqmrgtsbd9k/no-cost-product" - }, - { - "id": 291587, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/pvhwss7zjjnh/no-cost-product" - }, - { - "id": 294832, - "return_url": "http://www.example.com/", - "return_params": "engine=md7a", - "url": "https://general-goods.chargify.com/subscribe/m6tbcq4mcgpw/no-cost-product" + "id": 301079, + "return_url": null, + "return_params": null, + "url": "https://general-goods.chargify.com/subscribe/wgyd96tb5pj9/platinum" } ], - "product_price_point_name": "Default" + "product_price_point_name": "Original" } } ``` +## Errors -# List Products +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -This method allows to retrieve a list of Products belonging to a Site. + +# Create Product + +Use this method to create a product within your Chargify site. + ++ [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709) ++ [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations) ```csharp -ListProductsAsync( - Models.ListProductsInput input) +CreateProductAsync( + int productFamilyId, + Models.CreateOrUpdateProductRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `dateField` | [`BasicDateField?`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | -| `endDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `endDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | -| `startDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `startDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `includeArchived` | `bool?` | Query, Optional | Include archived products. Use in query: `include_archived=true`. | -| `include` | [`ListProductsInclude?`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | -| `filterPrepaidProductPricePointProductPricePointId` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | -| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | +| `body` | [`CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | ## Response Type -[`Task>`](../../doc/models/product-response.md) +[`Task`](../../doc/models/product-response.md) ## Example Usage ```csharp -ListProductsInput listProductsInput = new ListProductsInput +int productFamilyId = 140; +CreateOrUpdateProductRequest body = new CreateOrUpdateProductRequest { - DateField = BasicDateField.UpdatedAt, - Page = 2, - PerPage = 50, - IncludeArchived = true, - Include = ListProductsInclude.PrepaidProductPricePoint, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; + Product = new CreateOrUpdateProduct + { + Name = "Gold Plan", + Description = "This is our gold plan.", + PriceInCents = 1000L, + Interval = 1, + IntervalUnit = IntervalUnit.Month, + Handle = "gold", + AccountingCode = "123", + RequireCreditCard = true, + AutoCreateSignupPage = true, + TaxCode = "D0000000", + }, +}; try { - List result = await productsController.ListProductsAsync(listProductsInput); + ProductResponse result = await productsController.CreateProductAsync( + productFamilyId, + body + ); } catch (ApiException e) { @@ -556,60 +561,55 @@ catch (ApiException e) ## Example Response *(as JSON)* ```json -[ - { - "product": { - "id": 0, - "name": "string", - "handle": "string", - "description": "string", - "accounting_code": "string", - "request_credit_card": true, - "expiration_interval": 0, - "expiration_interval_unit": "month", - "created_at": "2023-11-23T10:28:34-05:00", - "updated_at": "2023-11-23T10:28:34-05:00", - "price_in_cents": 0, - "interval": 0, - "interval_unit": "month", - "initial_charge_in_cents": 0, - "trial_price_in_cents": 0, - "trial_interval": 0, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "string", - "taxable": true, - "update_return_url": "string", - "initial_charge_after_trial": true, - "version_number": 0, - "update_return_params": "string", - "product_family": { - "id": 0, - "name": "string", - "handle": "string", - "accounting_code": null, - "description": "string", - "created_at": "string", - "updated_at": "string" - }, - "public_signup_pages": [ - { - "id": 0, - "return_url": "string", - "return_params": "string", - "url": "string" - } - ], - "product_price_point_name": "string", - "request_billing_address": true, - "require_billing_address": true, - "require_shipping_address": true, - "use_site_exchange_rate": true, - "tax_code": "string", - "default_product_price_point_id": 0 - } +{ + "product": { + "id": 4364984, + "name": "Gold Plan", + "handle": "gold", + "description": "This is our gold plan.", + "accounting_code": "123", + "request_credit_card": true, + "created_at": "2016-11-04T16:31:15-04:00", + "updated_at": "2016-11-04T16:31:15-04:00", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "expiration_interval_unit": null, + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": null, + "archived_at": null, + "require_credit_card": true, + "return_params": null, + "taxable": false, + "update_return_url": null, + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": null, + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 301078, + "return_url": null, + "return_params": null, + "url": "https://general-goods.chargify.com/subscribe/ftgbpq7f5qpr/gold" + } + ], + "product_price_point_name": "Default" } -] +} ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/proforma-invoices.md b/doc/controllers/proforma-invoices.md index 4a58636..a23dc6c 100644 --- a/doc/controllers/proforma-invoices.md +++ b/doc/controllers/proforma-invoices.md @@ -10,49 +10,53 @@ ProformaInvoicesController proformaInvoicesController = client.ProformaInvoicesC ## Methods -* [Create Consolidated Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-consolidated-proforma-invoice) +* [Void Proforma Invoice](../../doc/controllers/proforma-invoices.md#void-proforma-invoice) +* [Create Signup Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-signup-proforma-invoice) * [List Subscription Group Proforma Invoices](../../doc/controllers/proforma-invoices.md#list-subscription-group-proforma-invoices) -* [Read Proforma Invoice](../../doc/controllers/proforma-invoices.md#read-proforma-invoice) * [Create Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-proforma-invoice) +* [Read Proforma Invoice](../../doc/controllers/proforma-invoices.md#read-proforma-invoice) * [List Proforma Invoices](../../doc/controllers/proforma-invoices.md#list-proforma-invoices) -* [Void Proforma Invoice](../../doc/controllers/proforma-invoices.md#void-proforma-invoice) +* [Create Consolidated Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-consolidated-proforma-invoice) * [Preview Proforma Invoice](../../doc/controllers/proforma-invoices.md#preview-proforma-invoice) -* [Create Signup Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-signup-proforma-invoice) * [Preview Signup Proforma Invoice](../../doc/controllers/proforma-invoices.md#preview-signup-proforma-invoice) -# Create Consolidated Proforma Invoice - -This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. +# Void Proforma Invoice -If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. +This endpoint will void a proforma invoice that has the status "draft". ## Restrictions -Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. +Proforma invoices are only available on Relationship Invoicing sites. + +Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. + +A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. ```csharp -CreateConsolidatedProformaInvoiceAsync( - string uid) +VoidProformaInvoiceAsync( + string proformaInvoiceUid, + Models.VoidInvoiceRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | +| `proformaInvoiceUid` | `string` | Template, Required | The uid of the proforma invoice | +| `body` | [`VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | ## Response Type -`Task` +[`Task`](../../doc/models/proforma-invoice.md) ## Example Usage ```csharp -string uid = "uid0"; +string proformaInvoiceUid = "proforma_invoice_uid4"; try { - await proformaInvoicesController.CreateConsolidatedProformaInvoiceAsync(uid); + ProformaInvoice result = await proformaInvoicesController.VoidProformaInvoiceAsync(proformaInvoiceUid); } catch (ApiException e) { @@ -65,25 +69,30 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# List Subscription Group Proforma Invoices +# Create Signup Proforma Invoice -Only proforma invoices with a `consolidation_level` of parent are returned. +This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. -By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. +Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. + +Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. + +A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. ```csharp -ListSubscriptionGroupProformaInvoicesAsync( - string uid) +CreateSignupProformaInvoiceAsync( + Models.CreateSubscriptionRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | ## Response Type @@ -92,10 +101,23 @@ ListSubscriptionGroupProformaInvoicesAsync( ## Example Usage ```csharp -string uid = "uid0"; +CreateSubscriptionRequest body = new CreateSubscriptionRequest +{ + Subscription = new CreateSubscription + { + ProductHandle = "gold-product", + CustomerAttributes = new CustomerAttributes + { + FirstName = "Myra", + LastName = "Maisel", + Email = "mmaisel@example.com", + }, + }, +}; + try { - ProformaInvoice result = await proformaInvoicesController.ListSubscriptionGroupProformaInvoicesAsync(uid); + ProformaInvoice result = await proformaInvoicesController.CreateSignupProformaInvoiceAsync(body); } catch (ApiException e) { @@ -108,27 +130,26 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | - +| 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | -# Read Proforma Invoice -Use this endpoint to read the details of an existing proforma invoice. +# List Subscription Group Proforma Invoices -## Restrictions +Only proforma invoices with a `consolidation_level` of parent are returned. -Proforma invoices are only available on Relationship Invoicing sites. +By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. ```csharp -ReadProformaInvoiceAsync( - int proformaInvoiceUid) +ListSubscriptionGroupProformaInvoicesAsync( + string uid) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `proformaInvoiceUid` | `int` | Template, Required | The uid of the proforma invoice | +| `uid` | `string` | Template, Required | The uid of the subscription group | ## Response Type @@ -137,10 +158,10 @@ ReadProformaInvoiceAsync( ## Example Usage ```csharp -int proformaInvoiceUid = 242; +string uid = "uid0"; try { - ProformaInvoice result = await proformaInvoicesController.ReadProformaInvoiceAsync(proformaInvoiceUid); + ProformaInvoice result = await proformaInvoicesController.ListSubscriptionGroupProformaInvoicesAsync(uid); } catch (ApiException e) { @@ -203,6 +224,51 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +# Read Proforma Invoice + +Use this endpoint to read the details of an existing proforma invoice. + +## Restrictions + +Proforma invoices are only available on Relationship Invoicing sites. + +```csharp +ReadProformaInvoiceAsync( + int proformaInvoiceUid) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `proformaInvoiceUid` | `int` | Template, Required | The uid of the proforma invoice | + +## Response Type + +[`Task`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```csharp +int proformaInvoiceUid = 242; +try +{ + ProformaInvoice result = await proformaInvoicesController.ReadProformaInvoiceAsync(proformaInvoiceUid); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | + + # List Proforma Invoices By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. @@ -263,42 +329,38 @@ catch (ApiException e) ``` -# Void Proforma Invoice - -This endpoint will void a proforma invoice that has the status "draft". +# Create Consolidated Proforma Invoice -## Restrictions +This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. -Proforma invoices are only available on Relationship Invoicing sites. +If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. -Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. +## Restrictions -A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. +Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. ```csharp -VoidProformaInvoiceAsync( - string proformaInvoiceUid, - Models.VoidInvoiceRequest body = null) +CreateConsolidatedProformaInvoiceAsync( + string uid) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `proformaInvoiceUid` | `string` | Template, Required | The uid of the proforma invoice | -| `body` | [`VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | +| `uid` | `string` | Template, Required | The uid of the subscription group | ## Response Type -[`Task`](../../doc/models/proforma-invoice.md) +`Task` ## Example Usage ```csharp -string proformaInvoiceUid = "proforma_invoice_uid4"; +string uid = "uid0"; try { - ProformaInvoice result = await proformaInvoicesController.VoidProformaInvoiceAsync(proformaInvoiceUid); + await proformaInvoicesController.CreateConsolidatedProformaInvoiceAsync(uid); } catch (ApiException e) { @@ -311,7 +373,6 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | @@ -363,67 +424,6 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Create Signup Proforma Invoice - -This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. - -Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. - -Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. - -A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. - -```csharp -CreateSignupProformaInvoiceAsync( - Models.CreateSubscriptionRequest body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```csharp -CreateSubscriptionRequest body = new CreateSubscriptionRequest -{ - Subscription = new CreateSubscription - { - ProductHandle = "gold-product", - CustomerAttributes = new CustomerAttributes - { - FirstName = "Myra", - LastName = "Maisel", - Email = "mmaisel@example.com", - }, - }, -}; - -try -{ - ProformaInvoice result = await proformaInvoicesController.CreateSignupProformaInvoiceAsync(body); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorMapResponseException`](../../doc/models/error-map-response-exception.md) | - - # Preview Signup Proforma Invoice This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoice previews or preview prepaid subscriptions. @@ -487,5 +487,5 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | | 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorMapResponseException`](../../doc/models/error-map-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | diff --git a/doc/controllers/reason-codes.md b/doc/controllers/reason-codes.md index 46606cd..0c5fe1a 100644 --- a/doc/controllers/reason-codes.md +++ b/doc/controllers/reason-codes.md @@ -10,41 +10,29 @@ ReasonCodesController reasonCodesController = client.ReasonCodesController; ## Methods -* [Create Reason Code](../../doc/controllers/reason-codes.md#create-reason-code) +* [Update Reason Code](../../doc/controllers/reason-codes.md#update-reason-code) * [List Reason Codes](../../doc/controllers/reason-codes.md#list-reason-codes) +* [Create Reason Code](../../doc/controllers/reason-codes.md#create-reason-code) * [Read Reason Code](../../doc/controllers/reason-codes.md#read-reason-code) -* [Update Reason Code](../../doc/controllers/reason-codes.md#update-reason-code) * [Delete Reason Code](../../doc/controllers/reason-codes.md#delete-reason-code) -# Create Reason Code - -# Reason Codes Intro - -ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. - -Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. - -## Reason Code Documentation - -Full documentation on how Reason Codes operate within Chargify can be located under the following links. - -[Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes) - -## Create Reason Code +# Update Reason Code -This method gives a merchant the option to create a reason codes for a given Site. +This method gives a merchant the option to update an existing reason code for a given site. ```csharp -CreateReasonCodeAsync( - Models.CreateReasonCodeRequest body = null) +UpdateReasonCodeAsync( + int reasonCodeId, + Models.UpdateReasonCodeRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `body` | [`CreateReasonCodeRequest`](../../doc/models/create-reason-code-request.md) | Body, Optional | - | +| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | +| `body` | [`UpdateReasonCodeRequest`](../../doc/models/update-reason-code-request.md) | Body, Optional | - | ## Response Type @@ -53,19 +41,10 @@ CreateReasonCodeAsync( ## Example Usage ```csharp -CreateReasonCodeRequest body = new CreateReasonCodeRequest -{ - ReasonCode = new CreateReasonCode - { - Code = "NOTHANKYOU", - Description = "No thank you!", - Position = 5, - }, -}; - +int reasonCodeId = 32; try { - ReasonCodeResponse result = await reasonCodesController.CreateReasonCodeAsync(body); + ReasonCodeResponse result = await reasonCodesController.UpdateReasonCodeAsync(reasonCodeId); } catch (ApiException e) { @@ -78,7 +57,7 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 404 | Not Found | `ApiException` | # List Reason Codes @@ -162,20 +141,34 @@ catch (ApiException e) ``` -# Read Reason Code +# Create Reason Code -This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. +# Reason Codes Intro + +ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. + +Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. + +## Reason Code Documentation + +Full documentation on how Reason Codes operate within Chargify can be located under the following links. + +[Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes) + +## Create Reason Code + +This method gives a merchant the option to create a reason codes for a given Site. ```csharp -ReadReasonCodeAsync( - int reasonCodeId) +CreateReasonCodeAsync( + Models.CreateReasonCodeRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | +| `body` | [`CreateReasonCodeRequest`](../../doc/models/create-reason-code-request.md) | Body, Optional | - | ## Response Type @@ -184,10 +177,19 @@ ReadReasonCodeAsync( ## Example Usage ```csharp -int reasonCodeId = 32; +CreateReasonCodeRequest body = new CreateReasonCodeRequest +{ + ReasonCode = new CreateReasonCode + { + Code = "NOTHANKYOU", + Description = "No thank you!", + Position = 5, + }, +}; + try { - ReasonCodeResponse result = await reasonCodesController.ReadReasonCodeAsync(reasonCodeId); + ReasonCodeResponse result = await reasonCodesController.CreateReasonCodeAsync(body); } catch (ApiException e) { @@ -200,17 +202,16 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Update Reason Code +# Read Reason Code -This method gives a merchant the option to update an existing reason code for a given site. +This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. ```csharp -UpdateReasonCodeAsync( - int reasonCodeId, - Models.UpdateReasonCodeRequest body = null) +ReadReasonCodeAsync( + int reasonCodeId) ``` ## Parameters @@ -218,7 +219,6 @@ UpdateReasonCodeAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | -| `body` | [`UpdateReasonCodeRequest`](../../doc/models/update-reason-code-request.md) | Body, Optional | - | ## Response Type @@ -230,7 +230,7 @@ UpdateReasonCodeAsync( int reasonCodeId = 32; try { - ReasonCodeResponse result = await reasonCodesController.UpdateReasonCodeAsync(reasonCodeId); + ReasonCodeResponse result = await reasonCodesController.ReadReasonCodeAsync(reasonCodeId); } catch (ApiException e) { diff --git a/doc/controllers/sales-commissions.md b/doc/controllers/sales-commissions.md index a09d2f7..887db09 100644 --- a/doc/controllers/sales-commissions.md +++ b/doc/controllers/sales-commissions.md @@ -10,99 +10,11 @@ SalesCommissionsController salesCommissionsController = client.SalesCommissionsC ## Methods -* [List Sales Commission Settings](../../doc/controllers/sales-commissions.md#list-sales-commission-settings) * [List Sales Reps](../../doc/controllers/sales-commissions.md#list-sales-reps) +* [List Sales Commission Settings](../../doc/controllers/sales-commissions.md#list-sales-commission-settings) * [Read Sales Rep](../../doc/controllers/sales-commissions.md#read-sales-rep) -# List Sales Commission Settings - -Endpoint returns subscriptions with associated sales reps - -## Modified Authentication Process - -The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). - -Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. - -> Note: The request is at seller level, it means `<>` variable will be replaced by `app` - -```csharp -ListSalesCommissionSettingsAsync( - Models.ListSalesCommissionSettingsInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | -| `authorization` | `string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | -| `liveMode` | `bool?` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | - -## Response Type - -[`Task>`](../../doc/models/sale-rep-settings.md) - -## Example Usage - -```csharp -ListSalesCommissionSettingsInput listSalesCommissionSettingsInput = new ListSalesCommissionSettingsInput -{ - SellerId = "seller_id8", - Authorization = "Bearer <>", - Page = 2, - PerPage = 100, -}; - -try -{ - List result = await salesCommissionsController.ListSalesCommissionSettingsAsync(listSalesCommissionSettingsInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "customer_name": "Ziomek Ziomeczek", - "subscription_id": 81746, - "site_link": "https://chargify9.staging-chargify.com/dashboard", - "site_name": "Chargify", - "subscription_mrr": "$200.00", - "sales_rep_id": 48, - "sales_rep_name": "John Candy" - }, - { - "customer_name": "Ziom Kom", - "subscription_id": 83758, - "site_link": "https://chargify9.staging-chargify.com/dashboard", - "site_name": "Chargify", - "subscription_mrr": "$200.00", - "sales_rep_id": 49, - "sales_rep_name": "Josh Acme" - }, - { - "customer_name": "George Bush", - "subscription_id": 83790, - "site_link": "https://chargify9.staging-chargify.com/dashboard", - "site_name": "Chargify", - "subscription_mrr": "$200.00", - "sales_rep_id": 48, - "sales_rep_name": "John Candy" - } -] -``` - - # List Sales Reps Endpoint returns sales rep list with details @@ -240,6 +152,94 @@ catch (ApiException e) ``` +# List Sales Commission Settings + +Endpoint returns subscriptions with associated sales reps + +## Modified Authentication Process + +The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). + +Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. + +> Note: The request is at seller level, it means `<>` variable will be replaced by `app` + +```csharp +ListSalesCommissionSettingsAsync( + Models.ListSalesCommissionSettingsInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | +| `authorization` | `string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | +| `liveMode` | `bool?` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | + +## Response Type + +[`Task>`](../../doc/models/sale-rep-settings.md) + +## Example Usage + +```csharp +ListSalesCommissionSettingsInput listSalesCommissionSettingsInput = new ListSalesCommissionSettingsInput +{ + SellerId = "seller_id8", + Authorization = "Bearer <>", + Page = 2, + PerPage = 100, +}; + +try +{ + List result = await salesCommissionsController.ListSalesCommissionSettingsAsync(listSalesCommissionSettingsInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "customer_name": "Ziomek Ziomeczek", + "subscription_id": 81746, + "site_link": "https://chargify9.staging-chargify.com/dashboard", + "site_name": "Chargify", + "subscription_mrr": "$200.00", + "sales_rep_id": 48, + "sales_rep_name": "John Candy" + }, + { + "customer_name": "Ziom Kom", + "subscription_id": 83758, + "site_link": "https://chargify9.staging-chargify.com/dashboard", + "site_name": "Chargify", + "subscription_mrr": "$200.00", + "sales_rep_id": 49, + "sales_rep_name": "Josh Acme" + }, + { + "customer_name": "George Bush", + "subscription_id": 83790, + "site_link": "https://chargify9.staging-chargify.com/dashboard", + "site_name": "Chargify", + "subscription_mrr": "$200.00", + "sales_rep_id": 48, + "sales_rep_name": "John Candy" + } +] +``` + + # Read Sales Rep Endpoint returns sales rep and attached subscriptions details. diff --git a/doc/controllers/sites.md b/doc/controllers/sites.md index b91aee9..90ef428 100644 --- a/doc/controllers/sites.md +++ b/doc/controllers/sites.md @@ -10,44 +10,43 @@ SitesController sitesController = client.SitesController; ## Methods -* [Read Site](../../doc/controllers/sites.md#read-site) -* [Clear Site](../../doc/controllers/sites.md#clear-site) * [List Chargify Js Public Keys](../../doc/controllers/sites.md#list-chargify-js-public-keys) +* [Clear Site](../../doc/controllers/sites.md#clear-site) +* [Read Site](../../doc/controllers/sites.md#read-site) -# Read Site - -This endpoint allows you to fetch some site data. - -Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). - -Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. - -#### Relationship invoicing enabled - -If site has RI enabled then you will see more settings like: - - "customer_hierarchy_enabled": true, - "whopays_enabled": true, - "whopays_default_payer": "self" +# List Chargify Js Public Keys -You can read more about these settings here: -[Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) +This endpoint returns public keys used for Chargify.js. ```csharp -ReadSiteAsync() +ListChargifyJsPublicKeysAsync( + Models.ListChargifyJsPublicKeysInput input) ``` +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + ## Response Type -[`Task`](../../doc/models/site-response.md) +[`Task`](../../doc/models/list-public-keys-response.md) ## Example Usage ```csharp +ListChargifyJsPublicKeysInput listChargifyJsPublicKeysInput = new ListChargifyJsPublicKeysInput +{ + Page = 2, + PerPage = 50, +}; + try { - SiteResponse result = await sitesController.ReadSiteAsync(); + ListPublicKeysResponse result = await sitesController.ListChargifyJsPublicKeysAsync(listChargifyJsPublicKeysInput); } catch (ApiException e) { @@ -60,48 +59,18 @@ catch (ApiException e) ```json { - "site": { - "id": 0, - "name": "string", - "subdomain": "string", - "currency": "string", - "seller_id": 0, - "non_primary_currencies": [ - "string" - ], - "relationship_invoicing_enabled": true, - "customer_hierarchy_enabled": true, - "whopays_enabled": true, - "whopays_default_payer": "string", - "default_payment_collection_method": "string", - "organization_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "name": "string", - "phone": "string" - }, - "tax_configuration": { - "kind": "custom", - "fully_configured": true, - "destination_address": "shipping_then_billing" - }, - "net_terms": { - "default_net_terms": 0, - "automatic_net_terms": 0, - "remittance_net_terms": 0, - "net_terms_on_remittance_signups_enabled": false, - "custom_net_terms_enabled": false - }, - "test": true, - "allocation_settings": { - "upgrade_charge": "prorated", - "downgrade_credit": "none", - "accrue_charge": "true" + "chargify_js_keys": [ + { + "public_key": "chjs_ftrxt7c4fv6f74wchjs_5zyn7gnwv", + "requires_security_token": false, + "created_at": "2021-01-01T05:00:00-04:00" } + ], + "meta": { + "total_count": 1, + "current_page": 1, + "total_pages": 1, + "per_page": 10 } } ``` @@ -144,38 +113,39 @@ catch (ApiException e) ``` -# List Chargify Js Public Keys +# Read Site -This endpoint returns public keys used for Chargify.js. +This endpoint allows you to fetch some site data. -```csharp -ListChargifyJsPublicKeysAsync( - Models.ListChargifyJsPublicKeysInput input) -``` +Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). -## Parameters +Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +#### Relationship invoicing enabled + +If site has RI enabled then you will see more settings like: + + "customer_hierarchy_enabled": true, + "whopays_enabled": true, + "whopays_default_payer": "self" + +You can read more about these settings here: +[Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) + +```csharp +ReadSiteAsync() +``` ## Response Type -[`Task`](../../doc/models/list-public-keys-response.md) +[`Task`](../../doc/models/site-response.md) ## Example Usage ```csharp -ListChargifyJsPublicKeysInput listChargifyJsPublicKeysInput = new ListChargifyJsPublicKeysInput -{ - Page = 2, - PerPage = 50, -}; - try { - ListPublicKeysResponse result = await sitesController.ListChargifyJsPublicKeysAsync(listChargifyJsPublicKeysInput); + SiteResponse result = await sitesController.ReadSiteAsync(); } catch (ApiException e) { @@ -188,18 +158,48 @@ catch (ApiException e) ```json { - "chargify_js_keys": [ - { - "public_key": "chjs_ftrxt7c4fv6f74wchjs_5zyn7gnwv", - "requires_security_token": false, - "created_at": "2021-01-01T05:00:00-04:00" + "site": { + "id": 0, + "name": "string", + "subdomain": "string", + "currency": "string", + "seller_id": 0, + "non_primary_currencies": [ + "string" + ], + "relationship_invoicing_enabled": true, + "customer_hierarchy_enabled": true, + "whopays_enabled": true, + "whopays_default_payer": "string", + "default_payment_collection_method": "string", + "organization_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "name": "string", + "phone": "string" + }, + "tax_configuration": { + "kind": "custom", + "fully_configured": true, + "destination_address": "shipping_then_billing" + }, + "net_terms": { + "default_net_terms": 0, + "automatic_net_terms": 0, + "remittance_net_terms": 0, + "net_terms_on_remittance_signups_enabled": false, + "custom_net_terms_enabled": false + }, + "test": true, + "allocation_settings": { + "upgrade_charge": "prorated", + "downgrade_credit": "none", + "accrue_charge": "true" } - ], - "meta": { - "total_count": 1, - "current_page": 1, - "total_pages": 1, - "per_page": 10 } } ``` diff --git a/doc/controllers/subscription-components.md b/doc/controllers/subscription-components.md index a2e0c7c..0bf2d41 100644 --- a/doc/controllers/subscription-components.md +++ b/doc/controllers/subscription-components.md @@ -10,183 +10,23 @@ SubscriptionComponentsController subscriptionComponentsController = client.Subsc ## Methods -* [Read Subscription Component](../../doc/controllers/subscription-components.md#read-subscription-component) -* [List Subscription Components](../../doc/controllers/subscription-components.md#list-subscription-components) * [Update Subscription Components Price Points](../../doc/controllers/subscription-components.md#update-subscription-components-price-points) -* [Reset Subscription Components Price Points](../../doc/controllers/subscription-components.md#reset-subscription-components-price-points) * [Allocate Component](../../doc/controllers/subscription-components.md#allocate-component) -* [List Allocations](../../doc/controllers/subscription-components.md#list-allocations) +* [Update Prepaid Usage Allocation](../../doc/controllers/subscription-components.md#update-prepaid-usage-allocation) +* [Record Event](../../doc/controllers/subscription-components.md#record-event) * [Allocate Components](../../doc/controllers/subscription-components.md#allocate-components) * [Preview Allocations](../../doc/controllers/subscription-components.md#preview-allocations) -* [Update Prepaid Usage Allocation](../../doc/controllers/subscription-components.md#update-prepaid-usage-allocation) -* [Delete Prepaid Usage Allocation](../../doc/controllers/subscription-components.md#delete-prepaid-usage-allocation) * [Create Usage](../../doc/controllers/subscription-components.md#create-usage) +* [Read Subscription Component](../../doc/controllers/subscription-components.md#read-subscription-component) +* [List Subscription Components](../../doc/controllers/subscription-components.md#list-subscription-components) +* [Deactivate Event Based Component](../../doc/controllers/subscription-components.md#deactivate-event-based-component) +* [List Subscription Components for Site](../../doc/controllers/subscription-components.md#list-subscription-components-for-site) +* [Reset Subscription Components Price Points](../../doc/controllers/subscription-components.md#reset-subscription-components-price-points) +* [List Allocations](../../doc/controllers/subscription-components.md#list-allocations) +* [Delete Prepaid Usage Allocation](../../doc/controllers/subscription-components.md#delete-prepaid-usage-allocation) * [List Usages](../../doc/controllers/subscription-components.md#list-usages) * [Activate Event Based Component](../../doc/controllers/subscription-components.md#activate-event-based-component) -* [Deactivate Event Based Component](../../doc/controllers/subscription-components.md#deactivate-event-based-component) -* [Record Event](../../doc/controllers/subscription-components.md#record-event) * [Record Events](../../doc/controllers/subscription-components.md#record-events) -* [List Subscription Components for Site](../../doc/controllers/subscription-components.md#list-subscription-components-for-site) - - -# Read Subscription Component - -This request will list information regarding a specific component owned by a subscription. - -```csharp -ReadSubscriptionComponentAsync( - int subscriptionId, - int componentId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:` | - -## Response Type - -[`Task`](../../doc/models/subscription-component-response.md) - -## Example Usage - -```csharp -int subscriptionId = 222; -int componentId = 222; -try -{ - SubscriptionComponentResponse result = await subscriptionComponentsController.ReadSubscriptionComponentAsync( - subscriptionId, - componentId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "component_id": 193028, - "subscription_id": 14593192, - "allocated_quantity": 1, - "pricing_scheme": "per_unit", - "name": "Users", - "kind": "quantity_based_component", - "unit_name": "Users", - "price_point_id": 1, - "price_point_handle": "top-tier", - "enabled": true - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | - - -# List Subscription Components - -This request will list a subscription's applied components. - -## Archived Components - -When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. - -```csharp -ListSubscriptionComponentsAsync( - Models.ListSubscriptionComponentsInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `dateField` | [`SubscriptionListDateField?`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query `date_field=updated_at`. | -| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | -| `pricePointIds` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | -| `productFamilyIds` | `List` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | -| `sort` | [`ListSubscriptionComponentsSort?`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query `sort=updated_at`. | -| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | -| `include` | [`ListSubscriptionComponentsInclude?`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | -| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | -| `filterCurrencies` | `List` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=EUR,USD`. | - -## Response Type - -[`Task>`](../../doc/models/subscription-component-response.md) - -## Example Usage - -```csharp -ListSubscriptionComponentsInput listSubscriptionComponentsInput = new ListSubscriptionComponentsInput -{ - SubscriptionId = 222, - DateField = SubscriptionListDateField.UpdatedAt, - PricePointIds = IncludeNotNull.NotNull, - ProductFamilyIds = new List - { - 1, - 2, - 3, - }, - Sort = ListSubscriptionComponentsSort.UpdatedAt, - Include = ListSubscriptionComponentsInclude.Subscription, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; - -try -{ - List result = await subscriptionComponentsController.ListSubscriptionComponentsAsync(listSubscriptionComponentsInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "component": { - "component_id": 0, - "subscription_id": 0, - "allocated_quantity": 0, - "pricing_scheme": "per_unit", - "name": "string", - "kind": "quantity_based_component", - "unit_name": "string", - "price_point_id": 0, - "price_point_handle": "string", - "price_point_type": "default", - "price_point_name": "string", - "enabled": true, - "unit_balance": 0, - "id": 0, - "created_at": "2022-02-22T14:07:00-05:00", - "updated_at": "2022-02-22T14:07:00-05:00", - "component_handle": "string", - "archived_at": "string" - } - } -] -``` # Update Subscription Components Price Points @@ -280,15 +120,63 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ComponentPricePointErrorException`](../../doc/models/component-price-point-error-exception.md) | -# Reset Subscription Components Price Points +# Allocate Component -Resets all of a subscription's components to use the current default. +This endpoint creates a new allocation, setting the current allocated quantity for the Component and recording a memo. -**Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. +**Notice**: Allocations can only be updated for Quantity, On/Off, and Prepaid Components. + +## Allocations Documentation + +Full documentation on how to record Allocations in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997). It is focused on how allocations operate within the Chargify UI.It goes into greater detail on how the user interface will react when recording allocations. + +This documentation also goes into greater detail on how proration is taken into consideration when applying component allocations. + +## Proration Schemes + +Changing the allocated quantity of a component mid-period can result in either a Charge or Credit being applied to the subscription. When creating an allocation via the API, you can pass the `upgrade_charge`, `downgrade_credit`, and `accrue_charge` to be applied. + +**Notice:** These proration and accural fields will be ignored for Prepaid Components since this component type always generate charges immediately without proration. + +For background information on prorated components and upgrade/downgrade schemes, see [Setting Component Allocations.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-upgrades-vs-downgrades). +See the tables below for valid values. + +| upgrade_charge | Definition                                                        | +|----------------|-------------------------------------------------------------------| +| `full`         | A charge is added for the full price of the component.            | +| `prorated`     | A charge is added for the prorated price of the component change. | +| `none`         | No charge is added.                                               | + +| downgrade_credit | Definition                                        | +|------------------|---------------------------------------------------| +| `full`           | A full price credit is added for the amount owed. | +| `prorated`       | A prorated credit is added for the amount owed.   | +| `none`           | No charge is added.                               | + +| accrue_charge | Definition                                                                                               | +|---------------|------------------------------------------------------------------------------------------------------------| +| `true`        | Attempt to charge the customer at next renewal. | +| `false`       | Attempt to charge the customer right away. If it fails, the charge will be accrued until the next renewal. | + +### Order of Resolution for upgrade_charge and downgrade_credit + +1. Per allocation in API call (within a single allocation of the `allocations` array) +2. [Component-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997-Component-Allocations#component-allocations-0-0) +3. Allocation API call top level (outside of the `allocations` array) +4. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) + +### Order of Resolution for accrue charge + +1. Allocation API call top level (outside of the `allocations` array) +2. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) + +**NOTE: Proration uses the current price of the component as well as the current tax rates. Changes to either may cause the prorated charge/credit to be wrong.** ```csharp -ResetSubscriptionComponentsPricePointsAsync( - int subscriptionId) +AllocateComponentAsync( + int subscriptionId, + int componentId, + Models.CreateAllocationRequest body = null) ``` ## Parameters @@ -296,18 +184,34 @@ ResetSubscriptionComponentsPricePointsAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `body` | [`CreateAllocationRequest`](../../doc/models/create-allocation-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/subscription-response.md) +[`Task`](../../doc/models/allocation-response.md) ## Example Usage ```csharp int subscriptionId = 222; +int componentId = 222; +CreateAllocationRequest body = new CreateAllocationRequest +{ + Allocation = new CreateAllocation + { + Quantity = 5, + Memo = "Recoding component purchase of Acme Support", + }, +}; + try { - SubscriptionResponse result = await subscriptionComponentsController.ResetSubscriptionComponentsPricePointsAsync(subscriptionId); + AllocationResponse result = await subscriptionComponentsController.AllocateComponentAsync( + subscriptionId, + componentId, + body + ); } catch (ApiException e) { @@ -320,161 +224,57 @@ catch (ApiException e) ```json { - "subscription": { - "id": -80293620, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2023-11-23T10:28:34-05:00", - "created_at": "2023-11-23T10:28:34-05:00", - "updated_at": "2023-11-23T10:28:34-05:00", - "expires_at": null, - "balance_in_cents": 50504234, - "current_period_ends_at": "2023-11-23T10:28:34-05:00", - "next_assessment_at": "2023-11-23T10:28:34-05:00", - "canceled_at": null, - "cancellation_message": "lorem ipsum", - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "remittance", - "snap_day": null, - "cancellation_method": "dunning", - "current_period_started_at": "2023-11-23T10:28:34-05:00", - "previous_state": "active", - "signup_payment_id": -45156092, - "signup_revenue": "do aliquip ea", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": -49740952, - "product_price_in_cents": 87617888, - "product_version_number": 13656635, - "payment_type": null, - "referral_code": null, - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": -26151968, - "customer": { - "id": 15208337, - "first_name": "ipsum culpa in labore eiusmod", - "last_name": "esse", - "organization": null, - "email": "ex eiusmod", - "created_at": "ad occaecat cillum", - "updated_at": "ut aute proident est", - "reference": "laboris ea cupidatat", - "address": null, - "address_2": null, - "city": "id eiusmod proident", - "state": "magna eiusmod anim non", - "zip": null, - "country": null, - "phone": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": "reprehenderit labore voluptate", - "portal_customer_created_at": "nisi aute reprehenderit Excepteur Duis", - "cc_emails": "eiusmod sunt", - "tax_exempt": true - }, - "product": { - "id": -74447756, - "name": "eu mollit nulla ut aute", - "handle": "esse dolor anim", - "description": "Lorem ut et non", - "accounting_code": "nisi", - "request_credit_card": false, - "expiration_interval": 1, - "expiration_interval_unit": "day", - "created_at": "2022-11-23T10:28:34-05:00", - "updated_at": "2022-11-23T10:28:34-05:00", - "price_in_cents": -4151649, - "interval": 20680876, - "interval_unit": "day", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "day", - "archived_at": null, - "require_credit_card": true, - "return_params": "magna eu", - "taxable": true, - "update_return_url": "exercitation in", - "tax_code": "Excepteur aliqua sunt in", - "initial_charge_after_trial": true, - "version_number": 41642597, - "update_return_params": "dolore labore", - "product_family": { - "id": -5356997, - "name": "officia amet Lorem proident enim", - "description": "Duis", - "handle": "ea dolore dolore sunt", - "accounting_code": null - }, - "public_signup_pages": [] + "allocation": { + "component_id": 4034995, + "subscription_id": 23737320, + "quantity": 3, + "previous_quantity": 2, + "memo": "dolore cupidatat elit", + "timestamp": "2022-11-23T10:28:34-05:00", + "proration_upgrade_scheme": "laboris ipsum dolore", + "proration_downgrade_scheme": "eiusmod dolore", + "price_point_id": -69720370, + "previous_price_point_id": -76493052, + "accrue_charge": true, + "upgrade_charge": "full", + "downgrade_credit": "full", + "payment": { + "id": -44566528, + "amount_in_cents": 123, + "success": false, + "memo": "aliqua" } } } ``` +## Errors -# Allocate Component - -This endpoint creates a new allocation, setting the current allocated quantity for the Component and recording a memo. - -**Notice**: Allocations can only be updated for Quantity, On/Off, and Prepaid Components. - -## Allocations Documentation - -Full documentation on how to record Allocations in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997). It is focused on how allocations operate within the Chargify UI.It goes into greater detail on how the user interface will react when recording allocations. - -This documentation also goes into greater detail on how proration is taken into consideration when applying component allocations. - -## Proration Schemes - -Changing the allocated quantity of a component mid-period can result in either a Charge or Credit being applied to the subscription. When creating an allocation via the API, you can pass the `upgrade_charge`, `downgrade_credit`, and `accrue_charge` to be applied. - -**Notice:** These proration and accural fields will be ignored for Prepaid Components since this component type always generate charges immediately without proration. - -For background information on prorated components and upgrade/downgrade schemes, see [Setting Component Allocations.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-upgrades-vs-downgrades). -See the tables below for valid values. - -| upgrade_charge | Definition                                                        | -|----------------|-------------------------------------------------------------------| -| `full`         | A charge is added for the full price of the component.            | -| `prorated`     | A charge is added for the prorated price of the component change. | -| `none`         | No charge is added.                                               | +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -| downgrade_credit | Definition                                        | -|------------------|---------------------------------------------------| -| `full`           | A full price credit is added for the amount owed. | -| `prorated`       | A prorated credit is added for the amount owed.   | -| `none`           | No charge is added.                               | -| accrue_charge | Definition                                                                                               | -|---------------|------------------------------------------------------------------------------------------------------------| -| `true`        | Attempt to charge the customer at next renewal. | -| `false`       | Attempt to charge the customer right away. If it fails, the charge will be accrued until the next renewal. | +# Update Prepaid Usage Allocation -### Order of Resolution for upgrade_charge and downgrade_credit +When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. -1. Per allocation in API call (within a single allocation of the `allocations` array) -2. [Component-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997-Component-Allocations#component-allocations-0-0) -3. Allocation API call top level (outside of the `allocations` array) -4. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) +In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. -### Order of Resolution for accrue charge +## Limitations -1. Allocation API call top level (outside of the `allocations` array) -2. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) +A few limitations exist when changing an allocation's expiration date: -**NOTE: Proration uses the current price of the component as well as the current tax rates. Changes to either may cause the prorated charge/credit to be wrong.** +- An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. +- An expiration date can be changed towards the future with no limitations. +- An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. ```csharp -AllocateComponentAsync( +UpdatePrepaidUsageAllocationAsync( int subscriptionId, int componentId, - Models.CreateAllocationRequest body = null) + int allocationId, + Models.UpdateAllocationExpirationDate body = null) ``` ## Parameters @@ -483,31 +283,33 @@ AllocateComponentAsync( | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | | `componentId` | `int` | Template, Required | The Chargify id of the component | -| `body` | [`CreateAllocationRequest`](../../doc/models/create-allocation-request.md) | Body, Optional | - | +| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | +| `body` | [`UpdateAllocationExpirationDate`](../../doc/models/update-allocation-expiration-date.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/allocation-response.md) +`Task` ## Example Usage ```csharp int subscriptionId = 222; int componentId = 222; -CreateAllocationRequest body = new CreateAllocationRequest +int allocationId = 24; +UpdateAllocationExpirationDate body = new UpdateAllocationExpirationDate { - Allocation = new CreateAllocation + Allocation = new AllocationExpirationDate { - Quantity = 5, - Memo = "Recoding component purchase of Acme Support", + ExpiresAt = "05/07/2021", }, }; try { - AllocationResponse result = await subscriptionComponentsController.AllocateComponentAsync( + await subscriptionComponentsController.UpdatePrepaidUsageAllocationAsync( subscriptionId, componentId, + allocationId, body ); } @@ -518,95 +320,77 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -{ - "allocation": { - "component_id": 4034995, - "subscription_id": 23737320, - "quantity": 3, - "previous_quantity": 2, - "memo": "dolore cupidatat elit", - "timestamp": "2022-11-23T10:28:34-05:00", - "proration_upgrade_scheme": "laboris ipsum dolore", - "proration_downgrade_scheme": "eiusmod dolore", - "price_point_id": -69720370, - "previous_price_point_id": -76493052, - "accrue_charge": true, - "upgrade_charge": "full", - "downgrade_credit": "full", - "payment": { - "id": -44566528, - "amount_in_cents": 123, - "success": false, - "memo": "aliqua" - } - } -} -``` - ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | -# List Allocations +# Record Event -This endpoint returns the 50 most recent Allocations, ordered by most recent first. +## Documentation -## On/Off Components +Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. -When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. +These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. -## Querying data via Chargify gem +This API allows you to stream events into the Chargify data ingestion engine. -You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares) +Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). -```# First way -component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}) -puts component.allocated_quantity -# => 23 +## Record Event -# Second way -component = Chargify::Subscription.find(7).component(1) -puts component.allocated_quantity -# => 23 +Use this endpoint to record a single event. + +*Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:* + +``` +https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle ``` ```csharp -ListAllocationsAsync( - int subscriptionId, - int componentId, - int? page = 1) +RecordEventAsync( + string subdomain, + string apiHandle, + string storeUid = null, + Models.EBBEvent body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `subdomain` | `string` | Template, Required | Your site's subdomain | +| `apiHandle` | `string` | Template, Required | Identifies the Stream for which the event should be published. | +| `storeUid` | `string` | Query, Optional | If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store. | +| `body` | [`EBBEvent`](../../doc/models/ebb-event.md) | Body, Optional | - | ## Response Type -[`Task>`](../../doc/models/allocation-response.md) +`Task` ## Example Usage ```csharp -int subscriptionId = 222; -int componentId = 222; -int? page = 2; +string subdomain = "subdomain4"; +string apiHandle = "api_handle6"; +EBBEvent body = new EBBEvent +{ + Chargify = new ChargifyEBB + { + Timestamp = "2020-02-27T17:45:50-05:00", + SubscriptionId = 1, + }, +}; + try { - List result = await subscriptionComponentsController.ListAllocationsAsync( - subscriptionId, - componentId, - page + await subscriptionComponentsController.RecordEventAsync( + subdomain, + apiHandle, + null, + body ); } catch (ApiException e) @@ -616,44 +400,6 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -[ - { - "allocation": { - "memo": "moving to 7", - "timestamp": "2012-11-20T22:00:37Z", - "quantity": 7, - "previous_quantity": 3, - "component_id": 11960, - "subscription_id": 2585595, - "proration_upgrade_scheme": "no-prorate", - "proration_downgrade_scheme": "no-prorate" - } - }, - { - "allocation": { - "memo": null, - "timestamp": "2012-11-20T21:48:09Z", - "quantity": 3, - "previous_quantity": 0, - "component_id": 11960, - "subscription_id": 2585595, - "proration_upgrade_scheme": "no-prorate", - "proration_downgrade_scheme": "no-prorate" - } - } -] -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - # Allocate Components @@ -942,26 +688,70 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ComponentAllocationErrorException`](../../doc/models/component-allocation-error-exception.md) | -# Update Prepaid Usage Allocation +# Create Usage -When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. +## Documentation -In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. +Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources: -## Limitations ++ [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage) ++ [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status) -A few limitations exist when changing an allocation's expiration date: +You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. -- An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. -- An expiration date can be changed towards the future with no limitations. -- An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. +## Create Usage for Subscription + +This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. + +## Price Point ID usage + +If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. + +You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. + +If an invalid `price_point_id` is submitted, the endpoint will return an error. + +## Deducting Usage + +In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. + +Example: + +Previously recorded: + +```json +{ + "usage": { + "quantity": 5000, + "memo": "Recording 5000 units" + } +} +``` + +At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload: + +```json +{ + "usage": { + "quantity": -5000, + "memo": "Deducting 5000 units" + } +} +``` + +The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. + +## FAQ + +Q. Is it possible to record metered usage for more than one component at a time? + +A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. ```csharp -UpdatePrepaidUsageAllocationAsync( +CreateUsageAsync( int subscriptionId, - int componentId, - int allocationId, - Models.UpdateAllocationExpirationDate body = null) + CreateUsageComponentId componentId, + Models.CreateUsageRequest body = null) ``` ## Parameters @@ -969,34 +759,34 @@ UpdatePrepaidUsageAllocationAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | -| `body` | [`UpdateAllocationExpirationDate`](../../doc/models/update-allocation-expiration-date.md) | Body, Optional | - | +| `componentId` | [`CreateUsageComponentId`](../../doc/models/containers/create-usage-component-id.md) | Template, Required | This is a container for one-of cases. | +| `body` | [`CreateUsageRequest`](../../doc/models/create-usage-request.md) | Body, Optional | - | ## Response Type -`Task` +[`Task`](../../doc/models/usage-response.md) ## Example Usage ```csharp int subscriptionId = 222; -int componentId = 222; -int allocationId = 24; -UpdateAllocationExpirationDate body = new UpdateAllocationExpirationDate +CreateUsageComponentId componentId = CreateUsageComponentId.FromNumber(144); + +CreateUsageRequest body = new CreateUsageRequest { - Allocation = new AllocationExpirationDate + Usage = new CreateUsage { - ExpiresAt = "05/07/2021", + Quantity = 1000, + PricePointId = "149416", + Memo = "My memo", }, }; try { - await subscriptionComponentsController.UpdatePrepaidUsageAllocationAsync( + UsageResponse result = await subscriptionComponentsController.CreateUsageAsync( subscriptionId, componentId, - allocationId, body ); } @@ -1007,31 +797,38 @@ catch (ApiException e) } ``` +## Example Response *(as JSON)* + +```json +{ + "usage": { + "id": 138522957, + "memo": "My memo", + "created_at": "2017-11-13T10:05:32-06:00", + "price_point_id": 149416, + "quantity": 1000, + "component_id": 500093, + "component_handle": "handle", + "subscription_id": 22824464 + } +} +``` + ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | - - -# Delete Prepaid Usage Allocation - -Prepaid Usage components are unique in that their allocations are always additive. In order to reduce a subscription's allocated quantity for a prepaid usage component each allocation must be destroyed individually via this endpoint. +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -## Credit Scheme -By default, destroying an allocation will generate a service credit on the subscription. This behavior can be modified with the optional `credit_scheme` parameter on this endpoint. The accepted values are: +# Read Subscription Component -1. `none`: The allocation will be destroyed and the balances will be updated but no service credit or refund will be created. -2. `credit`: The allocation will be destroyed and the balances will be updated and a service credit will be generated. This is also the default behavior if the `credit_scheme` param is not passed. -3. `refund`: The allocation will be destroyed and the balances will be updated and a refund will be issued along with a Credit Note. +This request will list information regarding a specific component owned by a subscription. ```csharp -DeletePrepaidUsageAllocationAsync( +ReadSubscriptionComponentAsync( int subscriptionId, - int componentId, - int allocationId, - Models.CreditSchemeRequest body = null) + int componentId) ``` ## Parameters @@ -1039,32 +836,22 @@ DeletePrepaidUsageAllocationAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | -| `body` | [`CreditSchemeRequest`](../../doc/models/credit-scheme-request.md) | Body, Optional | - | +| `componentId` | `int` | Template, Required | The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:` | ## Response Type -`Task` +[`Task`](../../doc/models/subscription-component-response.md) ## Example Usage ```csharp int subscriptionId = 222; int componentId = 222; -int allocationId = 24; -CreditSchemeRequest body = new CreditSchemeRequest -{ - CreditScheme = CreditScheme.None, -}; - try { - await subscriptionComponentsController.DeletePrepaidUsageAllocationAsync( + SubscriptionComponentResponse result = await subscriptionComponentsController.ReadSubscriptionComponentAsync( subscriptionId, - componentId, - allocationId, - body + componentId ); } catch (ApiException e) @@ -1074,77 +861,501 @@ catch (ApiException e) } ``` +## Example Response *(as JSON)* + +```json +{ + "component": { + "component_id": 193028, + "subscription_id": 14593192, + "allocated_quantity": 1, + "pricing_scheme": "per_unit", + "name": "Users", + "kind": "quantity_based_component", + "unit_name": "Users", + "price_point_id": 1, + "price_point_handle": "top-tier", + "enabled": true + } +} +``` + ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | - - -# Create Usage - -## Documentation +| 404 | Not Found | `ApiException` | -Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources: -+ [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage) -+ [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status) +# List Subscription Components -You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. +This request will list a subscription's applied components. -## Create Usage for Subscription +## Archived Components -This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. +When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. -## Price Point ID usage +```csharp +ListSubscriptionComponentsAsync( + Models.ListSubscriptionComponentsInput input) +``` -If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. +## Parameters -You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `dateField` | [`SubscriptionListDateField?`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query `date_field=updated_at`. | +| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | +| `pricePointIds` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | +| `productFamilyIds` | `List` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | +| `sort` | [`ListSubscriptionComponentsSort?`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query `sort=updated_at`. | +| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | +| `include` | [`ListSubscriptionComponentsInclude?`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | +| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | +| `filterCurrencies` | `List` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=EUR,USD`. | -If an invalid `price_point_id` is submitted, the endpoint will return an error. +## Response Type -## Deducting Usage +[`Task>`](../../doc/models/subscription-component-response.md) -In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. +## Example Usage -Example: +```csharp +ListSubscriptionComponentsInput listSubscriptionComponentsInput = new ListSubscriptionComponentsInput +{ + SubscriptionId = 222, + DateField = SubscriptionListDateField.UpdatedAt, + PricePointIds = IncludeNotNull.NotNull, + ProductFamilyIds = new List + { + 1, + 2, + 3, + }, + Sort = ListSubscriptionComponentsSort.UpdatedAt, + Include = ListSubscriptionComponentsInclude.Subscription, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; -Previously recorded: +try +{ + List result = await subscriptionComponentsController.ListSubscriptionComponentsAsync(listSubscriptionComponentsInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* ```json -{ - "usage": { - "quantity": 5000, - "memo": "Recording 5000 units" +[ + { + "component": { + "component_id": 0, + "subscription_id": 0, + "allocated_quantity": 0, + "pricing_scheme": "per_unit", + "name": "string", + "kind": "quantity_based_component", + "unit_name": "string", + "price_point_id": 0, + "price_point_handle": "string", + "price_point_type": "default", + "price_point_name": "string", + "enabled": true, + "unit_balance": 0, + "id": 0, + "created_at": "2022-02-22T14:07:00-05:00", + "updated_at": "2022-02-22T14:07:00-05:00", + "component_handle": "string", + "archived_at": "string" + } } +] +``` + + +# Deactivate Event Based Component + +Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. + +```csharp +DeactivateEventBasedComponentAsync( + int subscriptionId, + int componentId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | + +## Response Type + +`Task` + +## Example Usage + +```csharp +int subscriptionId = 222; +int componentId = 222; +try +{ + await subscriptionComponentsController.DeactivateEventBasedComponentAsync( + subscriptionId, + componentId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); } ``` -At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload: + +# List Subscription Components for Site + +This request will list components applied to each subscription. + +```csharp +ListSubscriptionComponentsForSiteAsync( + Models.ListSubscriptionComponentsForSiteInput input) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `sort` | [`ListSubscriptionComponentsSort?`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query: `sort=updated_at`. | +| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `dateField` | [`SubscriptionListDateField?`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query: `date_field=updated_at`. | +| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2011-12-15`. | +| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | +| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2011-12-16`. | +| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-07-01 09:00:05`. | +| `subscriptionIds` | `List` | Query, Optional | Allows fetching components allocation with matching subscription id based on provided ids. Use in query `subscription_ids=1,2,3`. | +| `pricePointIds` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | +| `productFamilyIds` | `List` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | +| `include` | [`ListSubscriptionComponentsInclude?`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | +| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | +| `filterCurrencies` | `List` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=USD,EUR`. | +| `filterSubscriptionStates` | [`List`](../../doc/models/subscription-state-filter.md) | Query, Optional | Allows fetching components allocations that belong to the subscription with matching states based on provided values. To use this filter you also have to include the following param in the request `include=subscription`. Use in query `filter[subscription][states]=active,canceled&include=subscription`. | +| `filterSubscriptionDateField` | [`SubscriptionListDateField?`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionStartDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionStartDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionEndDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionEndDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. To use this filter you also have to include the following param in the request `include=subscription`. | + +## Response Type + +[`Task`](../../doc/models/list-subscription-components-response.md) + +## Example Usage + +```csharp +ListSubscriptionComponentsForSiteInput listSubscriptionComponentsForSiteInput = new ListSubscriptionComponentsForSiteInput +{ + Page = 2, + PerPage = 50, + Sort = ListSubscriptionComponentsSort.UpdatedAt, + DateField = SubscriptionListDateField.UpdatedAt, + SubscriptionIds = new List + { + 1, + 2, + 3, + }, + PricePointIds = IncludeNotNull.NotNull, + ProductFamilyIds = new List + { + 1, + 2, + 3, + }, + Include = ListSubscriptionComponentsInclude.Subscription, +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; + +try +{ + ListSubscriptionComponentsResponse result = await subscriptionComponentsController.ListSubscriptionComponentsForSiteAsync(listSubscriptionComponentsForSiteInput); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + +# Reset Subscription Components Price Points + +Resets all of a subscription's components to use the current default. + +**Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. + +```csharp +ResetSubscriptionComponentsPricePointsAsync( + int subscriptionId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`Task`](../../doc/models/subscription-response.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +try +{ + SubscriptionResponse result = await subscriptionComponentsController.ResetSubscriptionComponentsPricePointsAsync(subscriptionId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* ```json { - "usage": { - "quantity": -5000, - "memo": "Deducting 5000 units" + "subscription": { + "id": -80293620, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2023-11-23T10:28:34-05:00", + "created_at": "2023-11-23T10:28:34-05:00", + "updated_at": "2023-11-23T10:28:34-05:00", + "expires_at": null, + "balance_in_cents": 50504234, + "current_period_ends_at": "2023-11-23T10:28:34-05:00", + "next_assessment_at": "2023-11-23T10:28:34-05:00", + "canceled_at": null, + "cancellation_message": "lorem ipsum", + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "remittance", + "snap_day": null, + "cancellation_method": "dunning", + "current_period_started_at": "2023-11-23T10:28:34-05:00", + "previous_state": "active", + "signup_payment_id": -45156092, + "signup_revenue": "do aliquip ea", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": -49740952, + "product_price_in_cents": 87617888, + "product_version_number": 13656635, + "payment_type": null, + "referral_code": null, + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": -26151968, + "customer": { + "id": 15208337, + "first_name": "ipsum culpa in labore eiusmod", + "last_name": "esse", + "organization": null, + "email": "ex eiusmod", + "created_at": "ad occaecat cillum", + "updated_at": "ut aute proident est", + "reference": "laboris ea cupidatat", + "address": null, + "address_2": null, + "city": "id eiusmod proident", + "state": "magna eiusmod anim non", + "zip": null, + "country": null, + "phone": null, + "portal_invite_last_sent_at": null, + "portal_invite_last_accepted_at": "reprehenderit labore voluptate", + "portal_customer_created_at": "nisi aute reprehenderit Excepteur Duis", + "cc_emails": "eiusmod sunt", + "tax_exempt": true + }, + "product": { + "id": -74447756, + "name": "eu mollit nulla ut aute", + "handle": "esse dolor anim", + "description": "Lorem ut et non", + "accounting_code": "nisi", + "request_credit_card": false, + "expiration_interval": 1, + "expiration_interval_unit": "day", + "created_at": "2022-11-23T10:28:34-05:00", + "updated_at": "2022-11-23T10:28:34-05:00", + "price_in_cents": -4151649, + "interval": 20680876, + "interval_unit": "day", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "day", + "archived_at": null, + "require_credit_card": true, + "return_params": "magna eu", + "taxable": true, + "update_return_url": "exercitation in", + "tax_code": "Excepteur aliqua sunt in", + "initial_charge_after_trial": true, + "version_number": 41642597, + "update_return_params": "dolore labore", + "product_family": { + "id": -5356997, + "name": "officia amet Lorem proident enim", + "description": "Duis", + "handle": "ea dolore dolore sunt", + "accounting_code": null + }, + "public_signup_pages": [] + } } } ``` -The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. -## FAQ +# List Allocations + +This endpoint returns the 50 most recent Allocations, ordered by most recent first. + +## On/Off Components + +When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. + +## Querying data via Chargify gem + +You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares) + +```# First way +component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}) +puts component.allocated_quantity +# => 23 + +# Second way +component = Chargify::Subscription.find(7).component(1) +puts component.allocated_quantity +# => 23 +``` + +```csharp +ListAllocationsAsync( + int subscriptionId, + int componentId, + int? page = 1) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | + +## Response Type + +[`Task>`](../../doc/models/allocation-response.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +int componentId = 222; +int? page = 2; +try +{ + List result = await subscriptionComponentsController.ListAllocationsAsync( + subscriptionId, + componentId, + page + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "allocation": { + "memo": "moving to 7", + "timestamp": "2012-11-20T22:00:37Z", + "quantity": 7, + "previous_quantity": 3, + "component_id": 11960, + "subscription_id": 2585595, + "proration_upgrade_scheme": "no-prorate", + "proration_downgrade_scheme": "no-prorate" + } + }, + { + "allocation": { + "memo": null, + "timestamp": "2012-11-20T21:48:09Z", + "quantity": 3, + "previous_quantity": 0, + "component_id": 11960, + "subscription_id": 2585595, + "proration_upgrade_scheme": "no-prorate", + "proration_downgrade_scheme": "no-prorate" + } + } +] +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Delete Prepaid Usage Allocation -Q. Is it possible to record metered usage for more than one component at a time? +Prepaid Usage components are unique in that their allocations are always additive. In order to reduce a subscription's allocated quantity for a prepaid usage component each allocation must be destroyed individually via this endpoint. -A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. +## Credit Scheme + +By default, destroying an allocation will generate a service credit on the subscription. This behavior can be modified with the optional `credit_scheme` parameter on this endpoint. The accepted values are: + +1. `none`: The allocation will be destroyed and the balances will be updated but no service credit or refund will be created. +2. `credit`: The allocation will be destroyed and the balances will be updated and a service credit will be generated. This is also the default behavior if the `credit_scheme` param is not passed. +3. `refund`: The allocation will be destroyed and the balances will be updated and a refund will be issued along with a Credit Note. ```csharp -CreateUsageAsync( +DeletePrepaidUsageAllocationAsync( int subscriptionId, - CreateUsageComponentId componentId, - Models.CreateUsageRequest body = null) + int componentId, + int allocationId, + Models.CreditSchemeRequest body = null) ``` ## Parameters @@ -1152,34 +1363,31 @@ CreateUsageAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | [`CreateUsageComponentId`](../../doc/models/containers/create-usage-component-id.md) | Template, Required | This is a container for one-of cases. | -| `body` | [`CreateUsageRequest`](../../doc/models/create-usage-request.md) | Body, Optional | - | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | +| `body` | [`CreditSchemeRequest`](../../doc/models/credit-scheme-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/usage-response.md) +`Task` ## Example Usage ```csharp int subscriptionId = 222; -CreateUsageComponentId componentId = CreateUsageComponentId.FromNumber(144); - -CreateUsageRequest body = new CreateUsageRequest +int componentId = 222; +int allocationId = 24; +CreditSchemeRequest body = new CreditSchemeRequest { - Usage = new CreateUsage - { - Quantity = 1000, - PricePointId = "149416", - Memo = "My memo", - }, + CreditScheme = CreditScheme.None, }; try { - UsageResponse result = await subscriptionComponentsController.CreateUsageAsync( + await subscriptionComponentsController.DeletePrepaidUsageAllocationAsync( subscriptionId, componentId, + allocationId, body ); } @@ -1190,28 +1398,11 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -{ - "usage": { - "id": 138522957, - "memo": "My memo", - "created_at": "2017-11-13T10:05:32-06:00", - "price_point_id": 149416, - "quantity": 1000, - "component_id": 500093, - "component_handle": "handle", - "subscription_id": 22824464 - } -} -``` - ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | # List Usages @@ -1355,121 +1546,6 @@ catch (ApiException e) ``` -# Deactivate Event Based Component - -Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. - -```csharp -DeactivateEventBasedComponentAsync( - int subscriptionId, - int componentId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | - -## Response Type - -`Task` - -## Example Usage - -```csharp -int subscriptionId = 222; -int componentId = 222; -try -{ - await subscriptionComponentsController.DeactivateEventBasedComponentAsync( - subscriptionId, - componentId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - -# Record Event - -## Documentation - -Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. - -These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. - -This API allows you to stream events into the Chargify data ingestion engine. - -Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). - -## Record Event - -Use this endpoint to record a single event. - -*Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:* - -``` -https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle -``` - -```csharp -RecordEventAsync( - string subdomain, - string apiHandle, - string storeUid = null, - Models.EBBEvent body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subdomain` | `string` | Template, Required | Your site's subdomain | -| `apiHandle` | `string` | Template, Required | Identifies the Stream for which the event should be published. | -| `storeUid` | `string` | Query, Optional | If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store. | -| `body` | [`EBBEvent`](../../doc/models/ebb-event.md) | Body, Optional | - | - -## Response Type - -`Task` - -## Example Usage - -```csharp -string subdomain = "subdomain4"; -string apiHandle = "api_handle6"; -EBBEvent body = new EBBEvent -{ - Chargify = new ChargifyEBB - { - Timestamp = "2020-02-27T17:45:50-05:00", - SubscriptionId = 1, - }, -}; - -try -{ - await subscriptionComponentsController.RecordEventAsync( - subdomain, - apiHandle, - null, - body - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - # Record Events Use this endpoint to record a collection of events. @@ -1532,79 +1608,3 @@ catch (ApiException e) } ``` - -# List Subscription Components for Site - -This request will list components applied to each subscription. - -```csharp -ListSubscriptionComponentsForSiteAsync( - Models.ListSubscriptionComponentsForSiteInput input) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `sort` | [`ListSubscriptionComponentsSort?`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query: `sort=updated_at`. | -| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `dateField` | [`SubscriptionListDateField?`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query: `date_field=updated_at`. | -| `startDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2011-12-15`. | -| `startDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | -| `endDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2011-12-16`. | -| `endDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-07-01 09:00:05`. | -| `subscriptionIds` | `List` | Query, Optional | Allows fetching components allocation with matching subscription id based on provided ids. Use in query `subscription_ids=1,2,3`. | -| `pricePointIds` | [`IncludeNotNull?`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | -| `productFamilyIds` | `List` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | -| `include` | [`ListSubscriptionComponentsInclude?`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | -| `filterUseSiteExchangeRate` | `bool?` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | -| `filterCurrencies` | `List` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=USD,EUR`. | -| `filterSubscriptionStates` | [`List`](../../doc/models/subscription-state-filter.md) | Query, Optional | Allows fetching components allocations that belong to the subscription with matching states based on provided values. To use this filter you also have to include the following param in the request `include=subscription`. Use in query `filter[subscription][states]=active,canceled&include=subscription`. | -| `filterSubscriptionDateField` | [`SubscriptionListDateField?`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionStartDate` | `string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionStartDatetime` | `string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionEndDate` | `string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionEndDatetime` | `string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. To use this filter you also have to include the following param in the request `include=subscription`. | - -## Response Type - -[`Task`](../../doc/models/list-subscription-components-response.md) - -## Example Usage - -```csharp -ListSubscriptionComponentsForSiteInput listSubscriptionComponentsForSiteInput = new ListSubscriptionComponentsForSiteInput -{ - Page = 2, - PerPage = 50, - Sort = ListSubscriptionComponentsSort.UpdatedAt, - DateField = SubscriptionListDateField.UpdatedAt, - SubscriptionIds = new List - { - 1, - 2, - 3, - }, - PricePointIds = IncludeNotNull.NotNull, - ProductFamilyIds = new List - { - 1, - 2, - 3, - }, - Include = ListSubscriptionComponentsInclude.Subscription, -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')}; - -try -{ - ListSubscriptionComponentsResponse result = await subscriptionComponentsController.ListSubscriptionComponentsForSiteAsync(listSubscriptionComponentsForSiteInput); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - diff --git a/doc/controllers/subscription-group-invoice-account.md b/doc/controllers/subscription-group-invoice-account.md index a6105c0..9a8995e 100644 --- a/doc/controllers/subscription-group-invoice-account.md +++ b/doc/controllers/subscription-group-invoice-account.md @@ -10,65 +10,10 @@ SubscriptionGroupInvoiceAccountController subscriptionGroupInvoiceAccountControl ## Methods -* [Create Subscription Group Prepayment](../../doc/controllers/subscription-group-invoice-account.md#create-subscription-group-prepayment) * [List Prepayments for Subscription Group](../../doc/controllers/subscription-group-invoice-account.md#list-prepayments-for-subscription-group) -* [Issue Subscription Group Service Credits](../../doc/controllers/subscription-group-invoice-account.md#issue-subscription-group-service-credits) +* [Create Subscription Group Prepayment](../../doc/controllers/subscription-group-invoice-account.md#create-subscription-group-prepayment) * [Deduct Subscription Group Service Credits](../../doc/controllers/subscription-group-invoice-account.md#deduct-subscription-group-service-credits) - - -# Create Subscription Group Prepayment - -A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. - -```csharp -CreateSubscriptionGroupPrepaymentAsync( - string uid, - Models.SubscriptionGroupPrepaymentRequest body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`SubscriptionGroupPrepaymentRequest`](../../doc/models/subscription-group-prepayment-request.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/subscription-group-prepayment-response.md) - -## Example Usage - -```csharp -string uid = "uid0"; -try -{ - SubscriptionGroupPrepaymentResponse result = await subscriptionGroupInvoiceAccountController.CreateSubscriptionGroupPrepaymentAsync(uid); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "id": 6049554, - "amount_in_cents": 10000, - "ending_balance_in_cents": 5000, - "entry_type": "Debit", - "memo": "Debit from invoice account." -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +* [Issue Subscription Group Service Credits](../../doc/controllers/subscription-group-invoice-account.md#issue-subscription-group-service-credits) # List Prepayments for Subscription Group @@ -145,14 +90,14 @@ catch (ApiException e) | 404 | Not Found | `ApiException` | -# Issue Subscription Group Service Credits +# Create Subscription Group Prepayment -Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. +A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. ```csharp -IssueSubscriptionGroupServiceCreditsAsync( +CreateSubscriptionGroupPrepaymentAsync( string uid, - Models.IssueServiceCreditRequest body = null) + Models.SubscriptionGroupPrepaymentRequest body = null) ``` ## Parameters @@ -160,31 +105,19 @@ IssueSubscriptionGroupServiceCreditsAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`IssueServiceCreditRequest`](../../doc/models/issue-service-credit-request.md) | Body, Optional | - | +| `body` | [`SubscriptionGroupPrepaymentRequest`](../../doc/models/subscription-group-prepayment-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/service-credit-response.md) +[`Task`](../../doc/models/subscription-group-prepayment-response.md) ## Example Usage ```csharp string uid = "uid0"; -IssueServiceCreditRequest body = new IssueServiceCreditRequest -{ - ServiceCredit = new IssueServiceCredit - { - Amount = IssueServiceCreditAmount.FromPrecision(10), - Memo = "Credit the group account", - }, -}; - try { - ServiceCreditResponse result = await subscriptionGroupInvoiceAccountController.IssueSubscriptionGroupServiceCreditsAsync( - uid, - body - ); + SubscriptionGroupPrepaymentResponse result = await subscriptionGroupInvoiceAccountController.CreateSubscriptionGroupPrepaymentAsync(uid); } catch (ApiException e) { @@ -197,13 +130,11 @@ catch (ApiException e) ```json { - "service_credit": { - "id": 101, - "amount_in_cents": 1000, - "ending_balance_in_cents": 2000, - "entry_type": "Credit", - "memo": "Credit to group account" - } + "id": 6049554, + "amount_in_cents": 10000, + "ending_balance_in_cents": 5000, + "entry_type": "Debit", + "memo": "Debit from invoice account." } ``` @@ -280,3 +211,72 @@ catch (ApiException e) | --- | --- | --- | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + +# Issue Subscription Group Service Credits + +Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. + +```csharp +IssueSubscriptionGroupServiceCreditsAsync( + string uid, + Models.IssueServiceCreditRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`IssueServiceCreditRequest`](../../doc/models/issue-service-credit-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/service-credit-response.md) + +## Example Usage + +```csharp +string uid = "uid0"; +IssueServiceCreditRequest body = new IssueServiceCreditRequest +{ + ServiceCredit = new IssueServiceCredit + { + Amount = IssueServiceCreditAmount.FromPrecision(10), + Memo = "Credit the group account", + }, +}; + +try +{ + ServiceCreditResponse result = await subscriptionGroupInvoiceAccountController.IssueSubscriptionGroupServiceCreditsAsync( + uid, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "service_credit": { + "id": 101, + "amount_in_cents": 1000, + "ending_balance_in_cents": 2000, + "entry_type": "Credit", + "memo": "Credit to group account" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/subscription-group-status.md b/doc/controllers/subscription-group-status.md index 718fd1f..ae31955 100644 --- a/doc/controllers/subscription-group-status.md +++ b/doc/controllers/subscription-group-status.md @@ -11,8 +11,8 @@ SubscriptionGroupStatusController subscriptionGroupStatusController = client.Sub ## Methods * [Cancel Subscriptions in Group](../../doc/controllers/subscription-group-status.md#cancel-subscriptions-in-group) -* [Initiate Delayed Cancellation for Group](../../doc/controllers/subscription-group-status.md#initiate-delayed-cancellation-for-group) * [Stop Delayed Cancellation for Group](../../doc/controllers/subscription-group-status.md#stop-delayed-cancellation-for-group) +* [Initiate Delayed Cancellation for Group](../../doc/controllers/subscription-group-status.md#initiate-delayed-cancellation-for-group) * [Reactivate Subscription Group](../../doc/controllers/subscription-group-status.md#reactivate-subscription-group) @@ -69,14 +69,12 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Initiate Delayed Cancellation for Group - -This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. +# Stop Delayed Cancellation for Group -All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. +Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. ```csharp -InitiateDelayedCancellationForGroupAsync( +StopDelayedCancellationForGroupAsync( string uid) ``` @@ -96,7 +94,7 @@ InitiateDelayedCancellationForGroupAsync( string uid = "uid0"; try { - await subscriptionGroupStatusController.InitiateDelayedCancellationForGroupAsync(uid); + await subscriptionGroupStatusController.StopDelayedCancellationForGroupAsync(uid); } catch (ApiException e) { @@ -112,12 +110,14 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Stop Delayed Cancellation for Group +# Initiate Delayed Cancellation for Group -Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. +This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. + +All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. ```csharp -StopDelayedCancellationForGroupAsync( +InitiateDelayedCancellationForGroupAsync( string uid) ``` @@ -137,7 +137,7 @@ StopDelayedCancellationForGroupAsync( string uid = "uid0"; try { - await subscriptionGroupStatusController.StopDelayedCancellationForGroupAsync(uid); + await subscriptionGroupStatusController.InitiateDelayedCancellationForGroupAsync(uid); } catch (ApiException e) { diff --git a/doc/controllers/subscription-groups.md b/doc/controllers/subscription-groups.md index a2bd92d..01b1b85 100644 --- a/doc/controllers/subscription-groups.md +++ b/doc/controllers/subscription-groups.md @@ -11,13 +11,13 @@ SubscriptionGroupsController subscriptionGroupsController = client.SubscriptionG ## Methods * [Signup With Subscription Group](../../doc/controllers/subscription-groups.md#signup-with-subscription-group) -* [Create Subscription Group](../../doc/controllers/subscription-groups.md#create-subscription-group) +* [Read Subscription Group by Subscription Id](../../doc/controllers/subscription-groups.md#read-subscription-group-by-subscription-id) * [List Subscription Groups](../../doc/controllers/subscription-groups.md#list-subscription-groups) -* [Read Subscription Group](../../doc/controllers/subscription-groups.md#read-subscription-group) -* [Update Subscription Group Members](../../doc/controllers/subscription-groups.md#update-subscription-group-members) * [Delete Subscription Group](../../doc/controllers/subscription-groups.md#delete-subscription-group) -* [Read Subscription Group by Subscription Id](../../doc/controllers/subscription-groups.md#read-subscription-group-by-subscription-id) * [Create Subscription Group Hierarchy](../../doc/controllers/subscription-groups.md#create-subscription-group-hierarchy) +* [Create Subscription Group](../../doc/controllers/subscription-groups.md#create-subscription-group) +* [Read Subscription Group](../../doc/controllers/subscription-groups.md#read-subscription-group) +* [Update Subscription Group Members](../../doc/controllers/subscription-groups.md#update-subscription-group-members) * [Remove Subscription From Group](../../doc/controllers/subscription-groups.md#remove-subscription-from-group) @@ -94,45 +94,34 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupSignupErrorResponseException`](../../doc/models/subscription-group-signup-error-response-exception.md) | -# Create Subscription Group +# Read Subscription Group by Subscription Id -Creates a subscription group with given members. +Use this endpoint to find subscription group associated with subscription. + +If the subscription is not in a group endpoint will return 404 code. ```csharp -CreateSubscriptionGroupAsync( - Models.CreateSubscriptionGroupRequest body = null) +ReadSubscriptionGroupBySubscriptionIdAsync( + string subscriptionId) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `body` | [`CreateSubscriptionGroupRequest`](../../doc/models/create-subscription-group-request.md) | Body, Optional | - | +| `subscriptionId` | `string` | Query, Required | The Chargify id of the subscription associated with the subscription group | ## Response Type -[`Task`](../../doc/models/subscription-group-response.md) +[`Task`](../../doc/models/full-subscription-group-response.md) ## Example Usage ```csharp -CreateSubscriptionGroupRequest body = new CreateSubscriptionGroupRequest -{ - SubscriptionGroup = new CreateSubscriptionGroup - { - SubscriptionId = CreateSubscriptionGroupSubscriptionId.FromNumber(1), - MemberIds = new List - { - 2, - 3, - 4, - }, - }, -}; - +string subscriptionId = "subscription_id0"; try { - SubscriptionGroupResponse result = await subscriptionGroupsController.CreateSubscriptionGroupAsync(body); + FullSubscriptionGroupResponse result = await subscriptionGroupsController.ReadSubscriptionGroupBySubscriptionIdAsync(subscriptionId); } catch (ApiException e) { @@ -145,20 +134,39 @@ catch (ApiException e) ```json { - "subscription_group": { - "customer_id": 1, - "payment_profile": { - "id": 1, - "first_name": "t", - "last_name": "t", - "masked_card_number": "XXXX-XXXX-XXXX-1" + "uid": "grp_939ktzq8v4477", + "scheme": 1, + "customer_id": 400, + "payment_profile_id": 567, + "subscription_ids": [ + 101, + 102, + 103 + ], + "primary_subscription_id": 101, + "next_assessment_at": "2020-08-01T14:00:00-05:00", + "state": "active", + "cancel_at_end_of_period": false, + "customer": { + "first_name": "Mark", + "last_name": "Wannabewahlberg", + "organization": "The Funky Bunch", + "email": "markymark@example.com", + "reference": "4c92223b-bc16-4d0d-87ff-b177a89a2655" + }, + "account_balances": { + "prepayments": { + "balance_in_cents": 0 }, - "payment_collection_method": "automatic", - "subscription_ids": [ - 1, - 2 - ], - "created_at": "2021-01-21T05:47:38-05:00" + "service_credits": { + "balance_in_cents": 0 + }, + "open_invoices": { + "balance_in_cents": 4400 + }, + "pending_discounts": { + "balance_in_cents": 0 + } } } ``` @@ -167,7 +175,7 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | +| 404 | Not Found | `ApiException` | # List Subscription Groups @@ -254,16 +262,13 @@ catch (ApiException e) ``` -# Read Subscription Group - -Use this endpoint to find subscription group details. - -#### Current Billing Amount in Cents +# Delete Subscription Group -Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. +Use this endpoint to delete subscription group. +Only groups without members can be deleted ```csharp -ReadSubscriptionGroupAsync( +DeleteSubscriptionGroupAsync( string uid) ``` @@ -275,7 +280,7 @@ ReadSubscriptionGroupAsync( ## Response Type -[`Task`](../../doc/models/full-subscription-group-response.md) +[`Task`](../../doc/models/delete-subscription-group-response.md) ## Example Usage @@ -283,7 +288,7 @@ ReadSubscriptionGroupAsync( string uid = "uid0"; try { - FullSubscriptionGroupResponse result = await subscriptionGroupsController.ReadSubscriptionGroupAsync(uid); + DeleteSubscriptionGroupResponse result = await subscriptionGroupsController.DeleteSubscriptionGroupAsync(uid); } catch (ApiException e) { @@ -296,62 +301,47 @@ catch (ApiException e) ```json { - "uid": "grp_939ktzq8v4477", - "scheme": 1, - "customer_id": 400, - "payment_profile_id": 567, - "subscription_ids": [ - 101, - 102, - 103 - ], - "primary_subscription_id": 101, - "next_assessment_at": "2020-08-01T14:00:00-05:00", - "state": "active", - "cancel_at_end_of_period": false, - "current_billing_amount_in_cents": 11500, - "customer": { - "first_name": "Mark", - "last_name": "Wannabewahlberg", - "organization": "The Funky Bunch", - "email": "markymark@example.com", - "reference": "4c92223b-bc16-4d0d-87ff-b177a89a2655" - }, - "account_balances": { - "prepayments": { - "balance_in_cents": 0 - }, - "service_credits": { - "balance_in_cents": 0 - }, - "open_invoices": { - "balance_in_cents": 4400 - }, - "pending_discounts": { - "balance_in_cents": 0 - } - } + "uid": "grp_99w5xp9y5xycy", + "deleted": true } ``` +## Errors -# Update Subscription Group Members +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | -Use this endpoint to update subscription group members. -`"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. + +# Create Subscription Group Hierarchy + +For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. + +Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. + +**Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. + +Rather than specifying a customer, the `target` parameter could instead simply have a value of + +* `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer, +* `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or +* `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. + +To create a new subscription into a subscription group, please reference the following: +[Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group) ```csharp -UpdateSubscriptionGroupMembersAsync( - string uid, - Models.UpdateSubscriptionGroupRequest body = null) +CreateSubscriptionGroupHierarchyAsync( + int subscriptionId, + Models.AddSubscriptionToAGroup body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`UpdateSubscriptionGroupRequest`](../../doc/models/update-subscription-group-request.md) | Body, Optional | - | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`AddSubscriptionToAGroup`](../../doc/models/add-subscription-to-a-group.md) | Body, Optional | - | ## Response Type @@ -360,24 +350,31 @@ UpdateSubscriptionGroupMembersAsync( ## Example Usage ```csharp -string uid = "uid0"; -UpdateSubscriptionGroupRequest body = new UpdateSubscriptionGroupRequest +int subscriptionId = 222; +AddSubscriptionToAGroup body = new AddSubscriptionToAGroup { - SubscriptionGroup = new UpdateSubscriptionGroup - { - MemberIds = new List + MGroup = AddSubscriptionToAGroupGroup.FromGroupSettings( + new GroupSettings { - 1, - 2, - 3, - }, - }, + Target = new GroupTarget + { + Type = GroupTargetType.Subscription, + Id = 32987, + }, + Billing = new GroupBilling + { + Accrue = true, + AlignDate = true, + Prorate = true, + }, + } + ), }; try { - SubscriptionGroupResponse result = await subscriptionGroupsController.UpdateSubscriptionGroupMembersAsync( - uid, + SubscriptionGroupResponse result = await subscriptionGroupsController.CreateSubscriptionGroupHierarchyAsync( + subscriptionId, body ); } @@ -393,56 +390,63 @@ catch (ApiException e) ```json { "subscription_group": { - "customer_id": 1, + "customer_id": 130690, "payment_profile": { - "id": 1, - "first_name": "t", - "last_name": "t", - "masked_card_number": "XXXX-XXXX-XXXX-1" + "id": 32055, + "first_name": "Marty", + "last_name": "McFly", + "masked_card_number": "XXXX-XXXX-XXXX-1111" }, - "payment_collection_method": "automatic", "subscription_ids": [ - 1 + 32988, + 33060, + 32986 ], - "created_at": "2021-01-21T05:47:38-05:00" + "created_at": "2018-08-30T17:14:30-04:00" } } ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupUpdateErrorResponseException`](../../doc/models/subscription-group-update-error-response-exception.md) | - -# Delete Subscription Group +# Create Subscription Group -Use this endpoint to delete subscription group. -Only groups without members can be deleted +Creates a subscription group with given members. ```csharp -DeleteSubscriptionGroupAsync( - string uid) +CreateSubscriptionGroupAsync( + Models.CreateSubscriptionGroupRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`CreateSubscriptionGroupRequest`](../../doc/models/create-subscription-group-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/delete-subscription-group-response.md) +[`Task`](../../doc/models/subscription-group-response.md) ## Example Usage ```csharp -string uid = "uid0"; +CreateSubscriptionGroupRequest body = new CreateSubscriptionGroupRequest +{ + SubscriptionGroup = new CreateSubscriptionGroup + { + SubscriptionId = CreateSubscriptionGroupSubscriptionId.FromNumber(1), + MemberIds = new List + { + 2, + 3, + 4, + }, + }, +}; + try { - DeleteSubscriptionGroupResponse result = await subscriptionGroupsController.DeleteSubscriptionGroupAsync(uid); + SubscriptionGroupResponse result = await subscriptionGroupsController.CreateSubscriptionGroupAsync(body); } catch (ApiException e) { @@ -455,8 +459,21 @@ catch (ApiException e) ```json { - "uid": "grp_99w5xp9y5xycy", - "deleted": true + "subscription_group": { + "customer_id": 1, + "payment_profile": { + "id": 1, + "first_name": "t", + "last_name": "t", + "masked_card_number": "XXXX-XXXX-XXXX-1" + }, + "payment_collection_method": "automatic", + "subscription_ids": [ + 1, + 2 + ], + "created_at": "2021-01-21T05:47:38-05:00" + } } ``` @@ -464,25 +481,27 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 404 | Not Found | `ApiException` | +| 422 | Unprocessable Entity (WebDAV) | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | -# Read Subscription Group by Subscription Id +# Read Subscription Group -Use this endpoint to find subscription group associated with subscription. +Use this endpoint to find subscription group details. -If the subscription is not in a group endpoint will return 404 code. +#### Current Billing Amount in Cents + +Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. ```csharp -ReadSubscriptionGroupBySubscriptionIdAsync( - string subscriptionId) +ReadSubscriptionGroupAsync( + string uid) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `string` | Query, Required | The Chargify id of the subscription associated with the subscription group | +| `uid` | `string` | Template, Required | The uid of the subscription group | ## Response Type @@ -491,10 +510,10 @@ ReadSubscriptionGroupBySubscriptionIdAsync( ## Example Usage ```csharp -string subscriptionId = "subscription_id0"; +string uid = "uid0"; try { - FullSubscriptionGroupResponse result = await subscriptionGroupsController.ReadSubscriptionGroupBySubscriptionIdAsync(subscriptionId); + FullSubscriptionGroupResponse result = await subscriptionGroupsController.ReadSubscriptionGroupAsync(uid); } catch (ApiException e) { @@ -520,6 +539,7 @@ catch (ApiException e) "next_assessment_at": "2020-08-01T14:00:00-05:00", "state": "active", "cancel_at_end_of_period": false, + "current_billing_amount_in_cents": 11500, "customer": { "first_name": "Mark", "last_name": "Wannabewahlberg", @@ -544,42 +564,24 @@ catch (ApiException e) } ``` -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | - - -# Create Subscription Group Hierarchy - -For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. - -Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. - -**Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. -Rather than specifying a customer, the `target` parameter could instead simply have a value of - -* `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer, -* `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or -* `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. +# Update Subscription Group Members -To create a new subscription into a subscription group, please reference the following: -[Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group) +Use this endpoint to update subscription group members. +`"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. ```csharp -CreateSubscriptionGroupHierarchyAsync( - int subscriptionId, - Models.AddSubscriptionToAGroup body = null) +UpdateSubscriptionGroupMembersAsync( + string uid, + Models.UpdateSubscriptionGroupRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`AddSubscriptionToAGroup`](../../doc/models/add-subscription-to-a-group.md) | Body, Optional | - | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`UpdateSubscriptionGroupRequest`](../../doc/models/update-subscription-group-request.md) | Body, Optional | - | ## Response Type @@ -588,31 +590,24 @@ CreateSubscriptionGroupHierarchyAsync( ## Example Usage ```csharp -int subscriptionId = 222; -AddSubscriptionToAGroup body = new AddSubscriptionToAGroup +string uid = "uid0"; +UpdateSubscriptionGroupRequest body = new UpdateSubscriptionGroupRequest { - MGroup = AddSubscriptionToAGroupGroup.FromGroupSettings( - new GroupSettings + SubscriptionGroup = new UpdateSubscriptionGroup + { + MemberIds = new List { - Target = new GroupTarget - { - Type = GroupTargetType.Subscription, - Id = 32987, - }, - Billing = new GroupBilling - { - Accrue = true, - AlignDate = true, - Prorate = true, - }, - } - ), + 1, + 2, + 3, + }, + }, }; try { - SubscriptionGroupResponse result = await subscriptionGroupsController.CreateSubscriptionGroupHierarchyAsync( - subscriptionId, + SubscriptionGroupResponse result = await subscriptionGroupsController.UpdateSubscriptionGroupMembersAsync( + uid, body ); } @@ -628,23 +623,28 @@ catch (ApiException e) ```json { "subscription_group": { - "customer_id": 130690, + "customer_id": 1, "payment_profile": { - "id": 32055, - "first_name": "Marty", - "last_name": "McFly", - "masked_card_number": "XXXX-XXXX-XXXX-1111" + "id": 1, + "first_name": "t", + "last_name": "t", + "masked_card_number": "XXXX-XXXX-XXXX-1" }, + "payment_collection_method": "automatic", "subscription_ids": [ - 32988, - 33060, - 32986 + 1 ], - "created_at": "2018-08-30T17:14:30-04:00" + "created_at": "2021-01-21T05:47:38-05:00" } } ``` +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupUpdateErrorResponseException`](../../doc/models/subscription-group-update-error-response-exception.md) | + # Remove Subscription From Group diff --git a/doc/controllers/subscription-invoice-account.md b/doc/controllers/subscription-invoice-account.md index 7d195e9..51f22c6 100644 --- a/doc/controllers/subscription-invoice-account.md +++ b/doc/controllers/subscription-invoice-account.md @@ -10,49 +10,14 @@ SubscriptionInvoiceAccountController subscriptionInvoiceAccountController = clie ## Methods -* [Read Account Balances](../../doc/controllers/subscription-invoice-account.md#read-account-balances) * [Create Prepayment](../../doc/controllers/subscription-invoice-account.md#create-prepayment) +* [Read Account Balances](../../doc/controllers/subscription-invoice-account.md#read-account-balances) * [List Prepayments](../../doc/controllers/subscription-invoice-account.md#list-prepayments) * [Issue Service Credit](../../doc/controllers/subscription-invoice-account.md#issue-service-credit) * [Deduct Service Credit](../../doc/controllers/subscription-invoice-account.md#deduct-service-credit) * [Refund Prepayment](../../doc/controllers/subscription-invoice-account.md#refund-prepayment) -# Read Account Balances - -Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. - -```csharp -ReadAccountBalancesAsync( - int subscriptionId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`Task`](../../doc/models/account-balances.md) - -## Example Usage - -```csharp -int subscriptionId = 222; -try -{ - AccountBalances result = await subscriptionInvoiceAccountController.ReadAccountBalancesAsync(subscriptionId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - - # Create Prepayment ## Create Prepayment @@ -126,6 +91,41 @@ catch (ApiException e) ``` +# Read Account Balances + +Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. + +```csharp +ReadAccountBalancesAsync( + int subscriptionId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`Task`](../../doc/models/account-balances.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +try +{ + AccountBalances result = await subscriptionInvoiceAccountController.ReadAccountBalancesAsync(subscriptionId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + # List Prepayments This request will list a subscription's prepayments. diff --git a/doc/controllers/subscription-notes.md b/doc/controllers/subscription-notes.md index 2cc8dda..13af67a 100644 --- a/doc/controllers/subscription-notes.md +++ b/doc/controllers/subscription-notes.md @@ -11,10 +11,10 @@ SubscriptionNotesController subscriptionNotesController = client.SubscriptionNot ## Methods * [Create Subscription Note](../../doc/controllers/subscription-notes.md#create-subscription-note) +* [Delete Subscription Note](../../doc/controllers/subscription-notes.md#delete-subscription-note) * [List Subscription Notes](../../doc/controllers/subscription-notes.md#list-subscription-notes) * [Read Subscription Note](../../doc/controllers/subscription-notes.md#read-subscription-note) * [Update Subscription Note](../../doc/controllers/subscription-notes.md#update-subscription-note) -* [Delete Subscription Note](../../doc/controllers/subscription-notes.md#delete-subscription-note) # Create Subscription Note @@ -74,6 +74,47 @@ catch (ApiException e) ``` +# Delete Subscription Note + +Use the following method to delete a note for a Subscription. + +```csharp +DeleteSubscriptionNoteAsync( + int subscriptionId, + int noteId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `noteId` | `int` | Template, Required | The Chargify id of the note | + +## Response Type + +`Task` + +## Example Usage + +```csharp +int subscriptionId = 222; +int noteId = 66; +try +{ + await subscriptionNotesController.DeleteSubscriptionNoteAsync( + subscriptionId, + noteId + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + + # List Subscription Notes Use this method to retrieve a list of Notes associated with a Subscription. The response will be an array of Notes. @@ -252,44 +293,3 @@ catch (ApiException e) } ``` - -# Delete Subscription Note - -Use the following method to delete a note for a Subscription. - -```csharp -DeleteSubscriptionNoteAsync( - int subscriptionId, - int noteId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `noteId` | `int` | Template, Required | The Chargify id of the note | - -## Response Type - -`Task` - -## Example Usage - -```csharp -int subscriptionId = 222; -int noteId = 66; -try -{ - await subscriptionNotesController.DeleteSubscriptionNoteAsync( - subscriptionId, - noteId - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - diff --git a/doc/controllers/subscription-status.md b/doc/controllers/subscription-status.md index bd3908d..260e763 100644 --- a/doc/controllers/subscription-status.md +++ b/doc/controllers/subscription-status.md @@ -10,204 +10,18 @@ SubscriptionStatusController subscriptionStatusController = client.SubscriptionS ## Methods -* [Retry Subscription](../../doc/controllers/subscription-status.md#retry-subscription) * [Cancel Subscription](../../doc/controllers/subscription-status.md#cancel-subscription) * [Resume Subscription](../../doc/controllers/subscription-status.md#resume-subscription) * [Pause Subscription](../../doc/controllers/subscription-status.md#pause-subscription) -* [Update Automatic Subscription Resumption](../../doc/controllers/subscription-status.md#update-automatic-subscription-resumption) -* [Reactivate Subscription](../../doc/controllers/subscription-status.md#reactivate-subscription) * [Initiate Delayed Cancellation](../../doc/controllers/subscription-status.md#initiate-delayed-cancellation) * [Stop Delayed Cancellation](../../doc/controllers/subscription-status.md#stop-delayed-cancellation) +* [Retry Subscription](../../doc/controllers/subscription-status.md#retry-subscription) +* [Update Automatic Subscription Resumption](../../doc/controllers/subscription-status.md#update-automatic-subscription-resumption) +* [Reactivate Subscription](../../doc/controllers/subscription-status.md#reactivate-subscription) * [Cancel Dunning](../../doc/controllers/subscription-status.md#cancel-dunning) * [Preview Renewal](../../doc/controllers/subscription-status.md#preview-renewal) -# Retry Subscription - -Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. - -## Successful Reactivation - -The response will be `200 OK` with the updated Subscription. - -## Failed Reactivation - -The response will be `422 "Unprocessable Entity`. - -```csharp -RetrySubscriptionAsync( - int subscriptionId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`Task`](../../doc/models/subscription-response.md) - -## Example Usage - -```csharp -int subscriptionId = 222; -try -{ - SubscriptionResponse result = await subscriptionStatusController.RetrySubscriptionAsync(subscriptionId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 46330, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2018-10-22T13:10:46-06:00", - "created_at": "2018-10-22T13:10:46-06:00", - "updated_at": "2021-06-10T09:23:43-06:00", - "expires_at": null, - "balance_in_cents": 18600, - "current_period_ends_at": "2021-06-22T13:10:46-06:00", - "next_assessment_at": "2021-06-22T13:10:46-06:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": null, - "payment_collection_method": "automatic", - "snap_day": null, - "cancellation_method": null, - "product_price_point_id": 3464, - "next_product_price_point_id": null, - "receives_invoice_emails": null, - "net_terms": null, - "locale": null, - "currency": "USD", - "reference": null, - "scheduled_cancellation_at": null, - "current_period_started_at": "2021-05-22T13:10:46-06:00", - "previous_state": "past_due", - "signup_payment_id": 651268, - "signup_revenue": "6.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 600, - "product_price_in_cents": 600, - "product_version_number": 501, - "payment_type": null, - "referral_code": "rzqvrx", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "coupon_codes": [], - "offer_id": null, - "credit_balance_in_cents": 0, - "prepayment_balance_in_cents": 0, - "payer_id": 142365, - "stored_credential_transaction_id": null, - "next_product_handle": null, - "on_hold_at": null, - "prepaid_dunning": false, - "customer": { - "id": 142365, - "first_name": "Lavern", - "last_name": "Fahey", - "organization": null, - "email": "millie2@example.com", - "created_at": "2018-10-22T13:10:46-06:00", - "updated_at": "2018-10-22T13:10:46-06:00", - "reference": null, - "address": null, - "address_2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "phone": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": null, - "verified": false, - "portal_customer_created_at": "2018-10-22T13:10:46-06:00", - "vat_number": null, - "cc_emails": "john@example.com, sue@example.com", - "tax_exempt": false, - "parent_id": null, - "locale": null - }, - "product": { - "id": 8080, - "name": "Pro Versions", - "handle": null, - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "month", - "created_at": "2019-02-15T10:15:00-07:00", - "updated_at": "2019-02-15T10:30:34-07:00", - "price_in_cents": 600, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "require_shipping_address": false, - "request_billing_address": false, - "require_billing_address": false, - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "default_product_price_point_id": 3464, - "version_number": 501, - "update_return_params": "", - "product_price_point_id": 3464, - "product_price_point_name": "Default", - "product_price_point_handle": "uuid:5305c3f0-1375-0137-5619-065dfbfdc636", - "product_family": { - "id": 37, - "name": "Acme Projects", - "description": null, - "handle": "acme-projects", - "accounting_code": null, - "created_at": "2013-02-20T15:05:51-07:00", - "updated_at": "2013-02-20T15:05:51-07:00" - }, - "public_signup_pages": [ - { - "id": 1540, - "return_url": null, - "return_params": "", - "url": "https://acme-test.staging-chargifypay.com/subscribe/2f6y53rrqgsf" - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - # Cancel Subscription The DELETE action causes the cancellation of the Subscription. This means, the method sets the Subscription state to "canceled". @@ -559,7 +373,276 @@ PauseSubscriptionAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`PauseRequest`](../../doc/models/pause-request.md) | Body, Optional | Allows to pause a Subscription | +| `body` | [`PauseRequest`](../../doc/models/pause-request.md) | Body, Optional | Allows to pause a Subscription | + +## Response Type + +[`Task`](../../doc/models/subscription-response.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +PauseRequest body = new PauseRequest +{ + Hold = new AutoResume + { + AutomaticallyResumeAt = DateTime.ParseExact("2017-05-25T11:25:00Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + }, +}; + +try +{ + SubscriptionResponse result = await subscriptionStatusController.PauseSubscriptionAsync( + subscriptionId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 18220670, + "state": "on_hold", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2017-06-27T13:45:15-05:00", + "created_at": "2017-06-27T13:45:13-05:00", + "updated_at": "2017-06-30T09:26:50-05:00", + "expires_at": null, + "balance_in_cents": 10000, + "current_period_ends_at": "2017-06-30T12:00:00-05:00", + "next_assessment_at": "2017-06-30T12:00:00-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": "end", + "cancellation_method": null, + "current_period_started_at": "2017-06-27T13:45:13-05:00", + "previous_state": "active", + "signup_payment_id": 191819284, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 0, + "product_version_number": 1, + "payment_type": null, + "referral_code": "d3pw7f", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": 10000, + "customer": { + "id": 17780587, + "first_name": "Catie", + "last_name": "Test", + "organization": "Acme, Inc.", + "email": "catie@example.com", + "created_at": "2017-06-27T13:01:05-05:00", + "updated_at": "2017-06-30T09:23:10-05:00", + "reference": "123ABC", + "address": "123 Anywhere Street", + "address_2": "Apartment #10", + "city": "Los Angeles", + "state": "CA", + "zip": "90210", + "country": "US", + "phone": "555-555-5555", + "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "portal_invite_last_accepted_at": null, + "verified": true, + "portal_customer_created_at": "2017-06-27T13:01:08-05:00", + "cc_emails": "support@example.com", + "tax_exempt": true + }, + "product": { + "id": 4470347, + "name": "Zero Dollar Product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-03-23T10:54:12-05:00", + "updated_at": "2017-04-20T15:18:46-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 997233, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 316810, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Initiate Delayed Cancellation + +Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. + +Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. + +Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. + +```csharp +InitiateDelayedCancellationAsync( + int subscriptionId, + Models.CancellationRequest body = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`CancellationRequest`](../../doc/models/cancellation-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/delayed-cancellation-response.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +try +{ + DelayedCancellationResponse result = await subscriptionStatusController.InitiateDelayedCancellationAsync(subscriptionId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | + + +# Stop Delayed Cancellation + +Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. + +This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. + +```csharp +StopDelayedCancellationAsync( + int subscriptionId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`Task`](../../doc/models/delayed-cancellation-response.md) + +## Example Usage + +```csharp +int subscriptionId = 222; +try +{ + DelayedCancellationResponse result = await subscriptionStatusController.StopDelayedCancellationAsync(subscriptionId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "message": "This subscription will no longer be canceled" +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiException` | + + +# Retry Subscription + +Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. + +## Successful Reactivation + +The response will be `200 OK` with the updated Subscription. + +## Failed Reactivation + +The response will be `422 "Unprocessable Entity`. + +```csharp +RetrySubscriptionAsync( + int subscriptionId) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | ## Response Type @@ -569,22 +652,9 @@ PauseSubscriptionAsync( ```csharp int subscriptionId = 222; -PauseRequest body = new PauseRequest -{ - Hold = new AutoResume - { - AutomaticallyResumeAt = DateTime.ParseExact("2017-05-25T11:25:00Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), - }, -}; - try { - SubscriptionResponse result = await subscriptionStatusController.PauseSubscriptionAsync( - subscriptionId, - body - ); + SubscriptionResponse result = await subscriptionStatusController.RetrySubscriptionAsync(subscriptionId); } catch (ApiException e) { @@ -598,75 +668,94 @@ catch (ApiException e) ```json { "subscription": { - "id": 18220670, - "state": "on_hold", + "id": 46330, + "state": "active", "trial_started_at": null, "trial_ended_at": null, - "activated_at": "2017-06-27T13:45:15-05:00", - "created_at": "2017-06-27T13:45:13-05:00", - "updated_at": "2017-06-30T09:26:50-05:00", + "activated_at": "2018-10-22T13:10:46-06:00", + "created_at": "2018-10-22T13:10:46-06:00", + "updated_at": "2021-06-10T09:23:43-06:00", "expires_at": null, - "balance_in_cents": 10000, - "current_period_ends_at": "2017-06-30T12:00:00-05:00", - "next_assessment_at": "2017-06-30T12:00:00-05:00", + "balance_in_cents": 18600, + "current_period_ends_at": "2021-06-22T13:10:46-06:00", + "next_assessment_at": "2021-06-22T13:10:46-06:00", "canceled_at": null, "cancellation_message": null, "next_product_id": null, - "cancel_at_end_of_period": false, + "cancel_at_end_of_period": null, "payment_collection_method": "automatic", - "snap_day": "end", + "snap_day": null, "cancellation_method": null, - "current_period_started_at": "2017-06-27T13:45:13-05:00", - "previous_state": "active", - "signup_payment_id": 191819284, - "signup_revenue": "0.00", + "product_price_point_id": 3464, + "next_product_price_point_id": null, + "receives_invoice_emails": null, + "net_terms": null, + "locale": null, + "currency": "USD", + "reference": null, + "scheduled_cancellation_at": null, + "current_period_started_at": "2021-05-22T13:10:46-06:00", + "previous_state": "past_due", + "signup_payment_id": 651268, + "signup_revenue": "6.00", "delayed_cancel_at": null, "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 0, - "product_version_number": 1, + "total_revenue_in_cents": 600, + "product_price_in_cents": 600, + "product_version_number": 501, "payment_type": null, - "referral_code": "d3pw7f", + "referral_code": "rzqvrx", "coupon_use_count": null, "coupon_uses_allowed": null, "reason_code": null, "automatically_resume_at": null, - "current_billing_amount_in_cents": 10000, + "coupon_codes": [], + "offer_id": null, + "credit_balance_in_cents": 0, + "prepayment_balance_in_cents": 0, + "payer_id": 142365, + "stored_credential_transaction_id": null, + "next_product_handle": null, + "on_hold_at": null, + "prepaid_dunning": false, "customer": { - "id": 17780587, - "first_name": "Catie", - "last_name": "Test", - "organization": "Acme, Inc.", - "email": "catie@example.com", - "created_at": "2017-06-27T13:01:05-05:00", - "updated_at": "2017-06-30T09:23:10-05:00", - "reference": "123ABC", - "address": "123 Anywhere Street", - "address_2": "Apartment #10", - "city": "Los Angeles", - "state": "CA", - "zip": "90210", - "country": "US", - "phone": "555-555-5555", - "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "id": 142365, + "first_name": "Lavern", + "last_name": "Fahey", + "organization": null, + "email": "millie2@example.com", + "created_at": "2018-10-22T13:10:46-06:00", + "updated_at": "2018-10-22T13:10:46-06:00", + "reference": null, + "address": null, + "address_2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "phone": null, + "portal_invite_last_sent_at": null, "portal_invite_last_accepted_at": null, - "verified": true, - "portal_customer_created_at": "2017-06-27T13:01:08-05:00", - "cc_emails": "support@example.com", - "tax_exempt": true + "verified": false, + "portal_customer_created_at": "2018-10-22T13:10:46-06:00", + "vat_number": null, + "cc_emails": "john@example.com, sue@example.com", + "tax_exempt": false, + "parent_id": null, + "locale": null }, "product": { - "id": 4470347, - "name": "Zero Dollar Product", - "handle": "zero-dollar-product", + "id": 8080, + "name": "Pro Versions", + "handle": null, "description": "", "accounting_code": "", "request_credit_card": true, "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-03-23T10:54:12-05:00", - "updated_at": "2017-04-20T15:18:46-05:00", - "price_in_cents": 0, + "expiration_interval_unit": "month", + "created_at": "2019-02-15T10:15:00-07:00", + "updated_at": "2019-02-15T10:30:34-07:00", + "price_in_cents": 600, "interval": 1, "interval_unit": "month", "initial_charge_in_cents": null, @@ -674,27 +763,36 @@ catch (ApiException e) "trial_interval": null, "trial_interval_unit": "month", "archived_at": null, - "require_credit_card": false, + "require_credit_card": true, "return_params": "", + "require_shipping_address": false, + "request_billing_address": false, + "require_billing_address": false, "taxable": false, "update_return_url": "", "tax_code": "", "initial_charge_after_trial": false, - "version_number": 1, + "default_product_price_point_id": 3464, + "version_number": 501, "update_return_params": "", + "product_price_point_id": 3464, + "product_price_point_name": "Default", + "product_price_point_handle": "uuid:5305c3f0-1375-0137-5619-065dfbfdc636", "product_family": { - "id": 997233, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null + "id": 37, + "name": "Acme Projects", + "description": null, + "handle": "acme-projects", + "accounting_code": null, + "created_at": "2013-02-20T15:05:51-07:00", + "updated_at": "2013-02-20T15:05:51-07:00" }, "public_signup_pages": [ { - "id": 316810, - "return_url": "", + "id": 1540, + "return_url": null, "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + "url": "https://acme-test.staging-chargifypay.com/subscribe/2f6y53rrqgsf" } ] } @@ -1220,104 +1318,6 @@ catch (ApiException e) | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Initiate Delayed Cancellation - -Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. - -Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. - -Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. - -```csharp -InitiateDelayedCancellationAsync( - int subscriptionId, - Models.CancellationRequest body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`CancellationRequest`](../../doc/models/cancellation-request.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/delayed-cancellation-response.md) - -## Example Usage - -```csharp -int subscriptionId = 222; -try -{ - DelayedCancellationResponse result = await subscriptionStatusController.InitiateDelayedCancellationAsync(subscriptionId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | - - -# Stop Delayed Cancellation - -Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. - -This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. - -```csharp -StopDelayedCancellationAsync( - int subscriptionId) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`Task`](../../doc/models/delayed-cancellation-response.md) - -## Example Usage - -```csharp -int subscriptionId = 222; -try -{ - DelayedCancellationResponse result = await subscriptionStatusController.StopDelayedCancellationAsync(subscriptionId); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` - -## Example Response *(as JSON)* - -```json -{ - "message": "This subscription will no longer be canceled" -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | - - # Cancel Dunning If a subscription is currently in dunning, the subscription will be set to active and the active Dunner will be resolved. diff --git a/doc/controllers/subscriptions.md b/doc/controllers/subscriptions.md index 9808799..7101edf 100644 --- a/doc/controllers/subscriptions.md +++ b/doc/controllers/subscriptions.md @@ -10,643 +10,735 @@ SubscriptionsController subscriptionsController = client.SubscriptionsController ## Methods -* [Create Subscription](../../doc/controllers/subscriptions.md#create-subscription) -* [List Subscriptions](../../doc/controllers/subscriptions.md#list-subscriptions) +* [Read Subscription by Reference](../../doc/controllers/subscriptions.md#read-subscription-by-reference) +* [Apply Coupon to Subscription](../../doc/controllers/subscriptions.md#apply-coupon-to-subscription) * [Update Subscription](../../doc/controllers/subscriptions.md#update-subscription) +* [Purge Subscription](../../doc/controllers/subscriptions.md#purge-subscription) +* [Preview Subscription](../../doc/controllers/subscriptions.md#preview-subscription) * [Read Subscription](../../doc/controllers/subscriptions.md#read-subscription) * [Override Subscription](../../doc/controllers/subscriptions.md#override-subscription) -* [Read Subscription by Reference](../../doc/controllers/subscriptions.md#read-subscription-by-reference) -* [Purge Subscription](../../doc/controllers/subscriptions.md#purge-subscription) * [Create Prepaid Subscription](../../doc/controllers/subscriptions.md#create-prepaid-subscription) -* [Preview Subscription](../../doc/controllers/subscriptions.md#preview-subscription) -* [Apply Coupon to Subscription](../../doc/controllers/subscriptions.md#apply-coupon-to-subscription) -* [Delete Coupon From Subscription](../../doc/controllers/subscriptions.md#delete-coupon-from-subscription) +* [Create Subscription](../../doc/controllers/subscriptions.md#create-subscription) +* [List Subscriptions](../../doc/controllers/subscriptions.md#list-subscriptions) * [Activate Subscription](../../doc/controllers/subscriptions.md#activate-subscription) +* [Delete Coupon From Subscription](../../doc/controllers/subscriptions.md#delete-coupon-from-subscription) -# Create Subscription - -Full documentation on how subscriptions operate within Chargify can be located under the following topics: - -+ [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction) -+ [Subscriptions Actions](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions) -+ [Subscription Cancellation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions#initiate-cancellation) -+ [Subscription Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021-Reactivating-and-Resuming) -+ [Subscription Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821-Imports) - -When creating a subscription, you must specify a product and a customer. Credit card details may be required, depending on the options for the Product being subscribed ([see Product Options](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221#payment-method-settings)). - -The product may be specified by `product_id` or by `product_handle` (API Handle). In similar fashion, to pass a particular product price point, you may either use `product_price_point_handle` or `product_price_point_id`. - -An existing customer may be specified by a `customer_id` (ID within Chargify) or a `customer_reference` (unique value within your app that you have shared with Chargify via the reference attribute on a customer). You may also pass in an existing payment profile for that customer with `payment_profile_id`. A new customer may be created by providing `customer_attributes`. - -Credit card details may be required, depending on the options for the product being subscribed. The product can be specified by `product_id` or by `product_handle` (API Handle). - -If you are creating a subscription with a payment profile, the attribute to send will be `credit_card_attributes` or `bank_account_attributes` for ACH and Direct Debit. That said, when you read the subscription after creation, we return the profile details under `credit_card` or `bank_account`. - -## Taxable Subscriptions - -If your intent is to charge your subscribers tax via [Avalara Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405275711885-Avalara-VAT-Tax) or [Custom Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405069041549-Custom-Taxes), there are a few considerations to be made regarding collecting subscription data. -For subscribers to be eligible to be taxed, the following information for the `customer` object or `payment_profile` object must by supplied: - -+ A subscription to a [taxable product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221-Product-Editing#tax-settings) -+ [Full valid billing or shipping address](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#full-address-required-for-taxable-subscriptions) to identify the tax locale -+ The portion of the address that houses the [state information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-state-format-for-taxable-subscriptions) of either adddress must adhere to the ISO standard of a 2-3 character limit/format. -+ The portion of the address that houses the [country information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-country-format-for-taxable-subscriptions) must adhere to the ISO standard of a 2 character limit/format. - -## Subscription Request Examples - -The subscription examples below will be split into two sections. - -The first section, "Subscription Customization", will focus on passing different information with a subscription, such as components, calendar billing, and custom fields. These examples will presume you are using a secure `chargify_token` generated by Chargify.js. - -The second section, "Passing Payment Information", will focus on passing payment information into Chargify. Please be aware that collecting and sending Chargify raw card details requires PCI compliance on your end; these examples are provided as guidance. If your business is not PCI compliant, we recommend using Chargify.js to collect credit cards or bank accounts. - -# Subscription Customization - -## With Components - -Different components require slightly different data. For example, quantity-based and on/off components accept `allocated_quantity`, while metered components accept `unit_balance`. - -When creating a subscription with a component, a `price_point_id` can be passed in along with the `component_id` to specify which price point to use. If not passed in, the default price point will be used. +# Read Subscription by Reference -Note: if an invalid `price_point_id` is used, the subscription will still proceed but will use the component's default price point. +Use this endpoint to find a subscription by its reference. -Components and their price points may be added by ID or by handle. See the example request body labeled "Components By Handle (Quantity-Based)"; the format will be the same for other component types. +```csharp +ReadSubscriptionByReferenceAsync( + string reference = null) +``` -## With Coupon(s) +## Parameters -Pass an array of `coupon_codes`. See the example request body "With Coupon". +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `reference` | `string` | Query, Optional | Subscription reference | -## With Manual Invoice Collection +## Response Type -The `invoice` collection method works only on legacy Statement Architecture. +[`Task`](../../doc/models/subscription-response.md) -On Relationship Invoicing Architecture use the `remittance` collection method. +## Example Usage -## Prepaid Subscription +```csharp +try +{ + SubscriptionResponse result = await subscriptionsController.ReadSubscriptionByReferenceAsync(); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -A prepaid subscription can be created with the usual subscription creation parameters, specifying `prepaid` as the `payment_collection_method` and including a nested `prepaid_configuration`. -After a prepaid subscription has been created, additional funds can be manually added to the prepayment account through the [Create Prepayment Endpoint](https://developers.chargify.com/docs/api-docs/7ec482de77ba7-create-prepayment). +# Apply Coupon to Subscription -Prepaid subscriptions do not work on legacy Statement Architecture. +An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons) -## With Metafields +## Query Parameters vs Request Body Parameters -Metafields can either attach to subscriptions or customers. Metafields are popuplated with the supplied metadata to the resource specified. +Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. -If the metafield doesn't exist yet, it will be created on-the-fly. +For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. -## With Custom Pricing +```csharp +ApplyCouponToSubscriptionAsync( + int subscriptionId, + string code = null, + Models.AddCouponsRequest body = null) +``` -Custom pricing is pricing specific to the subscription in question. -Create a subscription with custom pricing by passing pricing information instead of a price point. -For a custom priced product, pass the custom_price object in place of `product_price_point_id`. For a custom priced component, pass the `custom_price` object within the component object. -Custom prices and price points can exist in harmony on a subscription. +## Parameters -# Passing Payment Information +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `code` | `string` | Query, Optional | A code for the coupon that would be applied to a subscription | +| `body` | [`AddCouponsRequest`](../../doc/models/add-coupons-request.md) | Body, Optional | - | -## Subscription with Chargify.js token +## Response Type -The `chargify_token` can be obtained using [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). The token represents payment profile attributes that were provided by the customer in their browser and stored at the payment gateway. +[`Task`](../../doc/models/subscription-response.md) -The `payment_type` attribute may either be `credit_card` or `bank_account`, depending on the type of payment method being added. If a bank account is being passed, the payment attributes should be changed to `bank_account_attributes`. +## Example Usage -```json +```csharp +int subscriptionId = 222; +AddCouponsRequest body = new AddCouponsRequest { - "subscription": { - "product_handle": "pro-plan", - "customer_attributes": { - "first_name": "Joe", - "last_name": "Smith", - "email": "j.smith@example.com" + Codes = new List + { + "COUPON_1", + "COUPON_2", }, - "credit_card_attributes": { - "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn", - "payment_type": "credit_card" - } - } -} -``` - -## Subscription with vault token - -If you already have a customer and card stored in your payment gateway, you may create a subscription with a `vault_token`. Providing the last_four, card type and expiration date will allow the card to be displayed properly in the Chargify UI. +}; -```json +try { - "subscription": { - "product_handle": "pro-plan", - "customer_attributes": { - "first_name": "Joe", - "last_name": "Smith", - "email": "j.smith@example.com" - }, - "credit_card_attributes": { - first_name: "Joe, - last_name: "Smith", - card_type: "visa", - expiration_month: "05", - expiration_year: "2025", - last_four: "1234", - vault_token: "12345abc", - current_vault: "braintree_blue" - } + SubscriptionResponse result = await subscriptionsController.ApplyCouponToSubscriptionAsync( + subscriptionId, + null, + body + ); } -``` - -## Subscription with Credit Card - -```json -"subscription": { - "product_handle": "basic", - "customer_attributes": { - "first_name": "Joe", - "last_name": "Blow", - "email": "joe@example.com", - "zip": "02120", - "state": "MA", - "reference": "XYZ", - "phone": "(617) 111 - 0000", - "organization": "Acme", - "country": "US", - "city": "Boston", - "address_2": null, - "address": "123 Mass Ave." - }, - "credit_card_attributes": { - "last_name": "Smith", - "first_name": "Joe", - "full_number": "4111111111111111", - "expiration_year": "2021", - "expiration_month": "1", - "card_type": "visa", - "billing_zip": "02120", - "billing_state": "MA", - "billing_country": "US", - "billing_city": "Boston", - "billing_address_2": null, - "billing_address": "123 Mass Ave." - } +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); } ``` -## Subscription with ACH as Payment Profile +## Example Response *(as JSON)* ```json { "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Joe", - "last_name": "Blow", - "email": "joe@example.com", - "zip": "02120", - "state": "MA", - "reference": "XYZ", - "phone": "(617) 111 - 0000", - "organization": "Acme", - "country": "US", - "city": "Boston", - "address_2": null, - "address": "123 Mass Ave." - }, - "bank_account_attributes": { - "bank_name": "Best Bank", - "bank_routing_number": "021000089", - "bank_account_number": "111111111111", - "bank_account_type": "checking", - "bank_account_holder_type": "business", - "payment_type": "bank_account" - } - } -} -``` - -## Subscription with PayPal payment profile - -### With the nonce from Braintree JS - -```json -{ "subscription": { - "product_handle":"test-product-b", - "customer_attributes": { - "first_name":"Amelia", - "last_name":"Johnson", - "email":"amelia@example.com", - "organization":"My Awesome Company" + "id": 21607180, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2018-04-20T14:20:57-05:00", + "created_at": "2018-04-20T14:20:57-05:00", + "updated_at": "2018-05-11T13:53:44-05:00", + "expires_at": null, + "balance_in_cents": 49000, + "current_period_ends_at": "2018-05-12T11:33:03-05:00", + "next_assessment_at": "2018-05-12T11:33:03-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "remittance", + "snap_day": null, + "cancellation_method": null, + "current_period_started_at": "2018-05-11T11:33:03-05:00", + "previous_state": "active", + "signup_payment_id": 237154761, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": "COUPONA", + "total_revenue_in_cents": 52762, + "product_price_in_cents": 100000, + "product_version_number": 2, + "payment_type": "credit_card", + "referral_code": "x45nc8", + "coupon_use_count": 0, + "coupon_uses_allowed": 1, + "reason_code": null, + "automatically_resume_at": null, + "coupon_codes": [ + "COUPONA", + "COUPONB" + ], + "customer": { + "id": 21259051, + "first_name": "K", + "last_name": "C", + "organization": "", + "email": "example@chargify.com", + "created_at": "2018-04-20T14:20:57-05:00", + "updated_at": "2018-04-23T15:29:28-05:00", + "reference": null, + "address": "", + "address_2": "", + "city": "", + "state": "", + "zip": "", + "country": "", + "phone": "", + "portal_invite_last_sent_at": "2018-04-20T14:20:59-05:00", + "portal_invite_last_accepted_at": null, + "verified": false, + "portal_customer_created_at": "2018-04-20T14:20:59-05:00", + "cc_emails": "", + "tax_exempt": false }, - "payment_profile_attributes":{ - "paypal_email": "amelia@example.com", - "current_vault": "braintree_blue", - "payment_method_nonce":"abc123", - "payment_type":"paypal_account" - } - } -``` - -### With the Braintree Customer ID as the vault token: - -```json -{ "subscription": { - "product_handle":"test-product-b", - "customer_attributes": { - "first_name":"Amelia", - "last_name":"Johnson", - "email":"amelia@example.com", - "organization":"My Awesome Company" + "product": { + "id": 4581816, + "name": "Basic", + "handle": "basic", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-11-02T15:00:11-05:00", + "updated_at": "2018-04-10T09:02:59-05:00", + "price_in_cents": 100000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": 100000, + "trial_price_in_cents": 1000, + "trial_interval": 10, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 2, + "update_return_params": "", + "product_family": { + "id": 1025627, + "name": "My Product Family", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 333589, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/hbwtd98j3hk2/basic" + }, + { + "id": 335926, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/g366zy67c7rm/basic" + }, + { + "id": 345555, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/txqyyqk7d8rz/basic" + }, + { + "id": 345556, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/2zss3qpf4249/basic" + } + ] }, - "payment_profile_attributes":{ - "paypal_email": "amelia@example.com", - "current_vault": "braintree_blue", - "vault_token":"58271347", - "payment_type":"paypal_account" + "credit_card": { + "id": 14839830, + "first_name": "John", + "last_name": "Doe", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2028, + "customer_id": 21259051, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": null, + "billing_city": null, + "billing_state": null, + "billing_zip": "99999", + "billing_country": null, + "customer_vault_token": null, + "billing_address_2": null, + "payment_type": "credit_card" } } +} ``` -## Subscription using GoCardless Bank Number - -These examples creates a customer, bank account and mandate in GoCardless. +## Errors -For more information on GoCardless, please view the following two resources: +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionAddCouponErrorException`](../../doc/models/subscription-add-coupon-error-exception.md) | -+ [Payment Profiles via API for GoCardless](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#gocardless) -+ [Full documentation on GoCardless](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404501889677) +# Update Subscription -+ [Using Chargify.js with GoCardless - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-direct-debit-gocardless-gateway) +The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. -+ [Using Chargify.js with GoCardless - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-direct-debit-gocardless-gateway) +## Update Subscription Payment Method -```json -{ - "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Jane", - "last_name": "Doe", - "email": "jd@chargify.test" - }, - "bank_account_attributes": { - "bank_name": "Royal Bank of France", - "bank_account_number": "0000000", - "bank_routing_number": "0003", - "bank_branch_code": "00006", - "payment_type": "bank_account", - "billing_address": "20 Place de la Gare", - "billing_city": "Colombes", - "billing_state": "Île-de-France", - "billing_zip": "92700", - "billing_country": "FR" - } - } -} -``` +Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. -## Subscription using GoCardless IBAN Number +Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. -```json -{ - "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Jane", - "last_name": "Doe", - "email": "jd@chargify.test" - }, - "bank_account_attributes": { - "bank_name": "French Bank", - "bank_iban": "FR1420041010050500013M02606", - "payment_type": "bank_account", - "billing_address": "20 Place de la Gare", - "billing_city": "Colombes", - "billing_state": "Île-de-France", - "billing_zip": "92700", - "billing_country": "FR" - } - } -} -``` +You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. -## Subscription using Stripe SEPA Direct Debit +## Product Change -For more information on Stripe Direct Debit, please view the following two resources: +This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. -+ [Payment Profiles via API for Stripe SEPA Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#sepa-direct-debit) +To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. -+ [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) +### Delayed Product Change -+ [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) +This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. -+ [Using Chargify.js with Stripe SEPA Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) +This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. -```json -{ - "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Jane", - "last_name": "Doe", - "email": "jd@chargify.test" - }, - "bank_account_attributes": { - "bank_name": "Test Bank", - "bank_iban": "DE89370400440532013000", - "payment_type": "bank_account" - } - } -} -``` +You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle` -## Subscription using Stripe BECS Direct Debit +**Note: To cancel a delayed product change, set `next_product_id` to an empty string.** -For more information on Stripe Direct Debit, please view the following two resources: +## Billing Date Changes -+ [Payment Profiles via API for Stripe BECS Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#stripe-becs-direct-debit) +### Regular Billing Date Changes -+ [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) +Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. -+ [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) +Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. -+ [Using Chargify.js with Stripe BECS Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-becs-direct-debit-stripe-gateway) +The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. -```json -{ - "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Jane", - "last_name": "Doe", - "email": "jd@chargify.test" - }, - "bank_account_attributes": { - "bank_name": "Test Bank", - "bank_branch_code": "000000", - "bank_account_number": "000123456", - "payment_type": "bank_account" - } - } -} -``` +### Snap Day Changes -## 3D Secure - Stripe +For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. -It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: +Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. -```json -{ - "errors": [ - "Your card was declined. This transaction requires 3D secure authentication." - ], - "gateway_payment_id": "pi_1F0aGoJ2UDb3Q4av7zU3sHPh", - "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", - "action_link": "http://acme.chargify.com/3d-secure/pi_1F0aGoJ2UDb3Q4av7zU3sHPh?one_time_token_id=242" -} +```csharp +UpdateSubscriptionAsync( + int subscriptionId, + Models.UpdateSubscriptionRequest body = null) ``` -To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. -Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: +## Parameters -- whether the authentication was successful (`success`) -- the gateway ID for the payment (`gateway_payment_id`) -- the subscription ID (`subscription_id`) +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`UpdateSubscriptionRequest`](../../doc/models/update-subscription-request.md) | Body, Optional | - | -Lastly, you can also specify a `redirect_url` within the `action_link` URL if you’d like to redirect a customer back to your site. +## Response Type -It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. +[`Task`](../../doc/models/subscription-response.md) -The final URL that you send a customer to to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` +## Example Usage -## 3D Secure - Checkout +```csharp +int subscriptionId = 222; +UpdateSubscriptionRequest body = new UpdateSubscriptionRequest +{ + Subscription = new UpdateSubscription + { + CreditCardAttributes = new CreditCardAttributes + { + FullNumber = "4111111111111111", + ExpirationMonth = "10", + ExpirationYear = "2030", + }, + NextBillingAt = "2010-08-06T15:34:00Z", + }, +}; -It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: +try +{ + SubscriptionResponse result = await subscriptionsController.UpdateSubscriptionAsync( + subscriptionId, + body + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* ```json { - "errors": [ - "Your card was declined. This transaction requires 3D secure authentication." - ], - "gateway_payment_id": "pay_6gjofv7dlyrkpizlolsuspvtiu", - "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", - "action_link": "http://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123" + "subscription": { + "id": 18220670, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2017-06-27T13:45:15-05:00", + "created_at": "2017-06-27T13:45:13-05:00", + "updated_at": "2017-06-30T09:26:50-05:00", + "expires_at": null, + "balance_in_cents": 10000, + "current_period_ends_at": "2017-06-30T12:00:00-05:00", + "next_assessment_at": "2017-06-30T12:00:00-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": "end", + "cancellation_method": null, + "current_period_started_at": "2017-06-27T13:45:13-05:00", + "previous_state": "active", + "signup_payment_id": 191819284, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 0, + "product_version_number": 1, + "payment_type": null, + "referral_code": "d3pw7f", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": 10000, + "receives_invoice_emails": false, + "customer": { + "id": 17780587, + "first_name": "Catie", + "last_name": "Test", + "organization": "Acme, Inc.", + "email": "catie@example.com", + "created_at": "2017-06-27T13:01:05-05:00", + "updated_at": "2017-06-30T09:23:10-05:00", + "reference": "123ABC", + "address": "123 Anywhere Street", + "address_2": "Apartment #10", + "city": "Los Angeles", + "state": "CA", + "zip": "90210", + "country": "US", + "phone": "555-555-5555", + "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "portal_invite_last_accepted_at": null, + "verified": true, + "portal_customer_created_at": "2017-06-27T13:01:08-05:00", + "cc_emails": "support@example.com", + "tax_exempt": true + }, + "product": { + "id": 4470347, + "name": "Zero Dollar Product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-03-23T10:54:12-05:00", + "updated_at": "2017-04-20T15:18:46-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 997233, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 316810, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + } + ] + } + } } ``` -To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. -Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: - -- whether the authentication was successful (`success`) -- the gateway ID for the payment (`gateway_payment_id`) -- the subscription ID (`subscription_id`) - -Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. - -It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. - -The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` - -### Example Redirect Flow - -You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: - -1. Create a subscription via API; it requires 3DS -2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. -3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id -4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to -5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied -6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. -7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known -8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not - -## Subscriptions Import - -Subscriptions can be “imported” via the API to handle the following scenarios: - -+ You already have existing subscriptions with specific start and renewal dates that you would like to import to Chargify -+ You already have credit cards stored in your provider’s vault and you would like to create subscriptions using those tokens - -Before importing, you should have already set up your products to match your offerings. Then, you can create Subscriptions via the API just like you normally would, but using a few special attributes. - -Full documentation on how import Subscriptions using the **import tool** in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#imports-0-0). +## Errors -### Important Notices and Disclaimers regarding Imports +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -Before performing a bulk import of subscriptions via the API, we suggest reading the [Subscriptions Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#important-notices-and-disclaimers) instructions to understand the repurcussions of a large import. -### Subscription Input Attributes +# Purge Subscription -The following _additional_ attributes to the subscription input attributes make imports possible: `next_billing_at`, `previous_billing_at`, and `import_mrr`. +For sites in test mode, you may purge individual subscriptions. -### Current Vault +Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer` -If you are using a Legacy gateway such as "eWAY Rapid (Legacy)" or "Stripe (Legacy)" then please contact Support for further instructions on subscription imports. +If you need to remove subscriptions from a live site, please contact support to discuss your use case. -### Braintree Blue (Braintree v2) Imports +### Delete customer and payment profile -Braintree Blue is Braintree’s newer (version 2) API. For this gateway, please provide the `vault_token` parameter with the value from Braintree’s “Customer ID” rather than the “Payment Profile Token”. At this time we do not use `current_vault_token` with the Braintree Blue gateway, and we only support a single payment profile per Braintree Customer. +The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile` -When importing PayPal type payment profiles, please set `payment_type` to `paypal_account`. +```csharp +PurgeSubscriptionAsync( + int subscriptionId, + int ack, + List cascade = null) +``` -### Stripe ACH Imports +## Parameters -If the bank account has already been verified, currently you will need to create the customer, create the payment profile in Chargify - setting verified=true, then create a subscription using the customer_id and payment_profile_id. +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `ack` | `int` | Query, Required | id of the customer. | +| `cascade` | [`List`](../../doc/models/subscription-purge-type.md) | Query, Optional | Options are "customer" or "payment_profile".
Use in query: `cascade[]=customer&cascade[]=payment_profile`. | -### Webhooks During Import +## Response Type -If no `next_billing_at` is provided, webhooks will be fired as normal. If you do set a future `next_billing_at`, only a subset of the webhooks are fired when the subscription is created. Keep reading for more information as to what webhooks will be fired under which scenarios. +`Task` -#### Successful creation with Billing Date +## Example Usage -Scenario: If `next_billing_at` provided +```csharp +int subscriptionId = 222; +int ack = 252; +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')try +{ + await subscriptionsController.PurgeSubscriptionAsync( + subscriptionId, + ack + ); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -+ `signup_success` -+ `billing_date_change` -#### Successful creation without Billing Date +# Preview Subscription -Scenario: If no `next_billing_at` provided +The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. -+ `signup_success` -+ `payment_success` +The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). -#### Unsuccessful creation +## Side effects -Scenario: If card can’t be charged, and no `next_billing_at` provided +A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. -+ signup_failure +## Taxable Subscriptions -#### Webhooks fired when next_billing_at is reached: +This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met: -+ `renewal_success or renewal_failure` -+ `payment_success or payment_failure` ++ Taxes must be configured on the subscription ++ The preview must be for the purchase of a taxable product or component, or combination of the two. ++ The subscription payload must contain a full billing or shipping address in order to calculate tax -### Date and Time Formats +For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions) -We will attempt to parse any string you send as the value of next_billing_at in to a date or time. For best results, use a known format like described in “Date and Time Specification” of RFC 2822 or ISO 8601 . +You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. -The following are all equivalent and will work as input to `next_billing_at`: +You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. -``` -Aug 06 2030 11:34:00 -0400 -Aug 06 2030 11:34 -0400 -2030-08-06T11:34:00-04:00 -8/6/2030 11:34:00 EDT -8/6/2030 8:34:00 PDT -2030-08-06T15:34:00Z -``` +## Non-taxable Subscriptions -You may also pass just a date, in which case we will assume the time to be noon +If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. +```csharp +PreviewSubscriptionAsync( + Models.CreateSubscriptionRequest body = null) ``` -2010-08-06 -``` - -## Subscription Hierarchies & WhoPays - -When subscription groups were first added to our Relationship Invoicing architecture, to group together invoices for related subscriptions and allow for complex customer hierarchies and WhoPays scenarios, they were designed to consist of a primary and a collection of group members. The primary would control many aspects of the group, such as when the consolidated invoice is generated. As of today, groups still function this way. - -In the future, the concept of a "primary" will be removed in order to offer more flexibility into group management and reduce confusion concerning what actions must be done on a primary level, rather than a member level. - -We have introduced a two scheme system as a bridge between these two group organizations. Scheme 1, which is relevant to all subscription groups today, marks the group as being "ruled" by a primary. - -When reading a subscription via API, they will return a top-level attribute called `group`, which will denote which scheme is being used. At this time, the `scheme` attribute will always be 1. - -### Subscription in a Customer Hierarchy - -For sites making use of the [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) and [Customer Hierarchy](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404900384141) features, it is possible to create subscriptions within a customer hierarchy. This can be achieved through the API by passing group parameters in the **Create Subscription** request. - -+ The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. - -When the `target` parameter specifies a customer that is already part of a hierarchy, the new subscription will become a member of the customer hierarchy as well. If the target customer is not part of a hierarchy, a new customer hierarchy will be created and both the target customer and the new subscription will become part of the hierarchy with the specified target customer set as the responsible payer for the hierarchy's subscriptions. - -Rather than specifying a customer, the `target` parameter could instead simply have a value of `self` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer. This will be true whether the customer is being created new, is already part of a hierarchy, or already exists outside a hierarchy. A valid payment method must also be specified in the subscription parameters. -Note that when creating subscriptions in a customer hierarchy, if the customer hierarchy does not already have a payment method, passing valid credit card attributes in the subscription parameters will also result in the payment method being established as the default payment method for the customer hierarchy irrespective of the responsible payer. +## Parameters -The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the default subscription group in the customer hierarchy. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the default subscription group in the customer hierarchy also. +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | -### Subscription in a Subscription Group +## Response Type -For sites making use of [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) it may be desireable to create a subscription as part of a [subscription group](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577356173) in order to rely on [invoice consolidation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404980119949). This can be achieved through the API by passing group parameters in the Create Subscription request. The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. +[`Task`](../../doc/models/subscription-preview-response.md) -The `target` parameters specify an existing subscription with which the newly created subscription should be grouped. If the target subscription is already part of a group, the new subscription will become a member of the group as well. If the target subscription is not part of a group, a new group will be created and both the target and the new subscription will become part of the group with the target as the group's primary subscription. +## Example Usage -The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the target subscription. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the target subscription also. +```csharp +CreateSubscriptionRequest body = new CreateSubscriptionRequest +{ + Subscription = new CreateSubscription + { + ProductHandle = "gold-product", + }, +}; -## Providing Agreement Acceptance Params +try +{ + SubscriptionPreviewResponse result = await subscriptionsController.PreviewSubscriptionAsync(body); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` -It is possible to provide a proof of customer's acceptance of terms and policies. -We will be storing this proof in case it might be required (i.e. chargeback). -Currently, we already keep it for subscriptions created via Public Signup Pages. -In order to create a subscription with the proof of agreement acceptance, you must provide additional parameters `agreement acceptance` with `ip_address` and at least one url to the policy that was accepted: `terms_url` or `privacy_policy_url`. Additional urls that can be provided: `return_refund_policy_url`, `delivery_policy_url` and -`secure_checkout_policy_url`. +## Example Response *(as JSON)* ```json - "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Jane", - "last_name": "Doe", - "email": "jd@chargify.test" +{ + "subscription_preview": { + "current_billing_manifest": { + "line_items": [ + { + "transaction_type": "charge", + "kind": "baseline", + "amount_in_cents": 5000, + "memo": "Gold Product (08/21/2018 - 09/21/2018)", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "product_id": 1, + "product_handle": "gold-product", + "product_name": "Gold Product", + "period_range_start": "13 Oct 2023", + "period_range_end": "13 Nov 2023" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 28000, + "memo": "Component name: 14 Unit names", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 462149, + "component_handle": "handle", + "component_name": "Component name" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 2000, + "memo": "Fractional Metered Components: 20.0 Fractional Metereds", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 426665, + "component_handle": "handle", + "component_name": "Fractional Metered Components" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 0, + "memo": "On/Off Component", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 426670, + "component_handle": "handle", + "component_name": "On/Off Component" + }, + { + "transaction_type": "adjustment", + "kind": "coupon", + "amount_in_cents": 0, + "memo": "Coupon: 1DOLLAR - You only get $1.00 off", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0 + } + ], + "total_in_cents": 35000, + "total_discount_in_cents": 0, + "total_tax_in_cents": 0, + "subtotal_in_cents": 35000, + "start_date": "2018-08-21T21:25:21Z", + "end_date": "2018-09-21T21:25:21Z", + "period_type": "recurring", + "existing_balance_in_cents": 0 }, - "agreement_acceptance": { - "ip_address": "1.2.3.4", - "terms_url": "https://terms.url", - "privacy_policy_url": "https://privacy_policy.url", - "return_refund_policy_url": "https://return_refund_policy.url", - "delivery_policy_url": "https://delivery_policy.url", - "secure_checkout_policy_url": "https://secure_checkout_policy.url" + "next_billing_manifest": { + "line_items": [ + { + "transaction_type": "charge", + "kind": "baseline", + "amount_in_cents": 5000, + "memo": "Gold Product (09/21/2018 - 10/21/2018)", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "product_id": 1, + "product_handle": "gold-product", + "product_name": "Gold Product" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 28000, + "memo": "Component name: 14 Unit names", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 462149, + "component_handle": "handle", + "component_name": "Component name" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 0, + "memo": "On/Off Component", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 426670, + "component_handle": "handle", + "component_name": "On/Off Component" + } + ], + "total_in_cents": 33000, + "total_discount_in_cents": 0, + "total_tax_in_cents": 0, + "subtotal_in_cents": 33000, + "start_date": "2018-09-21T21:25:21Z", + "end_date": "2018-10-21T21:25:21Z", + "period_type": "recurring", + "existing_balance_in_cents": 0 } } } ``` -**For Maxio Payments subscriptions, the agreement acceptance params are required, with at least terms_url provided.** -## Providing ACH Agreement params +# Read Subscription -It is also possible to provide a proof that a customer authorized ACH agreement terms. -The proof will be stored and the email will be sent to the customer with a copy of the terms (if enabled). -In order to create a subscription with the proof of authorized ACH agreement terms, you must provide the additional parameter `ach_agreement` with the following nested parameters: `agreement_terms`, `authorizer_first_name`, `authorizer_last_name` and `ip_address`. -Each of them is required. +Use this endpoint to find subscription details. -```json - "subscription": { - "product_handle": "gold-product", - "customer_attributes": { - "first_name": "Jane", - "last_name": "Doe", - "email": "jd@chargify.test" - }, - "bank_account_attributes": { - "bank_name": "Test Bank", - "bank_routing_number": "021000089", - "bank_account_number": "111111111111", - "bank_account_type": "checking", - "bank_account_holder_type": "business", - "payment_type": "bank_account" - }, - "ach_agreement": { - "agreement_terms": "ACH agreement terms", - "authorizer_first_name": "Jane", - "authorizer_last_name": "Doe", - "ip_address": "1.2.3.4" - } - } -``` +## Self-Service Page token + +Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. ```csharp -CreateSubscriptionAsync( - Models.CreateSubscriptionRequest body = null) +ReadSubscriptionAsync( + int subscriptionId, + List include = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `body` | [`CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `include` | [`List`](../../doc/models/subscription-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`. | ## Response Type @@ -655,47 +747,10 @@ CreateSubscriptionAsync( ## Example Usage ```csharp -CreateSubscriptionRequest body = new CreateSubscriptionRequest -{ - Subscription = new CreateSubscription - { - ProductHandle = "basic", - CustomerAttributes = new CustomerAttributes - { - FirstName = "Joe", - LastName = "Blow", - Email = "joe@example.com", - Organization = "Acme", - Reference = "XYZ", - Address = "123 Mass Ave.", - Address2 = "address_24", - City = "Boston", - State = "MA", - Zip = "02120", - Country = "US", - Phone = "(617) 111 - 0000", - }, - CreditCardAttributes = new PaymentProfileAttributes - { - FirstName = "Joe", - LastName = "Smith", - FullNumber = "4111111111111111", - CardType = CardType.Visa, - ExpirationMonth = PaymentProfileAttributesExpirationMonth.FromString("1"), - ExpirationYear = PaymentProfileAttributesExpirationYear.FromString("2021"), - BillingAddress = "123 Mass Ave.", - BillingAddress2 = "billing_address_22", - BillingCity = "Boston", - BillingState = "MA", - BillingCountry = "US", - BillingZip = "02120", - }, - }, -}; - -try +int subscriptionId = 222; +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')try { - SubscriptionResponse result = await subscriptionsController.CreateSubscriptionAsync(body); + SubscriptionResponse result = await subscriptionsController.ReadSubscriptionAsync(subscriptionId); } catch (ApiException e) { @@ -724,7 +779,7 @@ catch (ApiException e) "created_at": "2016-11-14T14:48:10-05:00", "updated_at": "2016-11-14T15:24:41-05:00", "cancellation_message": null, - "cancellation_method": "merchant_api", + "cancellation_method": null, "cancel_at_end_of_period": null, "canceled_at": null, "current_period_started_at": "2016-11-14T14:48:10-05:00", @@ -737,6 +792,7 @@ catch (ApiException e) "snap_day": null, "reason_code": null, "receives_invoice_emails": false, + "net_terms": 0, "customer": { "first_name": "Curtis", "last_name": "Test", @@ -835,83 +891,80 @@ catch (ApiException e) "next_product_id": null, "coupon_use_count": 1, "coupon_uses_allowed": 1, - "next_product_handle": null, - "stored_credential_transaction_id": 125566112256688, - "dunning_communication_delay_enabled": true, - "dunning_communication_delay_time_zone": "Eastern Time (US & Canada)" + "stored_credential_transaction_id": 166411599220288, + "on_hold_at": null, + "scheduled_cancellation_at": "2016-11-14T14:48:13-05:00" } } ``` -## Errors -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +# Override Subscription +This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. -# List Subscriptions +This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. -This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. +Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.** -## Search for a subscription +Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. -Use the query strings below to search for a subscription using the criteria available. The return value will be an array. +If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. -## Self-Service Page token +## Limitations -Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. +When passing `current_period_starts_at` some validations are made: + +1. The subscription needs to be unbilled (no statements or invoices). +2. The value passed must be a valid date/time. We recommend using the iso 8601 format. +3. The value passed must be before the current date/time. + +If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. ```csharp -ListSubscriptionsAsync( - Models.ListSubscriptionsInput input) +OverrideSubscriptionAsync( + int subscriptionId, + Models.OverrideSubscriptionRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `state` | [`SubscriptionStateFilter?`](../../doc/models/subscription-state-filter.md) | Query, Optional | The current state of the subscription | -| `product` | `int?` | Query, Optional | The product id of the subscription. (Note that the product handle cannot be used.) | -| `productPricePointId` | `int?` | Query, Optional | The ID of the product price point. If supplied, product is required | -| `coupon` | `int?` | Query, Optional | The numeric id of the coupon currently applied to the subscription. (This can be found in the URL when editing a coupon. Note that the coupon code cannot be used.) | -| `dateField` | [`SubscriptionDateField?`](../../doc/models/subscription-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Allowed Values: , current_period_ends_at, current_period_starts_at, created_at, activated_at, canceled_at, expires_at, trial_started_at, trial_ended_at, updated_at | -| `startDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2022-07-01`. | -| `endDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2022-08-01`. | -| `startDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | -| `endDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-08-01 10:00:05`. | -| `metadata` | `Dictionary` | Query, Optional | The value of the metadata field specified in the parameter. Use in query `metadata[my-field]=value&metadata[other-field]=another_value`. | -| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `sort` | [`SubscriptionSort?`](../../doc/models/subscription-sort.md) | Query, Optional | The attribute by which to sort | -| `include` | [`List`](../../doc/models/subscription-list-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=self_service_page_token`. | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`OverrideSubscriptionRequest`](../../doc/models/override-subscription-request.md) | Body, Optional | Only these fields are available to be set. | ## Response Type -[`Task>`](../../doc/models/subscription-response.md) +`Task` ## Example Usage ```csharp -ListSubscriptionsInput listSubscriptionsInput = new ListSubscriptionsInput +int subscriptionId = 222; +OverrideSubscriptionRequest body = new OverrideSubscriptionRequest { - Page = 2, - PerPage = 50, - StartDate = DateTime.Parse("2022-07-01"), - EndDate = DateTime.Parse("2022-08-01"), - StartDatetime = DateTime.ParseExact("2022-07-01 09:00:05", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), - EndDatetime = DateTime.ParseExact("2022-08-01 10:00:05", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), - Sort = SubscriptionSort.SignupDate, -Liquid error: Value cannot be null. (Parameter 'key')}; + Subscription = new OverrideSubscription + { + ActivatedAt = DateTime.ParseExact("1999-12-01T10:28:34-05:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + CanceledAt = DateTime.ParseExact("2000-12-31T10:28:34-05:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + CancellationMessage = "Original cancellation in 2000", + ExpiresAt = DateTime.ParseExact("2001-07-15T10:28:34-05:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + }, +}; try { - List result = await subscriptionsController.ListSubscriptionsAsync(listSubscriptionsInput); + await subscriptionsController.OverrideSubscriptionAsync( + subscriptionId, + body + ); } catch (ApiException e) { @@ -920,55 +973,21 @@ catch (ApiException e) } ``` +## Errors -# Update Subscription - -The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. - -## Update Subscription Payment Method - -Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. - -Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. - -You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. - -## Product Change - -This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. - -To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. - -### Delayed Product Change - -This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. - -This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. - -You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle` - -**Note: To cancel a delayed product change, set `next_product_id` to an empty string.** - -## Billing Date Changes - -### Regular Billing Date Changes - -Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. - -Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. - -The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | -### Snap Day Changes -For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. +# Create Prepaid Subscription -Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. +Use this endpoint to update a subscription's prepaid configuration. ```csharp -UpdateSubscriptionAsync( +CreatePrepaidSubscriptionAsync( int subscriptionId, - Models.UpdateSubscriptionRequest body = null) + Models.UpsertPrepaidConfigurationRequest body = null) ``` ## Parameters @@ -976,33 +995,30 @@ UpdateSubscriptionAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | | `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`UpdateSubscriptionRequest`](../../doc/models/update-subscription-request.md) | Body, Optional | - | +| `body` | [`UpsertPrepaidConfigurationRequest`](../../doc/models/upsert-prepaid-configuration-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/subscription-response.md) +[`Task`](../../doc/models/prepaid-configuration-response.md) ## Example Usage ```csharp int subscriptionId = 222; -UpdateSubscriptionRequest body = new UpdateSubscriptionRequest +UpsertPrepaidConfigurationRequest body = new UpsertPrepaidConfigurationRequest { - Subscription = new UpdateSubscription + PrepaidConfiguration = new UpsertPrepaidConfiguration { - CreditCardAttributes = new CreditCardAttributes - { - FullNumber = "4111111111111111", - ExpirationMonth = "10", - ExpirationYear = "2030", - }, - NextBillingAt = "2010-08-06T15:34:00Z", + InitialFundingAmountInCents = 50000L, + ReplenishToAmountInCents = 50000L, + AutoReplenish = true, + ReplenishThresholdAmountInCents = 10000L, }, }; try { - SubscriptionResponse result = await subscriptionsController.UpdateSubscriptionAsync( + PrepaidConfigurationResponse result = await subscriptionsController.CreatePrepaidSubscriptionAsync( subscriptionId, body ); @@ -1018,740 +1034,640 @@ catch (ApiException e) ```json { - "subscription": { - "id": 18220670, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2017-06-27T13:45:15-05:00", - "created_at": "2017-06-27T13:45:13-05:00", - "updated_at": "2017-06-30T09:26:50-05:00", - "expires_at": null, - "balance_in_cents": 10000, - "current_period_ends_at": "2017-06-30T12:00:00-05:00", - "next_assessment_at": "2017-06-30T12:00:00-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": "end", - "cancellation_method": null, - "current_period_started_at": "2017-06-27T13:45:13-05:00", - "previous_state": "active", - "signup_payment_id": 191819284, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 0, - "product_version_number": 1, - "payment_type": null, - "referral_code": "d3pw7f", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": 10000, - "receives_invoice_emails": false, - "customer": { - "id": 17780587, - "first_name": "Catie", - "last_name": "Test", - "organization": "Acme, Inc.", - "email": "catie@example.com", - "created_at": "2017-06-27T13:01:05-05:00", - "updated_at": "2017-06-30T09:23:10-05:00", - "reference": "123ABC", - "address": "123 Anywhere Street", - "address_2": "Apartment #10", - "city": "Los Angeles", - "state": "CA", - "zip": "90210", - "country": "US", - "phone": "555-555-5555", - "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", - "portal_invite_last_accepted_at": null, - "verified": true, - "portal_customer_created_at": "2017-06-27T13:01:08-05:00", - "cc_emails": "support@example.com", - "tax_exempt": true - }, - "product": { - "id": 4470347, - "name": "Zero Dollar Product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-03-23T10:54:12-05:00", - "updated_at": "2017-04-20T15:18:46-05:00", - "price_in_cents": 0, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 997233, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 316810, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" - } - ] - } + "prepaid_configuration": { + "id": 55, + "initial_funding_amount_in_cents": 2500, + "auto_replenish": true, + "replenish_to_amount_in_cents": 50000, + "replenish_threshold_amount_in_cents": 10000 } } ``` -## Errors -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +# Create Subscription + +Full documentation on how subscriptions operate within Chargify can be located under the following topics: + ++ [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction) ++ [Subscriptions Actions](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions) ++ [Subscription Cancellation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions#initiate-cancellation) ++ [Subscription Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021-Reactivating-and-Resuming) ++ [Subscription Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821-Imports) + +When creating a subscription, you must specify a product and a customer. Credit card details may be required, depending on the options for the Product being subscribed ([see Product Options](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221#payment-method-settings)). + +The product may be specified by `product_id` or by `product_handle` (API Handle). In similar fashion, to pass a particular product price point, you may either use `product_price_point_handle` or `product_price_point_id`. + +An existing customer may be specified by a `customer_id` (ID within Chargify) or a `customer_reference` (unique value within your app that you have shared with Chargify via the reference attribute on a customer). You may also pass in an existing payment profile for that customer with `payment_profile_id`. A new customer may be created by providing `customer_attributes`. + +Credit card details may be required, depending on the options for the product being subscribed. The product can be specified by `product_id` or by `product_handle` (API Handle). + +If you are creating a subscription with a payment profile, the attribute to send will be `credit_card_attributes` or `bank_account_attributes` for ACH and Direct Debit. That said, when you read the subscription after creation, we return the profile details under `credit_card` or `bank_account`. + +## Taxable Subscriptions + +If your intent is to charge your subscribers tax via [Avalara Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405275711885-Avalara-VAT-Tax) or [Custom Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405069041549-Custom-Taxes), there are a few considerations to be made regarding collecting subscription data. +For subscribers to be eligible to be taxed, the following information for the `customer` object or `payment_profile` object must by supplied: + ++ A subscription to a [taxable product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221-Product-Editing#tax-settings) ++ [Full valid billing or shipping address](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#full-address-required-for-taxable-subscriptions) to identify the tax locale ++ The portion of the address that houses the [state information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-state-format-for-taxable-subscriptions) of either adddress must adhere to the ISO standard of a 2-3 character limit/format. ++ The portion of the address that houses the [country information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-country-format-for-taxable-subscriptions) must adhere to the ISO standard of a 2 character limit/format. + +## Subscription Request Examples + +The subscription examples below will be split into two sections. + +The first section, "Subscription Customization", will focus on passing different information with a subscription, such as components, calendar billing, and custom fields. These examples will presume you are using a secure `chargify_token` generated by Chargify.js. + +The second section, "Passing Payment Information", will focus on passing payment information into Chargify. Please be aware that collecting and sending Chargify raw card details requires PCI compliance on your end; these examples are provided as guidance. If your business is not PCI compliant, we recommend using Chargify.js to collect credit cards or bank accounts. + +# Subscription Customization + +## With Components + +Different components require slightly different data. For example, quantity-based and on/off components accept `allocated_quantity`, while metered components accept `unit_balance`. + +When creating a subscription with a component, a `price_point_id` can be passed in along with the `component_id` to specify which price point to use. If not passed in, the default price point will be used. + +Note: if an invalid `price_point_id` is used, the subscription will still proceed but will use the component's default price point. + +Components and their price points may be added by ID or by handle. See the example request body labeled "Components By Handle (Quantity-Based)"; the format will be the same for other component types. + +## With Coupon(s) + +Pass an array of `coupon_codes`. See the example request body "With Coupon". + +## With Manual Invoice Collection + +The `invoice` collection method works only on legacy Statement Architecture. + +On Relationship Invoicing Architecture use the `remittance` collection method. + +## Prepaid Subscription + +A prepaid subscription can be created with the usual subscription creation parameters, specifying `prepaid` as the `payment_collection_method` and including a nested `prepaid_configuration`. +After a prepaid subscription has been created, additional funds can be manually added to the prepayment account through the [Create Prepayment Endpoint](https://developers.chargify.com/docs/api-docs/7ec482de77ba7-create-prepayment). -# Read Subscription +Prepaid subscriptions do not work on legacy Statement Architecture. -Use this endpoint to find subscription details. +## With Metafields -## Self-Service Page token +Metafields can either attach to subscriptions or customers. Metafields are popuplated with the supplied metadata to the resource specified. -Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. +If the metafield doesn't exist yet, it will be created on-the-fly. -```csharp -ReadSubscriptionAsync( - int subscriptionId, - List include = null) -``` +## With Custom Pricing -## Parameters +Custom pricing is pricing specific to the subscription in question. +Create a subscription with custom pricing by passing pricing information instead of a price point. +For a custom priced product, pass the custom_price object in place of `product_price_point_id`. For a custom priced component, pass the `custom_price` object within the component object. +Custom prices and price points can exist in harmony on a subscription. -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `include` | [`List`](../../doc/models/subscription-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`. | +# Passing Payment Information -## Response Type +## Subscription with Chargify.js token -[`Task`](../../doc/models/subscription-response.md) +The `chargify_token` can be obtained using [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). The token represents payment profile attributes that were provided by the customer in their browser and stored at the payment gateway. -## Example Usage +The `payment_type` attribute may either be `credit_card` or `bank_account`, depending on the type of payment method being added. If a bank account is being passed, the payment attributes should be changed to `bank_account_attributes`. -```csharp -int subscriptionId = 222; -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')try +```json { - SubscriptionResponse result = await subscriptionsController.ReadSubscriptionAsync(subscriptionId); + "subscription": { + "product_handle": "pro-plan", + "customer_attributes": { + "first_name": "Joe", + "last_name": "Smith", + "email": "j.smith@example.com" + }, + "credit_card_attributes": { + "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn", + "payment_type": "credit_card" + } + } } -catch (ApiException e) +``` + +## Subscription with vault token + +If you already have a customer and card stored in your payment gateway, you may create a subscription with a `vault_token`. Providing the last_four, card type and expiration date will allow the card to be displayed properly in the Chargify UI. + +```json { - // TODO: Handle exception here - Console.WriteLine(e.Message); + "subscription": { + "product_handle": "pro-plan", + "customer_attributes": { + "first_name": "Joe", + "last_name": "Smith", + "email": "j.smith@example.com" + }, + "credit_card_attributes": { + first_name: "Joe, + last_name: "Smith", + card_type: "visa", + expiration_month: "05", + expiration_year: "2025", + last_four: "1234", + vault_token: "12345abc", + current_vault: "braintree_blue" + } } ``` -## Example Response *(as JSON)* +## Subscription with Credit Card + +```json +"subscription": { + "product_handle": "basic", + "customer_attributes": { + "first_name": "Joe", + "last_name": "Blow", + "email": "joe@example.com", + "zip": "02120", + "state": "MA", + "reference": "XYZ", + "phone": "(617) 111 - 0000", + "organization": "Acme", + "country": "US", + "city": "Boston", + "address_2": null, + "address": "123 Mass Ave." + }, + "credit_card_attributes": { + "last_name": "Smith", + "first_name": "Joe", + "full_number": "4111111111111111", + "expiration_year": "2021", + "expiration_month": "1", + "card_type": "visa", + "billing_zip": "02120", + "billing_state": "MA", + "billing_country": "US", + "billing_city": "Boston", + "billing_address_2": null, + "billing_address": "123 Mass Ave." + } +} +``` + +## Subscription with ACH as Payment Profile ```json { "subscription": { - "id": 15236915, - "state": "active", - "balance_in_cents": 0, - "total_revenue_in_cents": 14000, - "product_price_in_cents": 1000, - "product_version_number": 7, - "current_period_ends_at": "2016-11-15T14:48:10-05:00", - "next_assessment_at": "2016-11-15T14:48:10-05:00", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2016-11-14T14:48:12-05:00", - "expires_at": null, - "created_at": "2016-11-14T14:48:10-05:00", - "updated_at": "2016-11-14T15:24:41-05:00", - "cancellation_message": null, - "cancellation_method": null, - "cancel_at_end_of_period": null, - "canceled_at": null, - "current_period_started_at": "2016-11-14T14:48:10-05:00", - "previous_state": "active", - "signup_payment_id": 162269766, - "signup_revenue": "260.00", - "delayed_cancel_at": null, - "coupon_code": "5SNN6HFK3GBH", - "payment_collection_method": "automatic", - "snap_day": null, - "reason_code": null, - "receives_invoice_emails": false, - "net_terms": 0, - "customer": { - "first_name": "Curtis", - "last_name": "Test", - "email": "curtis@example.com", - "cc_emails": "jeff@example.com", - "organization": "", - "reference": null, - "id": 14714298, - "created_at": "2016-11-14T14:48:10-05:00", - "updated_at": "2016-11-14T14:48:13-05:00", - "address": "123 Anywhere Street", - "address_2": "", - "city": "Boulder", - "state": "CO", - "zip": "80302", + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Joe", + "last_name": "Blow", + "email": "joe@example.com", + "zip": "02120", + "state": "MA", + "reference": "XYZ", + "phone": "(617) 111 - 0000", + "organization": "Acme", "country": "US", - "phone": "", - "verified": false, - "portal_customer_created_at": "2016-11-14T14:48:13-05:00", - "portal_invite_last_sent_at": "2016-11-14T14:48:13-05:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "vat_number": "012345678" - }, - "product": { - "id": 3792003, - "name": "$10 Basic Plan", - "handle": "basic", - "description": "lorem ipsum", - "accounting_code": "basic", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "day", - "initial_charge_in_cents": null, - "expiration_interval": null, - "expiration_interval_unit": "never", - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "initial_charge_after_trial": false, - "return_params": "", - "request_credit_card": false, - "require_credit_card": false, - "created_at": "2016-03-24T13:38:39-04:00", - "updated_at": "2016-11-03T13:03:05-04:00", - "archived_at": null, - "update_return_url": "", - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "handle": "billing-plans", - "accounting_code": null, - "description": "" - }, - "public_signup_pages": [ - { - "id": 281054, - "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" - }, - { - "id": 281240, - "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" - }, - { - "id": 282694, - "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" - } - ], - "taxable": false, - "version_number": 7, - "product_price_point_name": "Default" - }, - "credit_card": { - "id": 10191713, - "payment_type": "credit_card", - "first_name": "Curtis", - "last_name": "Test", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2026, - "billing_address": "123 Anywhere Street", - "billing_address_2": "", - "billing_city": "Boulder", - "billing_state": null, - "billing_country": "", - "billing_zip": "80302", - "current_vault": "bogus", - "vault_token": "1", - "customer_vault_token": null, - "customer_id": 14714298 + "city": "Boston", + "address_2": null, + "address": "123 Mass Ave." }, - "payment_type": "credit_card", - "referral_code": "w7kjc9", - "next_product_id": null, - "coupon_use_count": 1, - "coupon_uses_allowed": 1, - "stored_credential_transaction_id": 166411599220288, - "on_hold_at": null, - "scheduled_cancellation_at": "2016-11-14T14:48:13-05:00" + "bank_account_attributes": { + "bank_name": "Best Bank", + "bank_routing_number": "021000089", + "bank_account_number": "111111111111", + "bank_account_type": "checking", + "bank_account_holder_type": "business", + "payment_type": "bank_account" + } } } ``` +## Subscription with PayPal payment profile -# Override Subscription - -This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. - -This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. - -Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.** - -Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. - -If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. +### With the nonce from Braintree JS -## Limitations +```json +{ "subscription": { + "product_handle":"test-product-b", + "customer_attributes": { + "first_name":"Amelia", + "last_name":"Johnson", + "email":"amelia@example.com", + "organization":"My Awesome Company" + }, + "payment_profile_attributes":{ + "paypal_email": "amelia@example.com", + "current_vault": "braintree_blue", + "payment_method_nonce":"abc123", + "payment_type":"paypal_account" + } + } +``` -When passing `current_period_starts_at` some validations are made: +### With the Braintree Customer ID as the vault token: -1. The subscription needs to be unbilled (no statements or invoices). -2. The value passed must be a valid date/time. We recommend using the iso 8601 format. -3. The value passed must be before the current date/time. +```json +{ "subscription": { + "product_handle":"test-product-b", + "customer_attributes": { + "first_name":"Amelia", + "last_name":"Johnson", + "email":"amelia@example.com", + "organization":"My Awesome Company" + }, + "payment_profile_attributes":{ + "paypal_email": "amelia@example.com", + "current_vault": "braintree_blue", + "vault_token":"58271347", + "payment_type":"paypal_account" + } + } +``` -If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. +## Subscription using GoCardless Bank Number -```csharp -OverrideSubscriptionAsync( - int subscriptionId, - Models.OverrideSubscriptionRequest body = null) -``` +These examples creates a customer, bank account and mandate in GoCardless. -## Parameters +For more information on GoCardless, please view the following two resources: -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`OverrideSubscriptionRequest`](../../doc/models/override-subscription-request.md) | Body, Optional | Only these fields are available to be set. | ++ [Payment Profiles via API for GoCardless](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#gocardless) -## Response Type ++ [Full documentation on GoCardless](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404501889677) -`Task` ++ [Using Chargify.js with GoCardless - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-direct-debit-gocardless-gateway) -## Example Usage ++ [Using Chargify.js with GoCardless - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-direct-debit-gocardless-gateway) -```csharp -int subscriptionId = 222; -OverrideSubscriptionRequest body = new OverrideSubscriptionRequest +```json { - Subscription = new OverrideSubscription - { - ActivatedAt = DateTime.ParseExact("1999-12-01T10:28:34-05:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), - CanceledAt = DateTime.ParseExact("2000-12-31T10:28:34-05:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), - CancellationMessage = "Original cancellation in 2000", - ExpiresAt = DateTime.ParseExact("2001-07-15T10:28:34-05:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", - provider: CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind), + "subscription": { + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Jane", + "last_name": "Doe", + "email": "jd@chargify.test" }, -}; - -try -{ - await subscriptionsController.OverrideSubscriptionAsync( - subscriptionId, - body - ); + "bank_account_attributes": { + "bank_name": "Royal Bank of France", + "bank_account_number": "0000000", + "bank_routing_number": "0003", + "bank_branch_code": "00006", + "payment_type": "bank_account", + "billing_address": "20 Place de la Gare", + "billing_city": "Colombes", + "billing_state": "Île-de-France", + "billing_zip": "92700", + "billing_country": "FR" + } + } } -catch (ApiException e) +``` + +## Subscription using GoCardless IBAN Number + +```json { - // TODO: Handle exception here - Console.WriteLine(e.Message); + "subscription": { + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Jane", + "last_name": "Doe", + "email": "jd@chargify.test" + }, + "bank_account_attributes": { + "bank_name": "French Bank", + "bank_iban": "FR1420041010050500013M02606", + "payment_type": "bank_account", + "billing_address": "20 Place de la Gare", + "billing_city": "Colombes", + "billing_state": "Île-de-France", + "billing_zip": "92700", + "billing_country": "FR" + } + } } ``` -## Errors +## Subscription using Stripe SEPA Direct Debit -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | +For more information on Stripe Direct Debit, please view the following two resources: ++ [Payment Profiles via API for Stripe SEPA Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#sepa-direct-debit) -# Read Subscription by Reference ++ [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) -Use this endpoint to find a subscription by its reference. ++ [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) -```csharp -ReadSubscriptionByReferenceAsync( - string reference = null) ++ [Using Chargify.js with Stripe SEPA Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) + +```json +{ + "subscription": { + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Jane", + "last_name": "Doe", + "email": "jd@chargify.test" + }, + "bank_account_attributes": { + "bank_name": "Test Bank", + "bank_iban": "DE89370400440532013000", + "payment_type": "bank_account" + } + } +} ``` -## Parameters +## Subscription using Stripe BECS Direct Debit -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `reference` | `string` | Query, Optional | Subscription reference | +For more information on Stripe Direct Debit, please view the following two resources: -## Response Type ++ [Payment Profiles via API for Stripe BECS Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#stripe-becs-direct-debit) -[`Task`](../../doc/models/subscription-response.md) ++ [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) -## Example Usage ++ [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) -```csharp -try -{ - SubscriptionResponse result = await subscriptionsController.ReadSubscriptionByReferenceAsync(); -} -catch (ApiException e) ++ [Using Chargify.js with Stripe BECS Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-becs-direct-debit-stripe-gateway) + +```json { - // TODO: Handle exception here - Console.WriteLine(e.Message); + "subscription": { + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Jane", + "last_name": "Doe", + "email": "jd@chargify.test" + }, + "bank_account_attributes": { + "bank_name": "Test Bank", + "bank_branch_code": "000000", + "bank_account_number": "000123456", + "payment_type": "bank_account" + } + } } ``` +## 3D Secure - Stripe -# Purge Subscription - -For sites in test mode, you may purge individual subscriptions. - -Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer` - -If you need to remove subscriptions from a live site, please contact support to discuss your use case. - -### Delete customer and payment profile - -The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile` +It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: -```csharp -PurgeSubscriptionAsync( - int subscriptionId, - int ack, - List cascade = null) +```json +{ + "errors": [ + "Your card was declined. This transaction requires 3D secure authentication." + ], + "gateway_payment_id": "pi_1F0aGoJ2UDb3Q4av7zU3sHPh", + "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", + "action_link": "http://acme.chargify.com/3d-secure/pi_1F0aGoJ2UDb3Q4av7zU3sHPh?one_time_token_id=242" +} ``` -## Parameters +To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. +Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `ack` | `int` | Query, Required | id of the customer. | -| `cascade` | [`List`](../../doc/models/subscription-purge-type.md) | Query, Optional | Options are "customer" or "payment_profile".
Use in query: `cascade[]=customer&cascade[]=payment_profile`. | +- whether the authentication was successful (`success`) +- the gateway ID for the payment (`gateway_payment_id`) +- the subscription ID (`subscription_id`) -## Response Type +Lastly, you can also specify a `redirect_url` within the `action_link` URL if you’d like to redirect a customer back to your site. -`Task` +It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. -## Example Usage +The final URL that you send a customer to to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` -```csharp -int subscriptionId = 222; -int ack = 252; -Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')try -{ - await subscriptionsController.PurgeSubscriptionAsync( - subscriptionId, - ack - ); -} -catch (ApiException e) +## 3D Secure - Checkout + +It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: + +```json { - // TODO: Handle exception here - Console.WriteLine(e.Message); + "errors": [ + "Your card was declined. This transaction requires 3D secure authentication." + ], + "gateway_payment_id": "pay_6gjofv7dlyrkpizlolsuspvtiu", + "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", + "action_link": "http://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123" } ``` +To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. +Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: -# Create Prepaid Subscription +- whether the authentication was successful (`success`) +- the gateway ID for the payment (`gateway_payment_id`) +- the subscription ID (`subscription_id`) -Use this endpoint to update a subscription's prepaid configuration. +Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. -```csharp -CreatePrepaidSubscriptionAsync( - int subscriptionId, - Models.UpsertPrepaidConfigurationRequest body = null) -``` +It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. -## Parameters +The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`UpsertPrepaidConfigurationRequest`](../../doc/models/upsert-prepaid-configuration-request.md) | Body, Optional | - | +### Example Redirect Flow -## Response Type +You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: -[`Task`](../../doc/models/prepaid-configuration-response.md) +1. Create a subscription via API; it requires 3DS +2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. +3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id +4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to +5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied +6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. +7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known +8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not -## Example Usage +## Subscriptions Import -```csharp -int subscriptionId = 222; -UpsertPrepaidConfigurationRequest body = new UpsertPrepaidConfigurationRequest -{ - PrepaidConfiguration = new UpsertPrepaidConfiguration - { - InitialFundingAmountInCents = 50000L, - ReplenishToAmountInCents = 50000L, - AutoReplenish = true, - ReplenishThresholdAmountInCents = 10000L, - }, -}; +Subscriptions can be “imported” via the API to handle the following scenarios: -try -{ - PrepaidConfigurationResponse result = await subscriptionsController.CreatePrepaidSubscriptionAsync( - subscriptionId, - body - ); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` ++ You already have existing subscriptions with specific start and renewal dates that you would like to import to Chargify ++ You already have credit cards stored in your provider’s vault and you would like to create subscriptions using those tokens -## Example Response *(as JSON)* +Before importing, you should have already set up your products to match your offerings. Then, you can create Subscriptions via the API just like you normally would, but using a few special attributes. -```json -{ - "prepaid_configuration": { - "id": 55, - "initial_funding_amount_in_cents": 2500, - "auto_replenish": true, - "replenish_to_amount_in_cents": 50000, - "replenish_threshold_amount_in_cents": 10000 - } -} -``` +Full documentation on how import Subscriptions using the **import tool** in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#imports-0-0). +### Important Notices and Disclaimers regarding Imports -# Preview Subscription +Before performing a bulk import of subscriptions via the API, we suggest reading the [Subscriptions Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#important-notices-and-disclaimers) instructions to understand the repurcussions of a large import. -The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. +### Subscription Input Attributes -The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). +The following _additional_ attributes to the subscription input attributes make imports possible: `next_billing_at`, `previous_billing_at`, and `import_mrr`. -## Side effects +### Current Vault -A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. +If you are using a Legacy gateway such as "eWAY Rapid (Legacy)" or "Stripe (Legacy)" then please contact Support for further instructions on subscription imports. -## Taxable Subscriptions +### Braintree Blue (Braintree v2) Imports -This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met: +Braintree Blue is Braintree’s newer (version 2) API. For this gateway, please provide the `vault_token` parameter with the value from Braintree’s “Customer ID” rather than the “Payment Profile Token”. At this time we do not use `current_vault_token` with the Braintree Blue gateway, and we only support a single payment profile per Braintree Customer. -+ Taxes must be configured on the subscription -+ The preview must be for the purchase of a taxable product or component, or combination of the two. -+ The subscription payload must contain a full billing or shipping address in order to calculate tax +When importing PayPal type payment profiles, please set `payment_type` to `paypal_account`. -For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions) +### Stripe ACH Imports -You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. +If the bank account has already been verified, currently you will need to create the customer, create the payment profile in Chargify - setting verified=true, then create a subscription using the customer_id and payment_profile_id. -You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. +### Webhooks During Import -## Non-taxable Subscriptions +If no `next_billing_at` is provided, webhooks will be fired as normal. If you do set a future `next_billing_at`, only a subset of the webhooks are fired when the subscription is created. Keep reading for more information as to what webhooks will be fired under which scenarios. -If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. +#### Successful creation with Billing Date -```csharp -PreviewSubscriptionAsync( - Models.CreateSubscriptionRequest body = null) -``` +Scenario: If `next_billing_at` provided -## Parameters ++ `signup_success` ++ `billing_date_change` -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | +#### Successful creation without Billing Date -## Response Type +Scenario: If no `next_billing_at` provided -[`Task`](../../doc/models/subscription-preview-response.md) ++ `signup_success` ++ `payment_success` -## Example Usage +#### Unsuccessful creation -```csharp -CreateSubscriptionRequest body = new CreateSubscriptionRequest -{ - Subscription = new CreateSubscription - { - ProductHandle = "gold-product", - }, -}; +Scenario: If card can’t be charged, and no `next_billing_at` provided -try -{ - SubscriptionPreviewResponse result = await subscriptionsController.PreviewSubscriptionAsync(body); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` ++ signup_failure -## Example Response *(as JSON)* +#### Webhooks fired when next_billing_at is reached: -```json -{ - "subscription_preview": { - "current_billing_manifest": { - "line_items": [ - { - "transaction_type": "charge", - "kind": "baseline", - "amount_in_cents": 5000, - "memo": "Gold Product (08/21/2018 - 09/21/2018)", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "product_id": 1, - "product_handle": "gold-product", - "product_name": "Gold Product", - "period_range_start": "13 Oct 2023", - "period_range_end": "13 Nov 2023" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 28000, - "memo": "Component name: 14 Unit names", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 462149, - "component_handle": "handle", - "component_name": "Component name" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 2000, - "memo": "Fractional Metered Components: 20.0 Fractional Metereds", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 426665, - "component_handle": "handle", - "component_name": "Fractional Metered Components" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 0, - "memo": "On/Off Component", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 426670, - "component_handle": "handle", - "component_name": "On/Off Component" - }, - { - "transaction_type": "adjustment", - "kind": "coupon", - "amount_in_cents": 0, - "memo": "Coupon: 1DOLLAR - You only get $1.00 off", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0 - } - ], - "total_in_cents": 35000, - "total_discount_in_cents": 0, - "total_tax_in_cents": 0, - "subtotal_in_cents": 35000, - "start_date": "2018-08-21T21:25:21Z", - "end_date": "2018-09-21T21:25:21Z", - "period_type": "recurring", - "existing_balance_in_cents": 0 ++ `renewal_success or renewal_failure` ++ `payment_success or payment_failure` + +### Date and Time Formats + +We will attempt to parse any string you send as the value of next_billing_at in to a date or time. For best results, use a known format like described in “Date and Time Specification” of RFC 2822 or ISO 8601 . + +The following are all equivalent and will work as input to `next_billing_at`: + +``` +Aug 06 2030 11:34:00 -0400 +Aug 06 2030 11:34 -0400 +2030-08-06T11:34:00-04:00 +8/6/2030 11:34:00 EDT +8/6/2030 8:34:00 PDT +2030-08-06T15:34:00Z +``` + +You may also pass just a date, in which case we will assume the time to be noon + +``` +2010-08-06 +``` + +## Subscription Hierarchies & WhoPays + +When subscription groups were first added to our Relationship Invoicing architecture, to group together invoices for related subscriptions and allow for complex customer hierarchies and WhoPays scenarios, they were designed to consist of a primary and a collection of group members. The primary would control many aspects of the group, such as when the consolidated invoice is generated. As of today, groups still function this way. + +In the future, the concept of a "primary" will be removed in order to offer more flexibility into group management and reduce confusion concerning what actions must be done on a primary level, rather than a member level. + +We have introduced a two scheme system as a bridge between these two group organizations. Scheme 1, which is relevant to all subscription groups today, marks the group as being "ruled" by a primary. + +When reading a subscription via API, they will return a top-level attribute called `group`, which will denote which scheme is being used. At this time, the `scheme` attribute will always be 1. + +### Subscription in a Customer Hierarchy + +For sites making use of the [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) and [Customer Hierarchy](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404900384141) features, it is possible to create subscriptions within a customer hierarchy. This can be achieved through the API by passing group parameters in the **Create Subscription** request. + ++ The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. + +When the `target` parameter specifies a customer that is already part of a hierarchy, the new subscription will become a member of the customer hierarchy as well. If the target customer is not part of a hierarchy, a new customer hierarchy will be created and both the target customer and the new subscription will become part of the hierarchy with the specified target customer set as the responsible payer for the hierarchy's subscriptions. + +Rather than specifying a customer, the `target` parameter could instead simply have a value of `self` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer. This will be true whether the customer is being created new, is already part of a hierarchy, or already exists outside a hierarchy. A valid payment method must also be specified in the subscription parameters. + +Note that when creating subscriptions in a customer hierarchy, if the customer hierarchy does not already have a payment method, passing valid credit card attributes in the subscription parameters will also result in the payment method being established as the default payment method for the customer hierarchy irrespective of the responsible payer. + +The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the default subscription group in the customer hierarchy. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the default subscription group in the customer hierarchy also. + +### Subscription in a Subscription Group + +For sites making use of [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) it may be desireable to create a subscription as part of a [subscription group](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577356173) in order to rely on [invoice consolidation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404980119949). This can be achieved through the API by passing group parameters in the Create Subscription request. The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. + +The `target` parameters specify an existing subscription with which the newly created subscription should be grouped. If the target subscription is already part of a group, the new subscription will become a member of the group as well. If the target subscription is not part of a group, a new group will be created and both the target and the new subscription will become part of the group with the target as the group's primary subscription. + +The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the target subscription. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the target subscription also. + +## Providing Agreement Acceptance Params + +It is possible to provide a proof of customer's acceptance of terms and policies. +We will be storing this proof in case it might be required (i.e. chargeback). +Currently, we already keep it for subscriptions created via Public Signup Pages. +In order to create a subscription with the proof of agreement acceptance, you must provide additional parameters `agreement acceptance` with `ip_address` and at least one url to the policy that was accepted: `terms_url` or `privacy_policy_url`. Additional urls that can be provided: `return_refund_policy_url`, `delivery_policy_url` and +`secure_checkout_policy_url`. + +```json + "subscription": { + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Jane", + "last_name": "Doe", + "email": "jd@chargify.test" }, - "next_billing_manifest": { - "line_items": [ - { - "transaction_type": "charge", - "kind": "baseline", - "amount_in_cents": 5000, - "memo": "Gold Product (09/21/2018 - 10/21/2018)", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "product_id": 1, - "product_handle": "gold-product", - "product_name": "Gold Product" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 28000, - "memo": "Component name: 14 Unit names", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 462149, - "component_handle": "handle", - "component_name": "Component name" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 0, - "memo": "On/Off Component", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 426670, - "component_handle": "handle", - "component_name": "On/Off Component" - } - ], - "total_in_cents": 33000, - "total_discount_in_cents": 0, - "total_tax_in_cents": 0, - "subtotal_in_cents": 33000, - "start_date": "2018-09-21T21:25:21Z", - "end_date": "2018-10-21T21:25:21Z", - "period_type": "recurring", - "existing_balance_in_cents": 0 + "agreement_acceptance": { + "ip_address": "1.2.3.4", + "terms_url": "https://terms.url", + "privacy_policy_url": "https://privacy_policy.url", + "return_refund_policy_url": "https://return_refund_policy.url", + "delivery_policy_url": "https://delivery_policy.url", + "secure_checkout_policy_url": "https://secure_checkout_policy.url" } } } ``` +**For Maxio Payments subscriptions, the agreement acceptance params are required, with at least terms_url provided.** -# Apply Coupon to Subscription - -An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons) - -## Query Parameters vs Request Body Parameters +## Providing ACH Agreement params -Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. +It is also possible to provide a proof that a customer authorized ACH agreement terms. +The proof will be stored and the email will be sent to the customer with a copy of the terms (if enabled). +In order to create a subscription with the proof of authorized ACH agreement terms, you must provide the additional parameter `ach_agreement` with the following nested parameters: `agreement_terms`, `authorizer_first_name`, `authorizer_last_name` and `ip_address`. +Each of them is required. -For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. +```json + "subscription": { + "product_handle": "gold-product", + "customer_attributes": { + "first_name": "Jane", + "last_name": "Doe", + "email": "jd@chargify.test" + }, + "bank_account_attributes": { + "bank_name": "Test Bank", + "bank_routing_number": "021000089", + "bank_account_number": "111111111111", + "bank_account_type": "checking", + "bank_account_holder_type": "business", + "payment_type": "bank_account" + }, + "ach_agreement": { + "agreement_terms": "ACH agreement terms", + "authorizer_first_name": "Jane", + "authorizer_last_name": "Doe", + "ip_address": "1.2.3.4" + } + } +``` ```csharp -ApplyCouponToSubscriptionAsync( - int subscriptionId, - string code = null, - Models.AddCouponsRequest body = null) +CreateSubscriptionAsync( + Models.CreateSubscriptionRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `code` | `string` | Query, Optional | A code for the coupon that would be applied to a subscription | -| `body` | [`AddCouponsRequest`](../../doc/models/add-coupons-request.md) | Body, Optional | - | +| `body` | [`CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | ## Response Type @@ -1760,23 +1676,47 @@ ApplyCouponToSubscriptionAsync( ## Example Usage ```csharp -int subscriptionId = 222; -AddCouponsRequest body = new AddCouponsRequest +CreateSubscriptionRequest body = new CreateSubscriptionRequest { - Codes = new List + Subscription = new CreateSubscription { - "COUPON_1", - "COUPON_2", + ProductHandle = "basic", + CustomerAttributes = new CustomerAttributes + { + FirstName = "Joe", + LastName = "Blow", + Email = "joe@example.com", + Organization = "Acme", + Reference = "XYZ", + Address = "123 Mass Ave.", + Address2 = "address_24", + City = "Boston", + State = "MA", + Zip = "02120", + Country = "US", + Phone = "(617) 111 - 0000", + }, + CreditCardAttributes = new PaymentProfileAttributes + { + FirstName = "Joe", + LastName = "Smith", + FullNumber = "4111111111111111", + CardType = CardType.Visa, + ExpirationMonth = PaymentProfileAttributesExpirationMonth.FromString("1"), + ExpirationYear = PaymentProfileAttributesExpirationYear.FromString("2021"), + BillingAddress = "123 Mass Ave.", + BillingAddress2 = "billing_address_22", + BillingCity = "Boston", + BillingState = "MA", + BillingCountry = "US", + BillingZip = "02120", + }, }, }; try { - SubscriptionResponse result = await subscriptionsController.ApplyCouponToSubscriptionAsync( - subscriptionId, - null, - body - ); + SubscriptionResponse result = await subscriptionsController.CreateSubscriptionAsync(body); } catch (ApiException e) { @@ -1790,147 +1730,136 @@ catch (ApiException e) ```json { "subscription": { - "id": 21607180, + "id": 15236915, "state": "active", + "balance_in_cents": 0, + "total_revenue_in_cents": 14000, + "product_price_in_cents": 1000, + "product_version_number": 7, + "current_period_ends_at": "2016-11-15T14:48:10-05:00", + "next_assessment_at": "2016-11-15T14:48:10-05:00", "trial_started_at": null, "trial_ended_at": null, - "activated_at": "2018-04-20T14:20:57-05:00", - "created_at": "2018-04-20T14:20:57-05:00", - "updated_at": "2018-05-11T13:53:44-05:00", + "activated_at": "2016-11-14T14:48:12-05:00", "expires_at": null, - "balance_in_cents": 49000, - "current_period_ends_at": "2018-05-12T11:33:03-05:00", - "next_assessment_at": "2018-05-12T11:33:03-05:00", - "canceled_at": null, + "created_at": "2016-11-14T14:48:10-05:00", + "updated_at": "2016-11-14T15:24:41-05:00", "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "remittance", - "snap_day": null, - "cancellation_method": null, - "current_period_started_at": "2018-05-11T11:33:03-05:00", + "cancellation_method": "merchant_api", + "cancel_at_end_of_period": null, + "canceled_at": null, + "current_period_started_at": "2016-11-14T14:48:10-05:00", "previous_state": "active", - "signup_payment_id": 237154761, - "signup_revenue": "0.00", + "signup_payment_id": 162269766, + "signup_revenue": "260.00", "delayed_cancel_at": null, - "coupon_code": "COUPONA", - "total_revenue_in_cents": 52762, - "product_price_in_cents": 100000, - "product_version_number": 2, - "payment_type": "credit_card", - "referral_code": "x45nc8", - "coupon_use_count": 0, - "coupon_uses_allowed": 1, + "coupon_code": "5SNN6HFK3GBH", + "payment_collection_method": "automatic", + "snap_day": null, "reason_code": null, - "automatically_resume_at": null, - "coupon_codes": [ - "COUPONA", - "COUPONB" - ], + "receives_invoice_emails": false, "customer": { - "id": 21259051, - "first_name": "K", - "last_name": "C", + "first_name": "Curtis", + "last_name": "Test", + "email": "curtis@example.com", + "cc_emails": "jeff@example.com", "organization": "", - "email": "example@chargify.com", - "created_at": "2018-04-20T14:20:57-05:00", - "updated_at": "2018-04-23T15:29:28-05:00", "reference": null, - "address": "", + "id": 14714298, + "created_at": "2016-11-14T14:48:10-05:00", + "updated_at": "2016-11-14T14:48:13-05:00", + "address": "123 Anywhere Street", "address_2": "", - "city": "", - "state": "", - "zip": "", - "country": "", + "city": "Boulder", + "state": "CO", + "zip": "80302", + "country": "US", "phone": "", - "portal_invite_last_sent_at": "2018-04-20T14:20:59-05:00", - "portal_invite_last_accepted_at": null, "verified": false, - "portal_customer_created_at": "2018-04-20T14:20:59-05:00", - "cc_emails": "", - "tax_exempt": false + "portal_customer_created_at": "2016-11-14T14:48:13-05:00", + "portal_invite_last_sent_at": "2016-11-14T14:48:13-05:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "vat_number": "012345678" }, "product": { - "id": 4581816, - "name": "Basic", + "id": 3792003, + "name": "$10 Basic Plan", "handle": "basic", - "description": "", - "accounting_code": "", - "request_credit_card": true, + "description": "lorem ipsum", + "accounting_code": "basic", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "day", + "initial_charge_in_cents": null, "expiration_interval": null, "expiration_interval_unit": "never", - "created_at": "2017-11-02T15:00:11-05:00", - "updated_at": "2018-04-10T09:02:59-05:00", - "price_in_cents": 100000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": 100000, - "trial_price_in_cents": 1000, - "trial_interval": 10, + "trial_price_in_cents": null, + "trial_interval": null, "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, + "initial_charge_after_trial": false, "return_params": "", - "taxable": false, + "request_credit_card": false, + "require_credit_card": false, + "created_at": "2016-03-24T13:38:39-04:00", + "updated_at": "2016-11-03T13:03:05-04:00", + "archived_at": null, "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 2, "update_return_params": "", "product_family": { - "id": 1025627, - "name": "My Product Family", - "description": "", - "handle": "acme-products", - "accounting_code": null + "id": 527890, + "name": "Acme Projects", + "handle": "billing-plans", + "accounting_code": null, + "description": "" }, "public_signup_pages": [ { - "id": 333589, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/hbwtd98j3hk2/basic" - }, - { - "id": 335926, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/g366zy67c7rm/basic" + "id": 281054, + "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" }, { - "id": 345555, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/txqyyqk7d8rz/basic" + "id": 281240, + "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" }, { - "id": 345556, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/2zss3qpf4249/basic" + "id": 282694, + "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" } - ] + ], + "taxable": false, + "version_number": 7, + "product_price_point_name": "Default" }, "credit_card": { - "id": 14839830, - "first_name": "John", - "last_name": "Doe", + "id": 10191713, + "payment_type": "credit_card", + "first_name": "Curtis", + "last_name": "Test", "masked_card_number": "XXXX-XXXX-XXXX-1", "card_type": "bogus", "expiration_month": 1, - "expiration_year": 2028, - "customer_id": 21259051, + "expiration_year": 2026, + "billing_address": "123 Anywhere Street", + "billing_address_2": "", + "billing_city": "Boulder", + "billing_state": null, + "billing_country": "", + "billing_zip": "80302", "current_vault": "bogus", "vault_token": "1", - "billing_address": null, - "billing_city": null, - "billing_state": null, - "billing_zip": "99999", - "billing_country": null, "customer_vault_token": null, - "billing_address_2": null, - "payment_type": "credit_card" - } + "customer_id": 14714298 + }, + "payment_type": "credit_card", + "referral_code": "w7kjc9", + "next_product_id": null, + "coupon_use_count": 1, + "coupon_uses_allowed": 1, + "next_product_handle": null, + "stored_credential_transaction_id": 125566112256688, + "dunning_communication_delay_enabled": true, + "dunning_communication_delay_time_zone": "Eastern Time (US & Canada)" } } ``` @@ -1939,39 +1868,71 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionAddCouponErrorException`](../../doc/models/subscription-add-coupon-error-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -# Delete Coupon From Subscription +# List Subscriptions -Use this endpoint to remove a coupon from an existing subscription. +This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. -For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon) +## Search for a subscription + +Use the query strings below to search for a subscription using the criteria available. The return value will be an array. + +## Self-Service Page token + +Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. ```csharp -DeleteCouponFromSubscriptionAsync( - int subscriptionId, - string couponCode = null) +ListSubscriptionsAsync( + Models.ListSubscriptionsInput input) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `couponCode` | `string` | Query, Optional | The coupon code | +| `page` | `int?` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `int?` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `state` | [`SubscriptionStateFilter?`](../../doc/models/subscription-state-filter.md) | Query, Optional | The current state of the subscription | +| `product` | `int?` | Query, Optional | The product id of the subscription. (Note that the product handle cannot be used.) | +| `productPricePointId` | `int?` | Query, Optional | The ID of the product price point. If supplied, product is required | +| `coupon` | `int?` | Query, Optional | The numeric id of the coupon currently applied to the subscription. (This can be found in the URL when editing a coupon. Note that the coupon code cannot be used.) | +| `dateField` | [`SubscriptionDateField?`](../../doc/models/subscription-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Allowed Values: , current_period_ends_at, current_period_starts_at, created_at, activated_at, canceled_at, expires_at, trial_started_at, trial_ended_at, updated_at | +| `startDate` | `DateTime?` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2022-07-01`. | +| `endDate` | `DateTime?` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2022-08-01`. | +| `startDatetime` | `DateTimeOffset?` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | +| `endDatetime` | `DateTimeOffset?` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-08-01 10:00:05`. | +| `metadata` | `Dictionary` | Query, Optional | The value of the metadata field specified in the parameter. Use in query `metadata[my-field]=value&metadata[other-field]=another_value`. | +| `direction` | [`SortingDirection?`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `sort` | [`SubscriptionSort?`](../../doc/models/subscription-sort.md) | Query, Optional | The attribute by which to sort | +| `include` | [`List`](../../doc/models/subscription-list-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=self_service_page_token`. | ## Response Type -`Task` +[`Task>`](../../doc/models/subscription-response.md) ## Example Usage ```csharp -int subscriptionId = 222; +ListSubscriptionsInput listSubscriptionsInput = new ListSubscriptionsInput +{ + Page = 2, + PerPage = 50, + StartDate = DateTime.Parse("2022-07-01"), + EndDate = DateTime.Parse("2022-08-01"), + StartDatetime = DateTime.ParseExact("2022-07-01 09:00:05", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + EndDatetime = DateTime.ParseExact("2022-08-01 10:00:05", "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK", + provider: CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind), + Sort = SubscriptionSort.SignupDate, +Liquid error: Value cannot be null. (Parameter 'key')}; + try { - string result = await subscriptionsController.DeleteCouponFromSubscriptionAsync(subscriptionId); + List result = await subscriptionsController.ListSubscriptionsAsync(listSubscriptionsInput); } catch (ApiException e) { @@ -1980,18 +1941,6 @@ catch (ApiException e) } ``` -## Example Response - -``` -"Coupon successfully removed" -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionRemoveCouponErrorsException`](../../doc/models/subscription-remove-coupon-errors-exception.md) | - # Activate Subscription @@ -2075,5 +2024,56 @@ catch (ApiException e) | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | -| 400 | Bad Request | [`NestedErrorResponseException`](../../doc/models/nested-error-response-exception.md) | +| 400 | Bad Request | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# Delete Coupon From Subscription + +Use this endpoint to remove a coupon from an existing subscription. + +For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon) + +```csharp +DeleteCouponFromSubscriptionAsync( + int subscriptionId, + string couponCode = null) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `couponCode` | `string` | Query, Optional | The coupon code | + +## Response Type + +`Task` + +## Example Usage + +```csharp +int subscriptionId = 222; +try +{ + string result = await subscriptionsController.DeleteCouponFromSubscriptionAsync(subscriptionId); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response + +``` +"Coupon successfully removed" +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionRemoveCouponErrorsException`](../../doc/models/subscription-remove-coupon-errors-exception.md) | diff --git a/doc/controllers/webhooks.md b/doc/controllers/webhooks.md index 44b6ec8..7b43c91 100644 --- a/doc/controllers/webhooks.md +++ b/doc/controllers/webhooks.md @@ -11,11 +11,11 @@ WebhooksController webhooksController = client.WebhooksController; ## Methods * [List Webhooks](../../doc/controllers/webhooks.md#list-webhooks) -* [Enable Webhooks](../../doc/controllers/webhooks.md#enable-webhooks) -* [Replay Webhooks](../../doc/controllers/webhooks.md#replay-webhooks) * [Create Endpoint](../../doc/controllers/webhooks.md#create-endpoint) -* [List Endpoints](../../doc/controllers/webhooks.md#list-endpoints) * [Update Endpoint](../../doc/controllers/webhooks.md#update-endpoint) +* [List Endpoints](../../doc/controllers/webhooks.md#list-endpoints) +* [Enable Webhooks](../../doc/controllers/webhooks.md#enable-webhooks) +* [Replay Webhooks](../../doc/controllers/webhooks.md#replay-webhooks) # List Webhooks @@ -116,36 +116,47 @@ catch (ApiException e) ``` -# Enable Webhooks +# Create Endpoint -This method allows you to enable webhooks via API for your site +The Chargify API allows you to create an endpoint and assign a list of webhooks subscriptions (events) to it. + +You can check available events here. +[Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#example-payloads) ```csharp -EnableWebhooksAsync( - Models.EnableWebhooksRequest body = null) +CreateEndpointAsync( + Models.UpdateEndpointRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `body` | [`EnableWebhooksRequest`](../../doc/models/enable-webhooks-request.md) | Body, Optional | - | +| `body` | [`UpdateEndpointRequest`](../../doc/models/update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | ## Response Type -[`Task`](../../doc/models/enable-webhooks-response.md) +[`Task`](../../doc/models/endpoint-response.md) ## Example Usage ```csharp -EnableWebhooksRequest body = new EnableWebhooksRequest +UpdateEndpointRequest body = new UpdateEndpointRequest { - WebhooksEnabled = true, + Endpoint = new UpdateEndpoint + { + Url = "https://your.site/webhooks", + WebhookSubscriptions = new List + { + WebhookSubscription.PaymentSuccess, + WebhookSubscription.PaymentFailure, + }, + }, }; try { - EnableWebhooksResponse result = await webhooksController.EnableWebhooksAsync(body); + EndpointResponse result = await webhooksController.CreateEndpointAsync(body); } catch (ApiException e) { @@ -158,73 +169,41 @@ catch (ApiException e) ```json { - "webhooks_enabled": true + "endpoint": { + "id": 1, + "url": "https://your.site/webhooks", + "site_id": 1, + "status": "enabled", + "webhook_subscriptions": [ + "payment_success", + "payment_failure" + ] + } } ``` +## Errors -# Replay Webhooks - -Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. - -You may submit an array of up to 1000 webhook IDs to replay in the request. - -```csharp -ReplayWebhooksAsync( - Models.ReplayWebhooksRequest body = null) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`ReplayWebhooksRequest`](../../doc/models/replay-webhooks-request.md) | Body, Optional | - | - -## Response Type - -[`Task`](../../doc/models/replay-webhooks-response.md) - -## Example Usage - -```csharp -ReplayWebhooksRequest body = new ReplayWebhooksRequest -{ - Ids = new List - { - 123456789, - 123456788, - }, -}; - -try -{ - ReplayWebhooksResponse result = await webhooksController.ReplayWebhooksAsync(body); -} -catch (ApiException e) -{ - // TODO: Handle exception here - Console.WriteLine(e.Message); -} -``` +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -## Example Response *(as JSON)* -```json -{ - "status": "ok" -} -``` +# Update Endpoint +You can update an Endpoint via the API with a PUT request to the resource endpoint. -# Create Endpoint +You can change the `url` of your endpoint which consumes webhooks or list of `webhook_subscriptions`. +Check available [Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404448450317-Webhooks#configure-webhook-url). -The Chargify API allows you to create an endpoint and assign a list of webhooks subscriptions (events) to it. +Always send a complete list of events which you want subscribe/watch. +Sending an PUT request for existing endpoint with empty list of `webhook_subscriptions` will end with unsubscribe from all events. -You can check available events here. -[Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#example-payloads) +If you want unsubscribe from specific event, just send a list of `webhook_subscriptions` without the specific event key. ```csharp -CreateEndpointAsync( +UpdateEndpointAsync( + int endpointId, Models.UpdateEndpointRequest body = null) ``` @@ -232,6 +211,7 @@ CreateEndpointAsync( | Parameter | Type | Tags | Description | | --- | --- | --- | --- | +| `endpointId` | `int` | Template, Required | The Chargify id for the endpoint that should be updated | | `body` | [`UpdateEndpointRequest`](../../doc/models/update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | ## Response Type @@ -241,22 +221,27 @@ CreateEndpointAsync( ## Example Usage ```csharp +int endpointId = 42; UpdateEndpointRequest body = new UpdateEndpointRequest { Endpoint = new UpdateEndpoint { - Url = "https://your.site/webhooks", + Url = "https://yout.site/webhooks/1/json.", WebhookSubscriptions = new List { - WebhookSubscription.PaymentSuccess, WebhookSubscription.PaymentFailure, + WebhookSubscription.PaymentSuccess, + WebhookSubscription.RefundFailure, }, }, }; try { - EndpointResponse result = await webhooksController.CreateEndpointAsync(body); + EndpointResponse result = await webhooksController.UpdateEndpointAsync( + endpointId, + body + ); } catch (ApiException e) { @@ -265,27 +250,11 @@ catch (ApiException e) } ``` -## Example Response *(as JSON)* - -```json -{ - "endpoint": { - "id": 1, - "url": "https://your.site/webhooks", - "site_id": 1, - "status": "enabled", - "webhook_subscriptions": [ - "payment_success", - "payment_failure" - ] - } -} -``` - ## Errors | HTTP Status Code | Error Description | Exception Class | | --- | --- | --- | +| 404 | Not Found | `ApiException` | | 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | @@ -344,59 +313,89 @@ catch (ApiException e) ``` -# Update Endpoint +# Enable Webhooks -You can update an Endpoint via the API with a PUT request to the resource endpoint. +This method allows you to enable webhooks via API for your site -You can change the `url` of your endpoint which consumes webhooks or list of `webhook_subscriptions`. -Check available [Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404448450317-Webhooks#configure-webhook-url). +```csharp +EnableWebhooksAsync( + Models.EnableWebhooksRequest body = null) +``` -Always send a complete list of events which you want subscribe/watch. -Sending an PUT request for existing endpoint with empty list of `webhook_subscriptions` will end with unsubscribe from all events. +## Parameters -If you want unsubscribe from specific event, just send a list of `webhook_subscriptions` without the specific event key. +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`EnableWebhooksRequest`](../../doc/models/enable-webhooks-request.md) | Body, Optional | - | + +## Response Type + +[`Task`](../../doc/models/enable-webhooks-response.md) + +## Example Usage ```csharp -UpdateEndpointAsync( - int endpointId, - Models.UpdateEndpointRequest body = null) +EnableWebhooksRequest body = new EnableWebhooksRequest +{ + WebhooksEnabled = true, +}; + +try +{ + EnableWebhooksResponse result = await webhooksController.EnableWebhooksAsync(body); +} +catch (ApiException e) +{ + // TODO: Handle exception here + Console.WriteLine(e.Message); +} +``` + +## Example Response *(as JSON)* + +```json +{ + "webhooks_enabled": true +} +``` + + +# Replay Webhooks + +Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. + +You may submit an array of up to 1000 webhook IDs to replay in the request. + +```csharp +ReplayWebhooksAsync( + Models.ReplayWebhooksRequest body = null) ``` ## Parameters | Parameter | Type | Tags | Description | | --- | --- | --- | --- | -| `endpointId` | `int` | Template, Required | The Chargify id for the endpoint that should be updated | -| `body` | [`UpdateEndpointRequest`](../../doc/models/update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | +| `body` | [`ReplayWebhooksRequest`](../../doc/models/replay-webhooks-request.md) | Body, Optional | - | ## Response Type -[`Task`](../../doc/models/endpoint-response.md) +[`Task`](../../doc/models/replay-webhooks-response.md) ## Example Usage ```csharp -int endpointId = 42; -UpdateEndpointRequest body = new UpdateEndpointRequest +ReplayWebhooksRequest body = new ReplayWebhooksRequest { - Endpoint = new UpdateEndpoint + Ids = new List { - Url = "https://yout.site/webhooks/1/json.", - WebhookSubscriptions = new List - { - WebhookSubscription.PaymentFailure, - WebhookSubscription.PaymentSuccess, - WebhookSubscription.RefundFailure, - }, + 123456789, + 123456788, }, }; try { - EndpointResponse result = await webhooksController.UpdateEndpointAsync( - endpointId, - body - ); + ReplayWebhooksResponse result = await webhooksController.ReplayWebhooksAsync(body); } catch (ApiException e) { @@ -405,10 +404,11 @@ catch (ApiException e) } ``` -## Errors +## Example Response *(as JSON)* -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiException` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +```json +{ + "status": "ok" +} +``` diff --git a/doc/models/applied-credit-note.md b/doc/models/applied-credit-note-data.md similarity index 85% rename from doc/models/applied-credit-note.md rename to doc/models/applied-credit-note-data.md index 28208a6..f76e289 100644 --- a/doc/models/applied-credit-note.md +++ b/doc/models/applied-credit-note-data.md @@ -1,9 +1,9 @@ -# Applied Credit Note +# Applied Credit Note Data ## Structure -`AppliedCreditNote` +`AppliedCreditNoteData` ## Fields diff --git a/doc/models/apply-credit-note-event-data.md b/doc/models/apply-credit-note-event-data.md index 24f2053..3c65cd0 100644 --- a/doc/models/apply-credit-note-event-data.md +++ b/doc/models/apply-credit-note-event-data.md @@ -20,7 +20,7 @@ Example schema for an `apply_credit_note` event | `Memo` | `string` | Optional | The credit note memo. | | `Role` | `string` | Optional | The role of the credit note (e.g. 'general') | | `ConsolidatedInvoice` | `bool?` | Optional | Shows whether it was applied to consolidated invoice or not | -| `AppliedCreditNotes` | [`List`](../../doc/models/applied-credit-note.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | +| `AppliedCreditNotes` | [`List`](../../doc/models/applied-credit-note-data.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | ## Example (as JSON) diff --git a/doc/models/bank-account-attributes.md b/doc/models/bank-account-attributes.md index 2b34698..c7d925b 100644 --- a/doc/models/bank-account-attributes.md +++ b/doc/models/bank-account-attributes.md @@ -13,11 +13,11 @@ | `BankName` | `string` | Optional | (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides | | `BankRoutingNumber` | `string` | Optional | (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | | `BankAccountNumber` | `string` | Optional | (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number | -| `BankAccountType` | `string` | Optional | - | +| `BankAccountType` | [`BankAccountType?`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking
**Default**: `BankAccountType.checking` | | `BankBranchCode` | `string` | Optional | (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided | | `BankIban` | `string` | Optional | (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided | -| `BankAccountHolderType` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | +| `BankAccountHolderType` | [`BankAccountHolderType?`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `PaymentType` | [`PaymentType?`](../../doc/models/payment-type.md) | Optional | **Default**: `PaymentType.credit_card` | | `CurrentVault` | [`BankAccountVault?`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | | `VaultToken` | `string` | Optional | - | | `CustomerVaultToken` | `string` | Optional | (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | @@ -26,11 +26,12 @@ ```json { + "bank_account_type": "checking", + "payment_type": "credit_card", "chargify_token": "chargify_token0", "bank_name": "bank_name2", "bank_routing_number": "bank_routing_number8", - "bank_account_number": "bank_account_number4", - "bank_account_type": "bank_account_type0" + "bank_account_number": "bank_account_number4" } ``` diff --git a/doc/models/holder-type.md b/doc/models/bank-account-holder-type.md similarity index 51% rename from doc/models/holder-type.md rename to doc/models/bank-account-holder-type.md index 81e07f6..b820e92 100644 --- a/doc/models/holder-type.md +++ b/doc/models/bank-account-holder-type.md @@ -1,9 +1,11 @@ -# Holder Type +# Bank Account Holder Type + +Defaults to personal ## Enumeration -`HolderType` +`BankAccountHolderType` ## Fields diff --git a/doc/models/bank-account-payment-profile.md b/doc/models/bank-account-payment-profile.md index 381fd5b..9d8b912 100644 --- a/doc/models/bank-account-payment-profile.md +++ b/doc/models/bank-account-payment-profile.md @@ -9,25 +9,25 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `FirstName` | `string` | Optional | - | -| `LastName` | `string` | Optional | - | -| `CustomerId` | `int?` | Optional | - | +| `Id` | `int?` | Optional | The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer | +| `FirstName` | `string` | Optional | The first name of the bank account holder | +| `LastName` | `string` | Optional | The last name of the bank account holder | +| `CustomerId` | `int?` | Optional | The Chargify-assigned id for the customer record to which the bank account belongs | | `CurrentVault` | [`BankAccountVault?`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | -| `VaultToken` | `string` | Optional | - | -| `BillingAddress` | `string` | Optional | - | -| `BillingCity` | `string` | Optional | - | -| `BillingState` | `string` | Optional | - | -| `BillingZip` | `string` | Optional | - | -| `BillingCountry` | `string` | Optional | - | -| `CustomerVaultToken` | `string` | Optional | - | -| `BillingAddress2` | `string` | Optional | - | -| `BankName` | `string` | Optional | - | -| `MaskedBankRoutingNumber` | `string` | Required | - | -| `MaskedBankAccountNumber` | `string` | Required | - | -| `BankAccountType` | `string` | Optional | - | -| `BankAccountHolderType` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | +| `VaultToken` | `string` | Optional | The “token” provided by your vault storage for an already stored payment profile | +| `BillingAddress` | `string` | Optional | The current billing street address for the bank account | +| `BillingCity` | `string` | Optional | The current billing address city for the bank account | +| `BillingState` | `string` | Optional | The current billing address state for the bank account | +| `BillingZip` | `string` | Optional | The current billing address zip code for the bank account | +| `BillingCountry` | `string` | Optional | The current billing address country for the bank account | +| `CustomerVaultToken` | `string` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | +| `BillingAddress2` | `string` | Optional | The current billing street address, second line, for the bank account | +| `BankName` | `string` | Optional | The bank where the account resides | +| `MaskedBankRoutingNumber` | `string` | Required | A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account | +| `MaskedBankAccountNumber` | `string` | Required | A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) | +| `BankAccountType` | [`BankAccountType?`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking
**Default**: `BankAccountType.checking` | +| `BankAccountHolderType` | [`BankAccountHolderType?`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `PaymentType` | [`PaymentType?`](../../doc/models/payment-type.md) | Optional | **Default**: `PaymentType.credit_card` | | `Verified` | `bool?` | Optional | denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account
**Default**: `false` | | `SiteGatewaySettingId` | `int?` | Optional | - | | `GatewayHandle` | `string` | Optional | - | @@ -38,6 +38,8 @@ { "masked_bank_routing_number": "masked_bank_routing_number8", "masked_bank_account_number": "masked_bank_account_number8", + "bank_account_type": "checking", + "payment_type": "credit_card", "verified": false, "id": 188, "first_name": "first_name6", diff --git a/doc/models/bank-account-response.md b/doc/models/bank-account-response.md index 1372704..32a6577 100644 --- a/doc/models/bank-account-response.md +++ b/doc/models/bank-account-response.md @@ -9,13 +9,17 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `PaymentProfile` | [`BankAccount`](../../doc/models/bank-account.md) | Required | - | +| `PaymentProfile` | [`BankAccountPaymentProfile`](../../doc/models/bank-account-payment-profile.md) | Required | - | ## Example (as JSON) ```json { "payment_profile": { + "masked_bank_routing_number": "masked_bank_routing_number0", + "masked_bank_account_number": "masked_bank_account_number6", + "bank_account_type": "checking", + "payment_type": "credit_card", "verified": false, "id": 44, "first_name": "first_name4", diff --git a/doc/models/bank-account-type.md b/doc/models/bank-account-type.md index 6c19062..ccce016 100644 --- a/doc/models/bank-account-type.md +++ b/doc/models/bank-account-type.md @@ -1,6 +1,8 @@ # Bank Account Type +Defaults to checking + ## Enumeration `BankAccountType` diff --git a/doc/models/bank-account.md b/doc/models/bank-account.md deleted file mode 100644 index e1905df..0000000 --- a/doc/models/bank-account.md +++ /dev/null @@ -1,47 +0,0 @@ - -# Bank Account - -## Structure - -`BankAccount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `FirstName` | `string` | Optional | - | -| `LastName` | `string` | Optional | - | -| `CustomerId` | `int?` | Optional | - | -| `CurrentVault` | [`BankAccountVault?`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | -| `VaultToken` | `string` | Optional | - | -| `BillingAddress` | `string` | Optional | - | -| `BillingCity` | `string` | Optional | - | -| `BillingState` | `string` | Optional | - | -| `BillingZip` | `string` | Optional | - | -| `BillingCountry` | `string` | Optional | - | -| `CustomerVaultToken` | `string` | Optional | - | -| `BillingAddress2` | `string` | Optional | - | -| `BankName` | `string` | Optional | - | -| `MaskedBankRoutingNumber` | `string` | Optional | - | -| `MaskedBankAccountNumber` | `string` | Optional | - | -| `BankAccountType` | `string` | Optional | - | -| `BankAccountHolderType` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | -| `Verified` | `bool?` | Optional | denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account
**Default**: `false` | -| `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | - | - -## Example (as JSON) - -```json -{ - "verified": false, - "id": 190, - "first_name": "first_name2", - "last_name": "last_name0", - "customer_id": 228, - "current_vault": "stripe_connect" -} -``` - diff --git a/doc/models/card-type-1.md b/doc/models/card-type-1.md deleted file mode 100644 index 45bbdb7..0000000 --- a/doc/models/card-type-1.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Card Type 1 - -## Enumeration - -`CardType1` - -## Fields - -| Name | -| --- | -| `Visa` | -| `Master` | -| `Elo` | -| `Cabal` | -| `Alelo` | -| `Discover` | -| `AmericanExpress` | -| `Naranja` | -| `DinersClub` | -| `Jcb` | -| `Dankort` | -| `Maestro` | -| `MaestroNoLuhn` | -| `Forbrugsforeningen` | -| `Sodexo` | -| `Alia` | -| `Vr` | -| `Unionpay` | -| `Carnet` | -| `CartesBancaires` | -| `Olimpica` | -| `Creditel` | -| `Confiable` | -| `Synchrony` | -| `Routex` | -| `Mada` | -| `BpPlus` | -| `Passcard` | -| `Edenred` | -| `Anda` | -| `Tarjetad` | -| `Hipercard` | -| `Bogus` | - diff --git a/doc/models/card-type.md b/doc/models/card-type.md index 523c48a..2acd766 100644 --- a/doc/models/card-type.md +++ b/doc/models/card-type.md @@ -11,17 +11,40 @@ The type of card used. | Name | | --- | -| `Bogus` | | `Visa` | | `Master` | +| `Elo` | +| `Cabal` | +| `Alelo` | | `Discover` | | `AmericanExpress` | +| `Naranja` | | `DinersClub` | | `Jcb` | -| `Switch` | -| `Solo` | | `Dankort` | | `Maestro` | -| `Laser` | +| `MaestroNoLuhn` | | `Forbrugsforeningen` | +| `Sodexo` | +| `Alia` | +| `Vr` | +| `Unionpay` | +| `Carnet` | +| `CartesBancaires` | +| `Olimpica` | +| `Creditel` | +| `Confiable` | +| `Synchrony` | +| `Routex` | +| `Mada` | +| `BpPlus` | +| `Passcard` | +| `Edenred` | +| `Anda` | +| `Tarjetad` | +| `Hipercard` | +| `Bogus` | +| `Switch` | +| `Solo` | +| `Laser` | diff --git a/doc/models/component-currency-price.md b/doc/models/component-currency-price.md new file mode 100644 index 0000000..ce63f92 --- /dev/null +++ b/doc/models/component-currency-price.md @@ -0,0 +1,30 @@ + +# Component Currency Price + +## Structure + +`ComponentCurrencyPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `int?` | Optional | - | +| `Currency` | `string` | Optional | - | +| `Price` | `string` | Optional | - | +| `FormattedPrice` | `string` | Optional | - | +| `PriceId` | `int?` | Optional | - | +| `PricePointId` | `int?` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 4, + "currency": "currency8", + "price": "price4", + "formatted_price": "formatted_price6", + "price_id": 162 +} +``` + diff --git a/doc/models/component-currency-prices-response.md b/doc/models/component-currency-prices-response.md new file mode 100644 index 0000000..5b74cb7 --- /dev/null +++ b/doc/models/component-currency-prices-response.md @@ -0,0 +1,29 @@ + +# Component Currency Prices Response + +## Structure + +`ComponentCurrencyPricesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`List`](../../doc/models/component-currency-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "id": 50, + "currency": "currency8", + "price": "price4", + "formatted_price": "formatted_price6", + "price_id": 116 + } + ] +} +``` + diff --git a/doc/models/component-kind-path.md b/doc/models/component-kind-path.md deleted file mode 100644 index 5925b26..0000000 --- a/doc/models/component-kind-path.md +++ /dev/null @@ -1,17 +0,0 @@ - -# Component Kind Path - -## Enumeration - -`ComponentKindPath` - -## Fields - -| Name | -| --- | -| `MeteredComponents` | -| `QuantityBasedComponents` | -| `OnOffComponents` | -| `PrepaidUsageComponents` | -| `EventBasedComponents` | - diff --git a/doc/models/component-price-point-price.md b/doc/models/component-price-point-price.md deleted file mode 100644 index b6c421d..0000000 --- a/doc/models/component-price-point-price.md +++ /dev/null @@ -1,32 +0,0 @@ - -# Component Price Point Price - -## Structure - -`ComponentPricePointPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `ComponentId` | `int?` | Optional | - | -| `StartingQuantity` | `int?` | Optional | - | -| `EndingQuantity` | `int?` | Optional | - | -| `UnitPrice` | `string` | Optional | - | -| `PricePointId` | `int?` | Optional | - | -| `FormattedUnitPrice` | `string` | Optional | - | -| `SegmentId` | `int?` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 20, - "component_id": 130, - "starting_quantity": 194, - "ending_quantity": 220, - "unit_price": "unit_price0" -} -``` - diff --git a/doc/models/component-price-point.md b/doc/models/component-price-point.md index 9dd303d..90cfe7b 100644 --- a/doc/models/component-price-point.md +++ b/doc/models/component-price-point.md @@ -16,15 +16,16 @@ | `PricingScheme` | [`PricingScheme?`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | | `ComponentId` | `int?` | Optional | - | | `Handle` | `string` | Optional | - | -| `ArchivedAt` | `string` | Optional | - | -| `CreatedAt` | `string` | Optional | - | -| `UpdatedAt` | `string` | Optional | - | -| `Prices` | [`List`](../../doc/models/component-price-point-price.md) | Optional | - | +| `ArchivedAt` | `DateTimeOffset?` | Optional | - | +| `CreatedAt` | `DateTimeOffset?` | Optional | - | +| `UpdatedAt` | `DateTimeOffset?` | Optional | - | +| `Prices` | [`List`](../../doc/models/component-price.md) | Optional | - | | `UseSiteExchangeRate` | `bool?` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | | `SubscriptionId` | `int?` | Optional | (only used for Custom Pricing - ie. when the price point's type is `custom`) The id of the subscription that the custom price point is for. | | `TaxIncluded` | `bool?` | Optional | - | | `Interval` | `int?` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`IntervalUnit?`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`ComponentPricePointIntervalUnit`](../../doc/models/containers/component-price-point-interval-unit.md) | Optional | This is a container for one-of cases. | +| `CurrencyPrices` | [`List`](../../doc/models/component-currency-price.md) | Optional | An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. | ## Example (as JSON) diff --git a/doc/models/component-price-points-response.md b/doc/models/component-price-points-response.md index 4849be8..ffeb210 100644 --- a/doc/models/component-price-points-response.md +++ b/doc/models/component-price-points-response.md @@ -10,6 +10,7 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | | `PricePoints` | [`List`](../../doc/models/component-price-point.md) | Optional | - | +| `Meta` | [`ListPublicKeysMeta`](../../doc/models/list-public-keys-meta.md) | Optional | - | ## Example (as JSON) @@ -30,7 +31,13 @@ "name": "name2", "pricing_scheme": "per_unit" } - ] + ], + "meta": { + "total_count": 150, + "current_page": 126, + "total_pages": 138, + "per_page": 152 + } } ``` diff --git a/doc/models/component.md b/doc/models/component.md index 5b29ad3..bf43fa7 100644 --- a/doc/models/component.md +++ b/doc/models/component.md @@ -23,6 +23,7 @@ | `Taxable` | `bool?` | Optional | Boolean flag describing whether a component is taxable or not. | | `Description` | `string` | Optional | The description of the component. | | `DefaultPricePointId` | `int?` | Optional | - | +| `OveragePrices` | [`List`](../../doc/models/component-price.md) | Optional | An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. | | `Prices` | [`List`](../../doc/models/component-price.md) | Optional | An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. | | `PricePointCount` | `int?` | Optional | Count for the number of price points associated with the component | | `PricePointsUrl` | `string` | Optional | URL that points to the location to read the existing price points via GET request | @@ -31,8 +32,8 @@ | `Recurring` | `bool?` | Optional | - | | `UpgradeCharge` | [`CreditType?`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | | `DowngradeCredit` | [`CreditType?`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `CreatedAt` | `string` | Optional | Timestamp indicating when this component was created | -| `UpdatedAt` | `string` | Optional | Timestamp indicating when this component was updated | +| `CreatedAt` | `DateTimeOffset?` | Optional | Timestamp indicating when this component was created | +| `UpdatedAt` | `DateTimeOffset?` | Optional | Timestamp indicating when this component was updated | | `ArchivedAt` | `string` | Optional | Timestamp indicating when this component was archived | | `HideDateRangeOnInvoice` | `bool?` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | | `AllowFractionalQuantities` | `bool?` | Optional | - | diff --git a/doc/models/containers/component-price-point-interval-unit.md b/doc/models/containers/component-price-point-interval-unit.md new file mode 100644 index 0000000..5eaa97b --- /dev/null +++ b/doc/models/containers/component-price-point-interval-unit.md @@ -0,0 +1,13 @@ + +# Component Price Point Interval Unit + +## Class Name + +`ComponentPricePointIntervalUnit` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`IntervalUnit`](../../../doc/models/interval-unit.md) | ComponentPricePointIntervalUnit.FromIntervalUnit(IntervalUnit intervalUnit) | + diff --git a/doc/models/containers/create-component-body.md b/doc/models/containers/create-component-body.md deleted file mode 100644 index cd1705a..0000000 --- a/doc/models/containers/create-component-body.md +++ /dev/null @@ -1,17 +0,0 @@ - -# Create Component Body - -## Class Name - -`CreateComponentBody` - -## Cases - -| Type | Factory Method | -| --- | --- | -| [`CreateMeteredComponent`](../../../doc/models/create-metered-component.md) | CreateComponentBody.FromCreateMeteredComponent(CreateMeteredComponent createMeteredComponent) | -| [`CreateQuantityBasedComponent`](../../../doc/models/create-quantity-based-component.md) | CreateComponentBody.FromCreateQuantityBasedComponent(CreateQuantityBasedComponent createQuantityBasedComponent) | -| [`CreateOnOffComponent`](../../../doc/models/create-on-off-component.md) | CreateComponentBody.FromCreateOnOffComponent(CreateOnOffComponent createOnOffComponent) | -| [`CreatePrepaidComponent`](../../../doc/models/create-prepaid-component.md) | CreateComponentBody.FromCreatePrepaidComponent(CreatePrepaidComponent createPrepaidComponent) | -| [`CreateEBBComponent`](../../../doc/models/create-ebb-component.md) | CreateComponentBody.FromCreateEBBComponent(CreateEBBComponent createEBBComponent) | - diff --git a/doc/models/containers/create-or-update-percentage-coupon-percentage.md b/doc/models/containers/create-or-update-percentage-coupon-percentage.md index b700f59..92526f3 100644 --- a/doc/models/containers/create-or-update-percentage-coupon-percentage.md +++ b/doc/models/containers/create-or-update-percentage-coupon-percentage.md @@ -9,6 +9,6 @@ | Type | Factory Method | | --- | --- | -| `double` | CreateOrUpdatePercentageCouponPercentage.FromPrecision(double precision) | | `string` | CreateOrUpdatePercentageCouponPercentage.FromString(string mString) | +| `double` | CreateOrUpdatePercentageCouponPercentage.FromPrecision(double precision) | diff --git a/doc/models/containers/invoice-event-event-data.md b/doc/models/containers/invoice-event-event-data.md index 2b312b3..cf38c55 100644 --- a/doc/models/containers/invoice-event-event-data.md +++ b/doc/models/containers/invoice-event-event-data.md @@ -17,5 +17,5 @@ | [`RefundInvoiceEventData`](../../../doc/models/refund-invoice-event-data.md) | InvoiceEventEventData.FromRefundInvoiceEventData(RefundInvoiceEventData refundInvoiceEventData) | | [`RemovePaymentEventData`](../../../doc/models/remove-payment-event-data.md) | InvoiceEventEventData.FromRemovePaymentEventData(RemovePaymentEventData removePaymentEventData) | | [`VoidInvoiceEventData`](../../../doc/models/void-invoice-event-data.md) | InvoiceEventEventData.FromVoidInvoiceEventData(VoidInvoiceEventData voidInvoiceEventData) | -| [`VoidInvoiceEventData1`](../../../doc/models/void-invoice-event-data-1.md) | InvoiceEventEventData.FromVoidInvoiceEventData1(VoidInvoiceEventData1 voidInvoiceEventData1) | +| [`VoidRemainderEventData`](../../../doc/models/void-remainder-event-data.md) | InvoiceEventEventData.FromVoidRemainderEventData(VoidRemainderEventData voidRemainderEventData) | diff --git a/doc/models/containers/payment-profile-response-payment-profile.md b/doc/models/containers/payment-profile-response-payment-profile.md new file mode 100644 index 0000000..2e81dfd --- /dev/null +++ b/doc/models/containers/payment-profile-response-payment-profile.md @@ -0,0 +1,14 @@ + +# Payment Profile Response Payment Profile + +## Class Name + +`PaymentProfileResponsePaymentProfile` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`BankAccountPaymentProfile`](../../../doc/models/bank-account-payment-profile.md) | PaymentProfileResponsePaymentProfile.FromBankAccountPaymentProfile(BankAccountPaymentProfile bankAccountPaymentProfile) | +| [`CreditCardPaymentProfile`](../../../doc/models/credit-card-payment-profile.md) | PaymentProfileResponsePaymentProfile.FromCreditCardPaymentProfile(CreditCardPaymentProfile creditCardPaymentProfile) | + diff --git a/doc/models/containers/read-payment-profile-response-payment-profile.md b/doc/models/containers/read-payment-profile-response-payment-profile.md deleted file mode 100644 index 8d82029..0000000 --- a/doc/models/containers/read-payment-profile-response-payment-profile.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Read Payment Profile Response Payment Profile - -## Class Name - -`ReadPaymentProfileResponsePaymentProfile` - -## Cases - -| Type | Factory Method | -| --- | --- | -| [`BankAccountPaymentProfile`](../../../doc/models/bank-account-payment-profile.md) | ReadPaymentProfileResponsePaymentProfile.FromBankAccountPaymentProfile(BankAccountPaymentProfile bankAccountPaymentProfile) | -| [`CreditCardPaymentProfile`](../../../doc/models/credit-card-payment-profile.md) | ReadPaymentProfileResponsePaymentProfile.FromCreditCardPaymentProfile(CreditCardPaymentProfile creditCardPaymentProfile) | - diff --git a/doc/models/containers/update-price-ending-quantity.md b/doc/models/containers/update-price-ending-quantity.md new file mode 100644 index 0000000..32e586e --- /dev/null +++ b/doc/models/containers/update-price-ending-quantity.md @@ -0,0 +1,14 @@ + +# Update Price Ending Quantity + +## Class Name + +`UpdatePriceEndingQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | UpdatePriceEndingQuantity.FromNumber(int number) | +| `string` | UpdatePriceEndingQuantity.FromString(string mString) | + diff --git a/doc/models/containers/update-price-starting-quantity.md b/doc/models/containers/update-price-starting-quantity.md new file mode 100644 index 0000000..dc8a98e --- /dev/null +++ b/doc/models/containers/update-price-starting-quantity.md @@ -0,0 +1,14 @@ + +# Update Price Starting Quantity + +## Class Name + +`UpdatePriceStartingQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | UpdatePriceStartingQuantity.FromNumber(int number) | +| `string` | UpdatePriceStartingQuantity.FromString(string mString) | + diff --git a/doc/models/containers/update-price-unit-price.md b/doc/models/containers/update-price-unit-price.md new file mode 100644 index 0000000..a3b3395 --- /dev/null +++ b/doc/models/containers/update-price-unit-price.md @@ -0,0 +1,14 @@ + +# Update Price Unit Price + +## Class Name + +`UpdatePriceUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `double` | UpdatePriceUnitPrice.FromPrecision(double precision) | +| `string` | UpdatePriceUnitPrice.FromString(string mString) | + diff --git a/doc/models/coupon.md b/doc/models/coupon.md index 2590c3e..ce058aa 100644 --- a/doc/models/coupon.md +++ b/doc/models/coupon.md @@ -19,7 +19,7 @@ | `ProductFamilyName` | `string` | Optional | - | | `StartDate` | `string` | Optional | - | | `EndDate` | `string` | Optional | - | -| `Percentage` | `double?` | Optional | - | +| `Percentage` | `string` | Optional | - | | `Recurring` | `bool?` | Optional | - | | `RecurringScheme` | [`RecurringScheme?`](../../doc/models/recurring-scheme.md) | Optional | - | | `DurationPeriodCount` | `int?` | Optional | - | diff --git a/doc/models/create-component-price-point-request.md b/doc/models/create-component-price-point-request.md index fd605d7..1b5a026 100644 --- a/doc/models/create-component-price-point-request.md +++ b/doc/models/create-component-price-point-request.md @@ -27,6 +27,7 @@ ], "use_site_exchange_rate": true, "handle": "handle6", + "tax_included": false, "interval": 24, "interval_unit": "day" } diff --git a/doc/models/create-component-price-point.md b/doc/models/create-component-price-point.md index 561583e..29d325a 100644 --- a/doc/models/create-component-price-point.md +++ b/doc/models/create-component-price-point.md @@ -14,6 +14,7 @@ | `PricingScheme` | [`PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | | `Prices` | [`List`](../../doc/models/price.md) | Required | - | | `UseSiteExchangeRate` | `bool?` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | +| `TaxIncluded` | `bool?` | Optional | Whether or not the price point includes tax | | `Interval` | `int?` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | | `IntervalUnit` | [`IntervalUnit?`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. | @@ -32,6 +33,7 @@ ], "use_site_exchange_rate": true, "handle": "handle6", + "tax_included": false, "interval": 24, "interval_unit": "day" } diff --git a/doc/models/create-component-price-points-request.md b/doc/models/create-component-price-points-request.md index 07c4347..cbb222b 100644 --- a/doc/models/create-component-price-points-request.md +++ b/doc/models/create-component-price-points-request.md @@ -38,6 +38,7 @@ } ], "use_site_exchange_rate": false, + "tax_included": false, "interval": 24, "interval_unit": "day" }, @@ -63,6 +64,7 @@ } ], "use_site_exchange_rate": false, + "tax_included": false, "interval": 24, "interval_unit": "day" } diff --git a/doc/models/create-currency-price.md b/doc/models/create-currency-price.md index 2e4f6fe..a5e703f 100644 --- a/doc/models/create-currency-price.md +++ b/doc/models/create-currency-price.md @@ -10,7 +10,7 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | | `Currency` | `string` | Optional | ISO code for a currency defined on the site level | -| `Price` | `int?` | Optional | Price for the price level in this currency | +| `Price` | `double?` | Optional | Price for the price level in this currency | | `PriceId` | `int?` | Optional | ID of the price that this corresponds with | ## Example (as JSON) @@ -18,7 +18,7 @@ ```json { "currency": "currency2", - "price": 16, + "price": 10.4, "price_id": 54 } ``` diff --git a/doc/models/create-currency-prices-request.md b/doc/models/create-currency-prices-request.md index b11d777..6cce601 100644 --- a/doc/models/create-currency-prices-request.md +++ b/doc/models/create-currency-prices-request.md @@ -18,7 +18,7 @@ "currency_prices": [ { "currency": "currency8", - "price": 78, + "price": 233.74, "price_id": 116 } ] diff --git a/doc/models/create-or-update-coupon.md b/doc/models/create-or-update-coupon.md index 8bf1134..409aef2 100644 --- a/doc/models/create-or-update-coupon.md +++ b/doc/models/create-or-update-coupon.md @@ -21,7 +21,7 @@ "name": "name0", "code": "code8", "description": "description0", - "percentage": 11.02, + "percentage": "String9", "allow_negative_balance": false, "recurring": false, "end_date": "2016-03-13T12:52:32.123Z", diff --git a/doc/models/create-or-update-percentage-coupon.md b/doc/models/create-or-update-percentage-coupon.md index a9736f7..3aa2649 100644 --- a/doc/models/create-or-update-percentage-coupon.md +++ b/doc/models/create-or-update-percentage-coupon.md @@ -29,7 +29,7 @@ "name": "name0", "code": "code8", "description": "description0", - "percentage": 11.02, + "percentage": "String9", "allow_negative_balance": false, "recurring": false, "end_date": "2016-03-13T12:52:32.123Z", diff --git a/doc/models/create-payment-profile-request.md b/doc/models/create-payment-profile-request.md index b0d9617..dcd8eb2 100644 --- a/doc/models/create-payment-profile-request.md +++ b/doc/models/create-payment-profile-request.md @@ -19,6 +19,7 @@ "chargify_token": "tok_9g6hw85pnpt6knmskpwp4ttt", "payment_type": "credit_card", "full_number": "5424000000000015", + "bank_account_type": "checking", "id": 44, "first_name": "first_name4", "last_name": "last_name2" diff --git a/doc/models/create-payment-profile-response.md b/doc/models/create-payment-profile-response.md deleted file mode 100644 index d7a4312..0000000 --- a/doc/models/create-payment-profile-response.md +++ /dev/null @@ -1,27 +0,0 @@ - -# Create Payment Profile Response - -## Structure - -`CreatePaymentProfileResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`CreatedPaymentProfile`](../../doc/models/created-payment-profile.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "id": 44, - "first_name": "first_name4", - "last_name": "last_name2", - "masked_card_number": "masked_card_number2", - "card_type": "card_type0" - } -} -``` - diff --git a/doc/models/create-payment-profile.md b/doc/models/create-payment-profile.md index 07a8585..64820cf 100644 --- a/doc/models/create-payment-profile.md +++ b/doc/models/create-payment-profile.md @@ -38,8 +38,8 @@ | `BankRoutingNumber` | `string` | Optional | (Required when creating with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | | `BankAccountNumber` | `string` | Optional | (Required when creating with ACH, GoCardless, Stripe BECS Direct Debit and bank_iban is blank) The customerʼs bank account number | | `BankBranchCode` | `string` | Optional | (Optional when creating with GoCardless, required with Stripe BECS Direct Debit) Branch code. Alternatively, an IBAN can be provided | -| `BankAccountType` | `string` | Optional | - | -| `BankAccountHolderType` | `string` | Optional | - | +| `BankAccountType` | [`BankAccountType?`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking
**Default**: `BankAccountType.checking` | +| `BankAccountHolderType` | [`BankAccountHolderType?`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | | `LastFour` | `string` | Optional | (Optional) Used for creating subscription with payment profile imported using vault_token, for proper display in Advanced Billing UI | ## Example (as JSON) @@ -49,6 +49,7 @@ "chargify_token": "tok_9g6hw85pnpt6knmskpwp4ttt", "payment_type": "credit_card", "full_number": "5424000000000015", + "bank_account_type": "checking", "id": 76, "first_name": "first_name8", "last_name": "last_name6" diff --git a/doc/models/create-prepaid-component.md b/doc/models/create-prepaid-component.md index 4ccbad4..af60fdb 100644 --- a/doc/models/create-prepaid-component.md +++ b/doc/models/create-prepaid-component.md @@ -20,7 +20,8 @@ "unit_name": "unit_name4", "description": "description2", "handle": "handle8", - "taxable": false + "taxable": false, + "pricing_scheme": "per_unit" } } ``` diff --git a/doc/models/created-payment-profile.md b/doc/models/created-payment-profile.md deleted file mode 100644 index 6b73637..0000000 --- a/doc/models/created-payment-profile.md +++ /dev/null @@ -1,51 +0,0 @@ - -# Created Payment Profile - -## Structure - -`CreatedPaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `FirstName` | `string` | Optional | - | -| `LastName` | `string` | Optional | - | -| `MaskedCardNumber` | `string` | Optional | - | -| `CardType` | `string` | Optional | - | -| `ExpirationMonth` | `int?` | Optional | - | -| `ExpirationYear` | `int?` | Optional | - | -| `CustomerId` | `int?` | Optional | - | -| `CurrentVault` | [`CurrentVault?`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `string` | Optional | - | -| `BillingAddress` | `string` | Optional | - | -| `BillingCity` | `string` | Optional | - | -| `BillingState` | `string` | Optional | - | -| `BillingZip` | `string` | Optional | - | -| `BillingCountry` | `string` | Optional | - | -| `CustomerVaultToken` | `string` | Optional | - | -| `BillingAddress2` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | -| `BankName` | `string` | Optional | - | -| `MaskedBankRoutingNumber` | `string` | Optional | - | -| `MaskedBankAccountNumber` | `string` | Optional | - | -| `BankAccountType` | `string` | Optional | - | -| `BankAccountHolderType` | `string` | Optional | - | -| `Verified` | `bool?` | Optional | - | -| `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | - | -| `Disabled` | `bool?` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 14, - "first_name": "first_name0", - "last_name": "last_name8", - "masked_card_number": "masked_card_number8", - "card_type": "card_type4" -} -``` - diff --git a/doc/models/credit-card-payment-profile.md b/doc/models/credit-card-payment-profile.md index 3aa6df7..5d018de 100644 --- a/doc/models/credit-card-payment-profile.md +++ b/doc/models/credit-card-payment-profile.md @@ -9,38 +9,53 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `FirstName` | `string` | Optional | - | -| `LastName` | `string` | Optional | - | -| `MaskedCardNumber` | `string` | Required | - | -| `CardType` | [`CardType1?`](../../doc/models/card-type-1.md) | Optional | - | -| `ExpirationMonth` | `int?` | Optional | - | -| `ExpirationYear` | `int?` | Optional | - | -| `CustomerId` | `int?` | Optional | - | +| `Id` | `int?` | Optional | The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. | +| `FirstName` | `string` | Optional | The first name of the card holder. | +| `LastName` | `string` | Optional | The last name of the card holder. | +| `MaskedCardNumber` | `string` | Required | A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). | +| `CardType` | [`CardType?`](../../doc/models/card-type.md) | Optional | The type of card used. | +| `ExpirationMonth` | `int?` | Optional | An integer representing the expiration month of the card(1 – 12). | +| `ExpirationYear` | `int?` | Optional | An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). | +| `CustomerId` | `int?` | Optional | The Chargify-assigned id for the customer record to which the card belongs. | | `CurrentVault` | [`CurrentVault?`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `string` | Optional | - | -| `BillingAddress` | `string` | Optional | - | -| `BillingCity` | `string` | Optional | - | -| `BillingState` | `string` | Optional | - | -| `BillingZip` | `string` | Optional | - | -| `BillingCountry` | `string` | Optional | - | -| `CustomerVaultToken` | `string` | Optional | - | -| `BillingAddress2` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | +| `VaultToken` | `string` | Optional | The “token” provided by your vault storage for an already stored payment profile. | +| `BillingAddress` | `string` | Optional | The current billing street address for the card. | +| `BillingCity` | `string` | Optional | The current billing address city for the card. | +| `BillingState` | `string` | Optional | The current billing address state for the card. | +| `BillingZip` | `string` | Optional | The current billing address zip code for the card. | +| `BillingCountry` | `string` | Optional | The current billing address country for the card. | +| `CustomerVaultToken` | `string` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | +| `BillingAddress2` | `string` | Optional | The current billing street address, second line, for the card. | +| `PaymentType` | [`PaymentType?`](../../doc/models/payment-type.md) | Optional | **Default**: `PaymentType.credit_card` | | `Disabled` | `bool?` | Optional | - | +| `ChargifyToken` | `string` | Optional | Token received after sending billing information using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) | | `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | - | +| `GatewayHandle` | `string` | Optional | An identifier of connected gateway. | ## Example (as JSON) ```json { - "id": 252, - "first_name": "first_name0", - "last_name": "last_name8", - "masked_card_number": "masked_card_number8", - "card_type": "synchrony", - "expiration_month": 170 + "id": 10088716, + "first_name": "Test", + "last_name": "Subscription", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2022, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null } ``` diff --git a/doc/models/product-price-point-currency-price.md b/doc/models/currency-prices-response.md similarity index 85% rename from doc/models/product-price-point-currency-price.md rename to doc/models/currency-prices-response.md index 570a1bc..09a6e25 100644 --- a/doc/models/product-price-point-currency-price.md +++ b/doc/models/currency-prices-response.md @@ -1,9 +1,9 @@ -# Product Price Point Currency Price +# Currency Prices Response ## Structure -`ProductPricePointCurrencyPrice` +`CurrencyPricesResponse` ## Fields diff --git a/doc/models/error-map-response-exception.md b/doc/models/error-array-map-response-exception.md similarity index 78% rename from doc/models/error-map-response-exception.md rename to doc/models/error-array-map-response-exception.md index b9da298..e424128 100644 --- a/doc/models/error-map-response-exception.md +++ b/doc/models/error-array-map-response-exception.md @@ -1,9 +1,9 @@ -# Error Map Response Exception +# Error Array Map Response Exception ## Structure -`ErrorMapResponseException` +`ErrorArrayMapResponseException` ## Fields diff --git a/doc/models/error-string-map-response-exception.md b/doc/models/error-string-map-response-exception.md new file mode 100644 index 0000000..732a6d6 --- /dev/null +++ b/doc/models/error-string-map-response-exception.md @@ -0,0 +1,24 @@ + +# Error String Map Response Exception + +## Structure + +`ErrorStringMapResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | `Dictionary` | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "key0": "errors3", + "key1": "errors4" + } +} +``` + diff --git a/doc/models/get-one-time-token-payment-profile.md b/doc/models/get-one-time-token-payment-profile.md index 3567230..6a5564d 100644 --- a/doc/models/get-one-time-token-payment-profile.md +++ b/doc/models/get-one-time-token-payment-profile.md @@ -13,7 +13,7 @@ | `FirstName` | `string` | Required | **Constraints**: *Minimum Length*: `1` | | `LastName` | `string` | Required | **Constraints**: *Minimum Length*: `1` | | `MaskedCardNumber` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `CardType` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `CardType` | [`CardType`](../../doc/models/card-type.md) | Required | The type of card used. | | `ExpirationMonth` | `double` | Required | - | | `ExpirationYear` | `double` | Required | - | | `CustomerId` | `string` | Optional | - | @@ -39,7 +39,7 @@ "first_name": "first_name2", "last_name": "last_name0", "masked_card_number": "masked_card_number0", - "card_type": "card_type8", + "card_type": "routex", "expiration_month": 187.78, "expiration_year": 164.44, "customer_id": "customer_id0", diff --git a/doc/models/get-one-time-token-request.md b/doc/models/get-one-time-token-request.md index f5a0c00..418a8c9 100644 --- a/doc/models/get-one-time-token-request.md +++ b/doc/models/get-one-time-token-request.md @@ -20,7 +20,7 @@ "first_name": "first_name4", "last_name": "last_name2", "masked_card_number": "masked_card_number2", - "card_type": "card_type0", + "card_type": "bogus", "expiration_month": 133.5, "expiration_year": 156.84, "customer_id": "customer_id2", diff --git a/doc/models/invoice-credit.md b/doc/models/invoice-credit.md index ed85f7f..a8e4c7a 100644 --- a/doc/models/invoice-credit.md +++ b/doc/models/invoice-credit.md @@ -12,7 +12,7 @@ | `Uid` | `string` | Optional | - | | `CreditNoteNumber` | `string` | Optional | - | | `CreditNoteUid` | `string` | Optional | - | -| `TransactionTime` | `string` | Optional | - | +| `TransactionTime` | `DateTimeOffset?` | Optional | - | | `Memo` | `string` | Optional | - | | `OriginalAmount` | `string` | Optional | - | | `AppliedAmount` | `string` | Optional | - | @@ -24,7 +24,7 @@ "uid": "uid6", "credit_note_number": "credit_note_number0", "credit_note_uid": "credit_note_uid0", - "transaction_time": "transaction_time8", + "transaction_time": "2016-03-13T12:52:32.123Z", "memo": "memo0" } ``` diff --git a/doc/models/invoice-event-1.md b/doc/models/invoice-event-1.md index 064208d..e1b7d47 100644 --- a/doc/models/invoice-event-1.md +++ b/doc/models/invoice-event-1.md @@ -20,7 +20,7 @@ The event data is the data that, when combined with the command, results in the | `Memo` | `string` | Optional | The credit note memo. | | `Role` | `string` | Optional | The role of the credit note (e.g. 'general') | | `ConsolidatedInvoice` | `bool?` | Optional | Shows whether it was applied to consolidated invoice or not | -| `AppliedCreditNotes` | [`List`](../../doc/models/applied-credit-note.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | +| `AppliedCreditNotes` | [`List`](../../doc/models/applied-credit-note-data.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | | `DebitNoteNumber` | `string` | Optional | A unique, identifying string that appears on the debit note and in places it is referenced. | | `DebitNoteUid` | `string` | Optional | Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. | | `PaymentMethod` | [`InvoiceEvent1PaymentMethod`](../../doc/models/containers/invoice-event-1-payment-method.md) | Optional | This is a container for one-of cases. | diff --git a/doc/models/invoice-line-item.md b/doc/models/invoice-line-item.md index 5c1be30..ab801ef 100644 --- a/doc/models/invoice-line-item.md +++ b/doc/models/invoice-line-item.md @@ -19,8 +19,8 @@ | `TaxAmount` | `string` | Optional | The approximate tax applied to just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. | | `TotalAmount` | `string` | Optional | The non-canonical total amount for the line.

`subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. | | `TieredUnitPrice` | `bool?` | Optional | When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. | -| `PeriodRangeStart` | `string` | Optional | Start date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the billing date, and the end date will be in the future.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date.
* For non-periodic charges, this date and the end date will match. | -| `PeriodRangeEnd` | `string` | Optional | End date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the next (future) billing date.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date.
* For non-periodic charges, this date and the start date will match. | +| `PeriodRangeStart` | `DateTime?` | Optional | Start date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the billing date, and the end date will be in the future.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date.
* For non-periodic charges, this date and the end date will match. | +| `PeriodRangeEnd` | `DateTime?` | Optional | End date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the next (future) billing date.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date.
* For non-periodic charges, this date and the start date will match. | | `TransactionId` | `int?` | Optional | - | | `ProductId` | `int?` | Optional | The ID of the product subscribed when the charge was made.

This may be set even for component charges, so true product-only (non-component) charges will also have a nil `component_id`. | | `ProductVersion` | `int?` | Optional | The version of the product subscribed when the charge was made. | diff --git a/doc/models/invoice-payment.md b/doc/models/invoice-payment.md index b29cc1a..e009533 100644 --- a/doc/models/invoice-payment.md +++ b/doc/models/invoice-payment.md @@ -9,7 +9,7 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `TransactionTime` | `string` | Optional | - | +| `TransactionTime` | `DateTimeOffset?` | Optional | - | | `Memo` | `string` | Optional | - | | `OriginalAmount` | `string` | Optional | - | | `AppliedAmount` | `string` | Optional | - | @@ -24,7 +24,7 @@ ```json { - "transaction_time": "transaction_time4", + "transaction_time": "2016-03-13T12:52:32.123Z", "memo": "memo6", "original_amount": "original_amount6", "applied_amount": "applied_amount6", diff --git a/doc/models/list-payment-profile-item.md b/doc/models/list-payment-profile-item.md deleted file mode 100644 index 65b7f18..0000000 --- a/doc/models/list-payment-profile-item.md +++ /dev/null @@ -1,45 +0,0 @@ - -# List Payment Profile Item - -## Structure - -`ListPaymentProfileItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `FirstName` | `string` | Optional | - | -| `LastName` | `string` | Optional | - | -| `CustomerId` | `int?` | Optional | - | -| `CurrentVault` | [`CurrentVault?`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `string` | Optional | - | -| `BillingAddress` | `string` | Optional | - | -| `BillingCity` | `string` | Optional | - | -| `BillingState` | `string` | Optional | - | -| `BillingZip` | `string` | Optional | - | -| `BillingCountry` | `string` | Optional | - | -| `CustomerVaultToken` | `string` | Optional | - | -| `BillingAddress2` | `string` | Optional | - | -| `BankName` | `string` | Optional | - | -| `MaskedBankRoutingNumber` | `string` | Optional | - | -| `MaskedBankAccountNumber` | `string` | Optional | - | -| `BankAccountType` | `string` | Optional | - | -| `BankAccountHolderType` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | -| `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 56, - "first_name": "first_name6", - "last_name": "last_name4", - "customer_id": 94, - "current_vault": "bogus" -} -``` - diff --git a/doc/models/list-payment-profiles-response.md b/doc/models/list-payment-profiles-response.md deleted file mode 100644 index 4bdc073..0000000 --- a/doc/models/list-payment-profiles-response.md +++ /dev/null @@ -1,27 +0,0 @@ - -# List Payment Profiles Response - -## Structure - -`ListPaymentProfilesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`ListPaymentProfileItem`](../../doc/models/list-payment-profile-item.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "id": 44, - "first_name": "first_name4", - "last_name": "last_name2", - "customer_id": 82, - "current_vault": "eway" - } -} -``` - diff --git a/doc/models/nested-error-response-exception.md b/doc/models/nested-error-response-exception.md deleted file mode 100644 index 08ea189..0000000 --- a/doc/models/nested-error-response-exception.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Nested Error Response Exception - -## Structure - -`NestedErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `object` | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "key0": { - "key1": "val1", - "key2": "val2" - }, - "key1": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - diff --git a/doc/models/payment-profile-response.md b/doc/models/payment-profile-response.md index 296dfdb..8526f48 100644 --- a/doc/models/payment-profile-response.md +++ b/doc/models/payment-profile-response.md @@ -9,33 +9,23 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `PaymentProfile` | [`PaymentProfile`](../../doc/models/payment-profile.md) | Required | - | +| `PaymentProfile` | [`PaymentProfileResponsePaymentProfile`](../../doc/models/containers/payment-profile-response-payment-profile.md) | Required | This is a container for one-of cases. | ## Example (as JSON) ```json { "payment_profile": { - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", + "masked_bank_routing_number": "masked_bank_routing_number8", + "masked_bank_account_number": "masked_bank_account_number8", + "bank_account_type": "checking", "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null + "verified": false, + "id": 188, + "first_name": "first_name6", + "last_name": "last_name4", + "customer_id": 226, + "current_vault": "authorizenet" } } ``` diff --git a/doc/models/payment-profile.md b/doc/models/payment-profile.md deleted file mode 100644 index 42c75bc..0000000 --- a/doc/models/payment-profile.md +++ /dev/null @@ -1,61 +0,0 @@ - -# Payment Profile - -## Structure - -`PaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int?` | Optional | The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. | -| `FirstName` | `string` | Optional | The first name of the card holder. | -| `LastName` | `string` | Optional | The last name of the card holder. | -| `MaskedCardNumber` | `string` | Optional | A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). | -| `CardType` | [`CardType?`](../../doc/models/card-type.md) | Optional | The type of card used. | -| `ExpirationMonth` | `int?` | Optional | An integer representing the expiration month of the card(1 – 12). | -| `ExpirationYear` | `int?` | Optional | An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). | -| `CustomerId` | `int?` | Optional | The Chargify-assigned id for the customer record to which the card belongs. | -| `CurrentVault` | [`CurrentVault?`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `string` | Optional | The “token” provided by your vault storage for an already stored payment profile. | -| `BillingAddress` | `string` | Optional | The current billing street address for the card. | -| `BillingCity` | `string` | Optional | The current billing address city for the card. | -| `BillingState` | `string` | Optional | The current billing address state for the card. | -| `BillingZip` | `string` | Optional | The current billing address zip code for the card. | -| `BillingCountry` | `string` | Optional | The current billing address country for the card. | -| `CustomerVaultToken` | `string` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | -| `BillingAddress2` | `string` | Optional | The current billing street address, second line, for the card. | -| `PaymentType` | [`PaymentType?`](../../doc/models/payment-type.md) | Optional | **Default**: `PaymentType.credit_card` | -| `Disabled` | `bool?` | Optional | - | -| `ChargifyToken` | `string` | Optional | Token received after sending billing informations using chargify.js. | -| `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | An identifier of connected gateway. | - -## Example (as JSON) - -```json -{ - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null -} -``` - diff --git a/doc/models/prepaid-usage-component.md b/doc/models/prepaid-usage-component.md index cdaa9a4..ada5651 100644 --- a/doc/models/prepaid-usage-component.md +++ b/doc/models/prepaid-usage-component.md @@ -9,7 +9,7 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `Name` | `string` | Optional | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | +| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | | `UnitName` | `string` | Optional | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | | `Description` | `string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | | `Handle` | `string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | @@ -40,7 +40,8 @@ "unit_name": "unit_name4", "description": "description8", "handle": "handle8", - "taxable": false + "taxable": false, + "pricing_scheme": "stairstep" } ``` diff --git a/doc/models/price-point.md b/doc/models/price-point.md index 0e89607..4372ac8 100644 --- a/doc/models/price-point.md +++ b/doc/models/price-point.md @@ -14,6 +14,7 @@ | `PricingScheme` | [`PricingScheme?`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | | `Prices` | [`List`](../../doc/models/price.md) | Optional | - | | `UseSiteExchangeRate` | `bool?` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | +| `TaxIncluded` | `bool?` | Optional | Whether or not the price point includes tax | | `Interval` | `int?` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | | `IntervalUnit` | [`IntervalUnit?`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. | | `OveragePricing` | [`OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | diff --git a/doc/models/product-price-point.md b/doc/models/product-price-point.md index c731a5a..9903d4f 100644 --- a/doc/models/product-price-point.md +++ b/doc/models/product-price-point.md @@ -32,6 +32,7 @@ | `Type` | [`PricePointType?`](../../doc/models/price-point-type.md) | Optional | The type of price point | | `TaxIncluded` | `bool?` | Optional | Whether or not the price point includes tax | | `SubscriptionId` | `int?` | Optional | The subscription id this price point belongs to | +| `CurrencyPrices` | [`List`](../../doc/models/currency-price.md) | Optional | An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. | ## Example (as JSON) diff --git a/doc/models/read-payment-profile-response.md b/doc/models/read-payment-profile-response.md deleted file mode 100644 index 8631222..0000000 --- a/doc/models/read-payment-profile-response.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Read Payment Profile Response - -## Structure - -`ReadPaymentProfileResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`ReadPaymentProfileResponsePaymentProfile`](../../doc/models/containers/read-payment-profile-response-payment-profile.md) | Required | This is a container for one-of cases. | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "masked_bank_routing_number": "masked_bank_routing_number8", - "masked_bank_account_number": "masked_bank_account_number8", - "verified": false, - "id": 188, - "first_name": "first_name6", - "last_name": "last_name4", - "customer_id": 226, - "current_vault": "authorizenet" - } -} -``` - diff --git a/doc/models/subscription-bank-account.md b/doc/models/subscription-bank-account.md deleted file mode 100644 index 0388e6a..0000000 --- a/doc/models/subscription-bank-account.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Subscription Bank Account - -## Structure - -`SubscriptionBankAccount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `BankAccountHolderType` | `string` | Optional | Defaults to personal | -| `BankAccountType` | `string` | Optional | Defaults to checking | -| `BankName` | `string` | Optional | The bank where the account resides | -| `BillingAddress` | `string` | Optional | The current billing street address for the bank account | -| `BillingAddress2` | `string` | Optional | The current billing street address, second line, for the bank account | -| `BillingCity` | `string` | Optional | The current billing address city for the bank account | -| `BillingState` | `string` | Optional | The current billing address state for the bank account | -| `BillingZip` | `string` | Optional | The current billing address zip code for the bank account | -| `BillingCountry` | `string` | Optional | The current billing address country for the bank account | -| `CurrentVault` | [`BankAccountVault?`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | -| `CustomerId` | `int?` | Optional | The Chargify-assigned id for the customer record to which the bank account belongs | -| `CustomerVaultToken` | `string` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | -| `FirstName` | `string` | Optional | The first name of the bank account holder | -| `LastName` | `string` | Optional | The last name of the bank account holder | -| `Id` | `int?` | Optional | The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer | -| `MaskedBankAccountNumber` | `string` | Optional | A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) | -| `MaskedBankRoutingNumber` | `string` | Optional | A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account | -| `VaultToken` | `string` | Optional | The “token” provided by your vault storage for an already stored payment profile | -| `ChargifyToken` | `string` | Optional | Token received after sending billing informations using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) | -| `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | - | - -## Example (as JSON) - -```json -{ - "bank_account_holder_type": "bank_account_holder_type4", - "bank_account_type": "bank_account_type4", - "bank_name": "bank_name8", - "billing_address": "billing_address8", - "billing_address_2": "billing_address_28" -} -``` - diff --git a/doc/models/subscription-group-bank-account.md b/doc/models/subscription-group-bank-account.md index 76dfbee..e1a393f 100644 --- a/doc/models/subscription-group-bank-account.md +++ b/doc/models/subscription-group-bank-account.md @@ -14,9 +14,9 @@ | `BankRoutingNumber` | `string` | Optional | (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | | `BankIban` | `string` | Optional | (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided | | `BankBranchCode` | `string` | Optional | (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided | -| `BankAccountType` | [`BankAccountType?`](../../doc/models/bank-account-type.md) | Optional | **Default**: `BankAccountType.checking` | -| `BankAccountHolderType` | [`HolderType?`](../../doc/models/holder-type.md) | Optional | - | -| `PaymentType` | `string` | Optional | - | +| `BankAccountType` | [`BankAccountType?`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking
**Default**: `BankAccountType.checking` | +| `BankAccountHolderType` | [`BankAccountHolderType?`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `PaymentType` | [`PaymentType?`](../../doc/models/payment-type.md) | Optional | **Default**: `PaymentType.credit_card` | | `BillingAddress` | `string` | Optional | - | | `BillingCity` | `string` | Optional | - | | `BillingState` | `string` | Optional | - | @@ -31,6 +31,7 @@ ```json { "bank_account_type": "checking", + "payment_type": "credit_card", "bank_name": "bank_name2", "bank_account_number": "bank_account_number4", "bank_routing_number": "bank_routing_number8", diff --git a/doc/models/subscription-group-credit-card.md b/doc/models/subscription-group-credit-card.md index 65fee2f..97ce8ad 100644 --- a/doc/models/subscription-group-credit-card.md +++ b/doc/models/subscription-group-credit-card.md @@ -25,7 +25,7 @@ | `BillingZip` | `string` | Optional | - | | `BillingCountry` | `string` | Optional | - | | `LastFour` | `string` | Optional | - | -| `CardType` | `string` | Optional | - | +| `CardType` | [`CardType?`](../../doc/models/card-type.md) | Optional | The type of card used. | | `CustomerVaultToken` | `string` | Optional | - | | `Cvv` | `string` | Optional | - | | `PaymentType` | `string` | Optional | - | @@ -36,7 +36,6 @@ { "full_number": 4111111111111111, "chargify_token": "tok_592nf92ng0sjd4300p", - "card_type": "visa", "expiration_month": "String1", "expiration_year": "String5", "vault_token": "vault_token6" diff --git a/doc/models/subscription-included-coupon.md b/doc/models/subscription-included-coupon.md index b48c88f..20c8a14 100644 --- a/doc/models/subscription-included-coupon.md +++ b/doc/models/subscription-included-coupon.md @@ -14,7 +14,7 @@ | `UsesAllowed` | `int?` | Optional | - | | `ExpiresAt` | `string` | Optional | - | | `Recurring` | `bool?` | Optional | - | -| `AmountInCents` | `long?` | Optional | - | +| `AmountInCents` | `long?` | Optional | **Constraints**: `>= 0` | | `Percentage` | `string` | Optional | - | ## Example (as JSON) diff --git a/doc/models/subscription.md b/doc/models/subscription.md index 57e058e..eb9cf3a 100644 --- a/doc/models/subscription.md +++ b/doc/models/subscription.md @@ -37,9 +37,9 @@ | `PaymentCollectionMethod` | [`PaymentCollectionMethod?`](../../doc/models/payment-collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `PaymentCollectionMethod.automatic` | | `Customer` | [`Customer`](../../doc/models/customer.md) | Optional | - | | `Product` | [`Product`](../../doc/models/product.md) | Optional | - | -| `CreditCard` | [`PaymentProfile`](../../doc/models/payment-profile.md) | Optional | - | +| `CreditCard` | [`CreditCardPaymentProfile`](../../doc/models/credit-card-payment-profile.md) | Optional | - | | `Group` | [`SubscriptionGroup2`](../../doc/models/containers/subscription-group-2.md) | Optional | This is a container for one-of cases. | -| `BankAccount` | [`SubscriptionBankAccount`](../../doc/models/subscription-bank-account.md) | Optional | - | +| `BankAccount` | [`BankAccountPaymentProfile`](../../doc/models/bank-account-payment-profile.md) | Optional | - | | `PaymentType` | `string` | Optional | The payment profile type for the active profile on file. | | `ReferralCode` | `string` | Optional | The subscription's unique code that can be given to referrals. | | `NextProductId` | `int?` | Optional | If a delayed product change is scheduled, the ID of the product that the subscription will be changed to at the next renewal. | diff --git a/doc/models/update-component-price-point-request.md b/doc/models/update-component-price-point-request.md index 0c80b07..48251d2 100644 --- a/doc/models/update-component-price-point-request.md +++ b/doc/models/update-component-price-point-request.md @@ -17,31 +17,10 @@ { "price_point": { "name": "name0", - "interval": 44, - "interval_unit": "day", - "prices": [ - { - "id": 18, - "ending_quantity": 38, - "unit_price": 88, - "_destroy": "_destroy4", - "starting_quantity": 64 - }, - { - "id": 18, - "ending_quantity": 38, - "unit_price": 88, - "_destroy": "_destroy4", - "starting_quantity": 64 - }, - { - "id": 18, - "ending_quantity": 38, - "unit_price": 88, - "_destroy": "_destroy4", - "starting_quantity": 64 - } - ] + "handle": "handle6", + "pricing_scheme": "per_unit", + "use_site_exchange_rate": false, + "tax_included": false } } ``` diff --git a/doc/models/update-component-price-point.md b/doc/models/update-component-price-point.md index a426e82..5f4133f 100644 --- a/doc/models/update-component-price-point.md +++ b/doc/models/update-component-price-point.md @@ -10,6 +10,10 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | | `Name` | `string` | Optional | - | +| `Handle` | `string` | Optional | - | +| `PricingScheme` | [`PricingScheme?`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `UseSiteExchangeRate` | `bool?` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. | +| `TaxIncluded` | `bool?` | Optional | Whether or not the price point includes tax | | `Interval` | `int?` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | | `IntervalUnit` | [`IntervalUnit?`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | | `Prices` | [`List`](../../doc/models/update-price.md) | Optional | - | @@ -19,24 +23,10 @@ ```json { "name": "name2", - "interval": 216, - "interval_unit": "day", - "prices": [ - { - "id": 18, - "ending_quantity": 38, - "unit_price": 88, - "_destroy": "_destroy4", - "starting_quantity": 64 - }, - { - "id": 18, - "ending_quantity": 38, - "unit_price": 88, - "_destroy": "_destroy4", - "starting_quantity": 64 - } - ] + "handle": "handle8", + "pricing_scheme": "per_unit", + "use_site_exchange_rate": false, + "tax_included": false } ``` diff --git a/doc/models/update-payment-profile-request.md b/doc/models/update-payment-profile-request.md index 8b41e38..4b516c3 100644 --- a/doc/models/update-payment-profile-request.md +++ b/doc/models/update-payment-profile-request.md @@ -19,7 +19,7 @@ "full_number": "5424000000000015", "first_name": "first_name4", "last_name": "last_name2", - "card_type": "discover", + "card_type": "bogus", "expiration_month": "expiration_month0" } } diff --git a/doc/models/update-payment-profile-response.md b/doc/models/update-payment-profile-response.md deleted file mode 100644 index 2d2636f..0000000 --- a/doc/models/update-payment-profile-response.md +++ /dev/null @@ -1,27 +0,0 @@ - -# Update Payment Profile Response - -## Structure - -`UpdatePaymentProfileResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`UpdatedPaymentProfile`](../../doc/models/updated-payment-profile.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "id": 44, - "first_name": "first_name4", - "last_name": "last_name2", - "card_type": "card_type0", - "expiration_month": 38 - } -} -``` - diff --git a/doc/models/update-payment-profile.md b/doc/models/update-payment-profile.md index 8b3084b..73a66dc 100644 --- a/doc/models/update-payment-profile.md +++ b/doc/models/update-payment-profile.md @@ -30,7 +30,7 @@ "full_number": "5424000000000015", "first_name": "first_name2", "last_name": "last_name0", - "card_type": "switch", + "card_type": "carnet", "expiration_month": "expiration_month2" } ``` diff --git a/doc/models/update-price.md b/doc/models/update-price.md index 575b7c5..ec580fb 100644 --- a/doc/models/update-price.md +++ b/doc/models/update-price.md @@ -10,20 +10,20 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | | `Id` | `int?` | Optional | - | -| `EndingQuantity` | `int?` | Optional | - | -| `UnitPrice` | `int?` | Optional | - | -| `Destroy` | `string` | Optional | - | -| `StartingQuantity` | `int?` | Optional | - | +| `EndingQuantity` | [`UpdatePriceEndingQuantity`](../../doc/models/containers/update-price-ending-quantity.md) | Optional | This is a container for one-of cases. | +| `UnitPrice` | [`UpdatePriceUnitPrice`](../../doc/models/containers/update-price-unit-price.md) | Optional | This is a container for one-of cases. | +| `Destroy` | `bool?` | Optional | - | +| `StartingQuantity` | [`UpdatePriceStartingQuantity`](../../doc/models/containers/update-price-starting-quantity.md) | Optional | This is a container for one-of cases. | ## Example (as JSON) ```json { "id": 18, - "ending_quantity": 38, - "unit_price": 88, - "_destroy": "_destroy0", - "starting_quantity": 64 + "ending_quantity": 216, + "unit_price": 166.62, + "_destroy": false, + "starting_quantity": 242 } ``` diff --git a/doc/models/updated-payment-profile.md b/doc/models/updated-payment-profile.md deleted file mode 100644 index 7e38823..0000000 --- a/doc/models/updated-payment-profile.md +++ /dev/null @@ -1,44 +0,0 @@ - -# Updated Payment Profile - -## Structure - -`UpdatedPaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | -| `FirstName` | `string` | Optional | - | -| `LastName` | `string` | Optional | - | -| `CardType` | `string` | Optional | - | -| `ExpirationMonth` | `int?` | Optional | - | -| `ExpirationYear` | `int?` | Optional | - | -| `CustomerId` | `int?` | Optional | - | -| `CurrentVault` | [`CurrentVault?`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `string` | Optional | - | -| `BillingAddress` | `string` | Optional | - | -| `BillingAddress2` | `string` | Optional | - | -| `BillingCity` | `string` | Optional | - | -| `BillingState` | `string` | Optional | - | -| `BillingZip` | `string` | Optional | - | -| `BillingCountry` | `string` | Optional | - | -| `PaymentType` | `string` | Optional | - | -| `SiteGatewaySettingId` | `int?` | Optional | - | -| `GatewayHandle` | `string` | Optional | - | -| `MaskedCardNumber` | `string` | Optional | - | -| `CustomerVaultToken` | `string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 232, - "first_name": "first_name0", - "last_name": "last_name8", - "card_type": "card_type4", - "expiration_month": 150 -} -``` - diff --git a/doc/models/usage.md b/doc/models/usage.md index b24dd42..090e92d 100644 --- a/doc/models/usage.md +++ b/doc/models/usage.md @@ -9,7 +9,7 @@ | Name | Type | Tags | Description | | --- | --- | --- | --- | -| `Id` | `int?` | Optional | - | +| `Id` | `long?` | Optional | **Constraints**: `>= 0` | | `Memo` | `string` | Optional | - | | `CreatedAt` | `DateTimeOffset?` | Optional | - | | `PricePointId` | `int?` | Optional | - | diff --git a/doc/models/void-invoice-event-data-1.md b/doc/models/void-remainder-event-data.md similarity index 86% rename from doc/models/void-invoice-event-data-1.md rename to doc/models/void-remainder-event-data.md index 9fe783a..cf204fc 100644 --- a/doc/models/void-invoice-event-data-1.md +++ b/doc/models/void-remainder-event-data.md @@ -1,11 +1,11 @@ -# Void Invoice Event Data 1 +# Void Remainder Event Data -Example schema for an `void_invoice` event +Example schema for an `void_remainder` event ## Structure -`VoidInvoiceEventData1` +`VoidRemainderEventData` ## Fields @@ -27,7 +27,7 @@ Example schema for an `void_invoice` event "subscription_id": 0, "number": "number0" }, - "memo": "memo8", + "memo": "memo6", "applied_amount": "applied_amount4", "transaction_time": "2016-03-13T12:52:32.123Z" }