### Install GoCardless Pro Ruby Gem Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Add the GoCardless Pro gem to your application's Gemfile for integration. ```ruby gem 'gocardless_pro' ``` -------------------------------- ### Install GoCardless Pro Ruby Gem Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Add the gem to your Gemfile and require it in your application code to integrate the client. ```ruby # Gemfile gem 'gocardless_pro' # Application code require 'gocardless_pro' ``` -------------------------------- ### Get All Resources with GoCardless Pro Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Use the #all method for a lazily paginated list of all records for a resource type. It handles pagination automatically. ```ruby @client.customers.all.each do |customer| p customer.given_name end ``` -------------------------------- ### Get Single Resource with GoCardless Pro Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Use the #get method to retrieve details for a single resource by its ID. ```ruby @client.customers.get(customer_id) ``` -------------------------------- ### Paginate GoCardless Records in Ruby Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt This example illustrates how to fetch records from GoCardless using cursor-based pagination. It shows manual pagination with cursors and the use of the `#all` method for lazily iterating through all records, which is efficient for large datasets. ```ruby # Manual pagination with list response = client.payments.list(params: { limit: 50 }) response.records.each { |p| process(p) } # Fetch next page using cursor next_cursor = response.after if next_cursor next_page = client.payments.list(params: { limit: 50, after: next_cursor }) end # Access raw response metadata puts response.response.status # => 200 puts response.response.headers # => { "Content-Type" => "application/json", ... } # Auto-paginate all payments lazily (best for large datasets) client.payments.all(params: { status: 'paid_out', limit: 100 }).each do |payment| puts "#{payment.id}: #{payment.amount}" end # Collect into an array (use with caution on large datasets) all_customers = client.customers.all.to_a puts "Total customers: #{all_customers.count}" ``` -------------------------------- ### List Resources with Query Parameters Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Pass an options hash as the last argument to #list to include query parameters for GET requests, such as setting a limit. ```ruby @client.customers.list(params: { limit: 400 }) ``` -------------------------------- ### Access Resource Details After Get Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md After retrieving a resource using #get, you can access its properties, such as given_name. ```ruby p @client.customers.get(customer_id).given_name ``` -------------------------------- ### List All Refunds Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Iterates through all refunds and prints their ID, amount, and currency. No specific setup is required beyond an authenticated client. ```ruby client.refunds.all.each { |r| puts "#{r.id}: #{r.amount} #{r.currency}" } ``` -------------------------------- ### Handle GoCardless Webhooks in Sinatra/Rack Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt This example shows how to process GoCardless webhook events within a Sinatra or Rack application. It parses the request body and signature, then handles potential signature validation errors. ```ruby post '/webhooks' do events = GoCardlessPro::Webhook.parse( request_body: request.body.tap(&:rewind).read, signature_header: request.env['HTTP_WEBHOOK_SIGNATURE'], webhook_endpoint_secret: ENV['GOCARDLESS_WEBHOOK_ENDPOINT_SECRET'] ) events.each { |e| process(e) } status 200 rescue GoCardlessPro::Webhook::InvalidSignatureError status 498 end ``` -------------------------------- ### Create Billing Request Flow Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Generates a URL for a billing request flow, which customers use to complete payment and mandate setup. Requires a billing request ID and redirect URIs. ```ruby # Create a billing request flow to get the hosted URL flow = client.billing_request_flows.create( params: { redirect_uri: 'https://example.com/payment/complete', exit_uri: 'https://example.com/payment/cancelled', links: { billing_request: billing_request.id } } ) puts flow.authorisation_url # redirect customer to this URL ``` -------------------------------- ### Update a Subscription Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Updates an existing subscription, for example, to change the amount or payment reference. ```ruby # Update a subscription's amount client.subscriptions.update('SB123ABC', params: { amount: 2500, payment_reference: 'NEW-REF' } ) ``` -------------------------------- ### Get Single Event Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Retrieves a specific event by its ID. Useful for inspecting the details of a single state change. ```ruby # Get a single event event = client.events.get('EV123ABC') puts event.action # => "confirmed" puts event.resource_type # => "payments" puts event.links # => { payment: "PM123ABC" } ``` -------------------------------- ### Customers Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Manage customer records including creation, retrieval, updates, listing, and removal. Customers are identified by IDs starting with 'CU'. ```APIDOC ## Customers Service `client.customers` — Create, retrieve, update, list, and remove customer records. The customers service manages payer identity records in GoCardless. Customers are identified by IDs beginning with `"CU"`. The `create` method automatically includes an idempotency key to prevent duplicate creation on retries. ```ruby # Create a customer customer = client.customers.create( params: { given_name: 'Jane', family_name: 'Smith', email: 'jane@example.com', phone_number: '+44 20 7183 8674', address_line1: '1 Somewhere Lane', city: 'London', postal_code: 'SW1A 1AA', country_code: 'GB', metadata: { salesforce_id: 'SF-123' } } ) puts customer.id # => "CU123ABC" puts customer.given_name # => "Jane" # Retrieve a single customer customer = client.customers.get('CU123ABC') puts customer.email # => "jane@example.com" # Update a customer updated = client.customers.update('CU123ABC', params: { email: 'jane.new@example.com' } ) # List customers (paginated page) response = client.customers.list(params: { limit: 10 }) response.records.each { |c| puts "#{c.id}: #{c.given_name} #{c.family_name}" } # Auto-paginate all customers lazily client.customers.all.each do |c| puts c.email end # Remove a customer (irreversible) client.customers.remove('CU123ABC') ``` ``` -------------------------------- ### Initialize GoCardless Pro Client Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Initialize the GoCardlessPro::Client with an access token. Use environment: :sandbox for sandbox requests. ```ruby @client = GoCardlessPro::Client.new( access_token: ENV["GOCARDLESS_TOKEN"] ) ``` -------------------------------- ### Initialize GoCardless Pro Client Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Instantiate the client with an access token. Use `:sandbox` for testing or `:live` for production. Options include custom connection timeouts and idempotency conflict handling. ```ruby # Production client client = GoCardlessPro::Client.new( access_token: ENV['GOCARDLESS_TOKEN'] ) ``` ```ruby # Sandbox client with custom options client = GoCardlessPro::Client.new( access_token: ENV['GOCARDLESS_TOKEN'], environment: :sandbox, on_idempotency_conflict: :fetch, # auto-fetch existing resource on conflict (default) connection_options: { request: { timeout: 10 } } ) ``` ```ruby # Raise on idempotency conflict instead of auto-fetching strict_client = GoCardlessPro::Client.new( access_token: ENV['GOCARDLESS_TOKEN'], on_idempotency_conflict: :raise ) ``` -------------------------------- ### Client Initialization Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Instantiate the GoCardlessPro::Client with an access token. Options include environment (sandbox/live), idempotency conflict handling, and custom connection options. ```APIDOC ## Client Initialization `GoCardlessPro::Client.new(options)` — Create an authenticated API client instance. Instantiate `GoCardlessPro::Client` with an access token. Use `environment: :sandbox` for testing and `environment: :live` (default) for production. You can also pass Faraday `connection_options` for timeout tuning and configure idempotency conflict behavior with `on_idempotency_conflict: :raise` or `:fetch` (default). ```ruby # Production client client = GoCardlessPro::Client.new( access_token: ENV['GOCARDLESS_TOKEN'] ) # Sandbox client with custom options client = GoCardlessPro::Client.new( access_token: ENV['GOCARDLESS_TOKEN'], environment: :sandbox, on_idempotency_conflict: :fetch, # auto-fetch existing resource on conflict (default) connection_options: { request: { timeout: 10 } } ) # Raise on idempotency conflict instead of auto-fetching strict_client = GoCardlessPro::Client.new( access_token: ENV['GOCARDLESS_TOKEN'], on_idempotency_conflict: :raise ) ``` ``` -------------------------------- ### List Resources with GoCardless Pro Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Use the #list method to retrieve a list of resources. The response is a GoCardlessPro::ListResponse object. ```ruby @client.customers.list ``` -------------------------------- ### Create Resource with GoCardless Pro Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Use the #create method for POST requests, passing resource attributes under the 'params' key. An idempotency key is automatically generated. ```ruby @client.customers.create( params: { given_name: "Pete", family_name: "Hamilton", email: "pete@hamilton.enterprises", ... } ) ``` -------------------------------- ### Create a Customer Record Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Use the customers service to create a new customer record. The `create` method automatically includes an idempotency key. ```ruby # Create a customer customer = client.customers.create( params: { given_name: 'Jane', family_name: 'Smith', email: 'jane@example.com', phone_number: '+44 20 7183 8674', address_line1: '1 Somewhere Lane', city: 'London', postal_code: 'SW1A 1AA', country_code: 'GB', metadata: { salesforce_id: 'SF-123' } } ) puts customer.id # => "CU123ABC" puts customer.given_name # => "Jane" ``` -------------------------------- ### Create a Subscription Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Creates a recurring payment schedule. Define amount, currency, name, interval, and mandate link. ```ruby # Create a monthly subscription subscription = client.subscriptions.create( params: { amount: 2000, currency: 'GBP', name: 'Premium plan', interval_unit: 'monthly', interval: 1, day_of_month: 15, links: { mandate: 'MD123ABC' } } ) puts subscription.id # => "SB123ABC" puts subscription.status # => "active" puts subscription.upcoming_payments.first # => { charge_date: "2025-02-15", amount: 2000 } ``` -------------------------------- ### Create a Payment Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Creates a Direct Debit payment charge against an active mandate. Specify amount, currency, charge date, and mandate link. ```ruby # Create a payment payment = client.payments.create( params: { amount: 1000, # in pence/cents currency: 'GBP', charge_date: '2025-02-01', description: 'Monthly subscription fee', links: { mandate: 'MD123ABC' }, metadata: { invoice_id: 'INV-001' } } ) puts payment.id # => "PM123ABC" puts payment.status # => "pending_submission" puts payment.amount # => 1000 ``` -------------------------------- ### Require GoCardless Pro Library Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Load the GoCardless Pro library into your Ruby application after adding it to the Gemfile. ```ruby require 'gocardless_pro' ``` -------------------------------- ### Update Resource with GoCardless Pro Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Use the #update method for PUT requests, providing the resource ID and an options hash for the attributes to update. ```ruby @client.customers.update(customer_id, {...}) ``` -------------------------------- ### Create Redirect Flow Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Initiates a redirect flow for customer bank account authorization. Requires a description, session token for verification, success URL, and optionally pre-filled customer details. ```ruby # Create a redirect flow flow = client.redirect_flows.create( params: { description: 'Subscribe to Premium Plan', session_token: SecureRandom.uuid, # store for verification on return success_redirect_url: 'https://example.com/confirm', prefilled_customer: { given_name: 'Jane', family_name: 'Smith', email: 'jane@example.com', country_code: 'GB' } } ) puts flow.redirect_url # send customer to this URL ``` -------------------------------- ### Create a Customer Bank Account Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Link a new bank account to a customer. Supports UK sort code/account number, IBAN, and local equivalents. ```ruby # Create a bank account for a customer bank_account = client.customer_bank_accounts.create( params: { account_holder_name: 'Jane Smith', sort_code: '20-00-00', account_number: '55779911', country_code: 'GB', links: { customer: 'CU123ABC' } } ) puts bank_account.id # => "BA123ABC" puts bank_account.account_type # => "savings" or "checking" ``` -------------------------------- ### Configure Client to Raise on Idempotency Conflict Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Configure the GoCardless client to raise a GoCardlessPro::IdempotencyConflict exception when an idempotent creation request conflicts with an existing resource. This allows for explicit handling of such conflicts. ```ruby @client = GoCardlessPro::Client.new( on_idempotency_conflict: :raise ) begin @client.payments.create(...) rescue GoCardlessPro::IdempotencyConflict => e # do something useful end ``` -------------------------------- ### Create a Mandate Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Use this to create a new Direct Debit mandate. Requires the scheme and the customer bank account ID. ```ruby mandate = client.mandates.create( params: { scheme: 'bacs', links: { customer_bank_account: 'BA123ABC' } } ) puts mandate.id # => "MD123ABC" puts mandate.status # => "pending_submission" ``` -------------------------------- ### Create Billing Request Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Creates a billing request for a one-off payment and mandate. Requires payment and mandate request details. ```ruby # Create a billing request for a one-off payment + mandate billing_request = client.billing_requests.create( params: { payment_request: { amount: 3000, currency: 'GBP', description: 'First payment' }, mandate_request: { currency: 'GBP', scheme: 'bacs' } } ) puts billing_request.id # => "BRQ123ABC" ``` -------------------------------- ### Create a Full Refund Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Issues a full refund for a collected payment. Requires the payment ID and the total amount to be refunded. ```ruby # Create a full refund refund = client.refunds.create( params: { amount: 1000, total_amount_confirmation: 1000, # must equal sum of all refunds for this payment links: { payment: 'PM123ABC' }, metadata: { reason: 'faulty_product' } } ) puts refund.id # => "RF123ABC" puts refund.status # => "created" ``` -------------------------------- ### Handle GoCardless Webhooks in Rails Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt This controller demonstrates how to parse and handle incoming webhook events from GoCardless in a Rails application. It includes signature verification and routing events to specific handlers. ```ruby class WebhooksController < ApplicationController protect_from_forgery except: :create def create webhook_endpoint_secret = ENV['GOCARDLESS_WEBHOOK_ENDPOINT_SECRET'] begin events = GoCardlessPro::Webhook.parse( request_body: request.raw_post, signature_header: request.headers['Webhook-Signature'], webhook_endpoint_secret: webhook_endpoint_secret ) events.each do |event| case event.resource_type when 'payments' handle_payment_event(event) when 'mandates' handle_mandate_event(event) when 'subscriptions' handle_subscription_event(event) end end head :ok rescue GoCardlessPro::Webhook::InvalidSignatureError head :unauthorized # 401 – signature mismatch end end private def handle_payment_event(event) case event.action when 'confirmed' Payment.find_by(gc_id: event.links.payment)&.mark_paid! when 'failed' Payment.find_by(gc_id: event.links.payment)&.mark_failed! end end def handle_mandate_event(event) if event.action == 'cancelled' Subscription.find_by(gc_mandate_id: event.links.mandate)&.suspend! end end end ``` -------------------------------- ### Configure Idempotency Conflict Handling Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Configure the client to raise an error on Idempotency Key conflict instead of retrying. Default behavior is to retry and return the original object. ```ruby @client = GoCardlessPro::Client.new( access_token: ENV["GOCARDLESS_TOKEN"], on_idempotency_conflict: :raise, ) ``` -------------------------------- ### Create a Partial Refund Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Issues a partial refund for a collected payment. The `total_amount_confirmation` must match the refund amount. ```ruby # Create a partial refund partial_refund = client.refunds.create( params: { amount: 500, total_amount_confirmation: 500, links: { payment: 'PM123ABC' } } ) ``` -------------------------------- ### List Payment Failure Events Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Lists all events where a payment failed. Filters events by resource type and action. Prints the event ID and failure description. ```ruby # List payment failure events client.events.list( params: { resource_type: 'payments', action: 'failed' } ).records.each { |e| puts "#{e.id}: #{e.details.description}" } ``` -------------------------------- ### List Bank Accounts for a Customer Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Retrieve all bank accounts associated with a specific customer. ```ruby # List all bank accounts for a customer client.customer_bank_accounts.list( params: { customer: 'CU123ABC' } ).records.each { |ba| puts ba.id } ``` -------------------------------- ### Resume a Paused Subscription Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Resumes a subscription that has been previously paused. ```ruby # Resume a paused subscription client.subscriptions.resume('SB123ABC') ``` -------------------------------- ### Handle GoCardless API Errors in Ruby Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt This snippet demonstrates robust error handling for GoCardless API interactions using specific exception types. It covers validation errors, invalid states, permission issues, authentication failures, and general API or network problems. ```ruby begin payment = client.payments.create( params: { amount: 1000, currency: 'GBP', links: { mandate: 'MD_INVALID' } } ) rescue GoCardlessPro::ValidationError => e # HTTP 422 - invalid request parameters puts e.message # => "mandate is not active" puts e.type # => "validation_failed" puts e.code # => 422 puts e.request_id # => "dummy_request_id" e.errors.each { |err| puts "#{err['field']}: #{err['message']}" } rescue GoCardlessPro::InvalidStateError => e # HTTP 409 - resource in wrong state puts e.message rescue GoCardlessPro::PermissionError => e # HTTP 403 - insufficient permissions for the action puts e.documentation_url rescue GoCardlessPro::AuthenticationError => e # HTTP 401 - invalid or expired access token puts e.message rescue GoCardlessPro::GoCardlessError => e # HTTP 5xx from GoCardless puts e.message rescue GoCardlessPro::ApiError => e # HTTP 5xx from infrastructure (not the API itself) puts e.message rescue GoCardlessPro::IdempotencyConflict => e # Raised when on_idempotency_conflict: :raise and a duplicate key is detected existing_id = e.error['links']['conflicting_resource_id'] existing_payment = client.payments.get(existing_id) rescue Faraday::TimeoutError # Network timeout - safe to retry if request was idempotent puts 'Request timed out' rescue Faraday::ConnectionFailed => e puts "Connection failed: #{e.message}" end ``` -------------------------------- ### List All Customers Lazily Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Iterate over all customer records using a lazy paginator, which fetches pages as needed. ```ruby # Auto-paginate all customers lazily client.customers.all.each do |c| puts c.email end ``` -------------------------------- ### Events Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Query the immutable audit log of all state changes in your account. Events record every state transition across all GoCardless resources. ```APIDOC ## Get Event ### Description Retrieves a single event by its ID. ### Method GET ### Endpoint `/events/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the event. ### Response #### Success Response (200) - **action** (string) - The action performed. - **resource_type** (string) - The type of resource the event relates to. - **links** (object) - Links to related resources. - **payment** (string) - The ID of the related payment. ### Request Example ```ruby client.events.get('EV123ABC') ``` ``` ```APIDOC ## List Events ### Description Lists events based on specified filters. ### Method GET ### Endpoint `/events` ### Parameters #### Query Parameters - **params** (object) - Optional - Filters for listing events. - **resource_type** (string) - Optional - Filter by resource type (e.g., 'payments'). - **action** (string) - Optional - Filter by action (e.g., 'failed'). - **created_at** (object) - Optional - Filter by creation timestamp. - **gte** (string) - Optional - Greater than or equal to the specified timestamp. ### Response #### Success Response (200) - **records** (array) - An array of event objects. - **id** (string) - The ID of the event. - **details** (object) - Details of the event. - **description** (string) - Description of the event details. - **action** (string) - The action performed. - **resource_type** (string) - The type of resource the event relates to. - **links** (object) - Links to related resources. - **payment** (string) - The ID of the related payment. - **created_at** (string) - The timestamp when the event was created. ### Request Example ```ruby client.events.list( params: { resource_type: 'payments', action: 'failed' } ) ``` ``` ```APIDOC ## List All Events ### Description Retrieves all events, with optional filtering and auto-pagination. ### Method GET ### Endpoint `/events` ### Parameters #### Query Parameters - **params** (object) - Optional - Filters for listing events. - **resource_type** (string) - Optional - Filter by resource type (e.g., 'mandates'). - **created_at** (object) - Optional - Filter by creation timestamp. - **gte** (string) - Optional - Greater than or equal to the specified timestamp. ### Response #### Success Response (200) - **created_at** (string) - The timestamp when the event was created. - **action** (string) - The action performed. ### Request Example ```ruby client.events.all( params: { resource_type: 'mandates', created_at: { gte: '2025-01-01T00:00:00Z' } } ) ``` ``` -------------------------------- ### List Customer Records Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Retrieve a paginated list of customer records, optionally specifying a limit. ```ruby # List customers (paginated page) response = client.customers.list(params: { limit: 10 }) response.records.each { |c| puts "#{c.id}: #{c.given_name} #{c.family_name}" } ``` -------------------------------- ### Subscriptions Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Create and manage recurring payment schedules. Subscriptions automatically generate payments on a recurring schedule. ```APIDOC ## Subscriptions Service `client.subscriptions` — Create and manage recurring payment schedules. Subscriptions (ID prefix `"SB"`) automatically generate payments on a recurring schedule defined by `interval`, `interval_unit`, and `amount`. They can be paused (indefinitely or for a set number of billing cycles) and resumed, or cancelled outright. ### Create a monthly subscription ```ruby subscription = client.subscriptions.create( params: { amount: 2000, currency: 'GBP', name: 'Premium plan', interval_unit: 'monthly', interval: 1, day_of_month: 15, links: { mandate: 'MD123ABC' } } ) puts subscription.id # => "SB123ABC" puts subscription.status # => "active" puts subscription.upcoming_payments.first # => { charge_date: "2025-02-15", amount: 2000 } ``` ### Pause a subscription for a set number of billing cycles ```ruby client.subscriptions.pause('SB123ABC', params: { pause_cycles: 2 } ) ``` ### Pause a subscription indefinitely ```ruby client.subscriptions.pause('SB123ABC') ``` ### Resume a paused subscription ```ruby client.subscriptions.resume('SB123ABC') ``` ### Update a subscription's amount ```ruby client.subscriptions.update('SB123ABC', params: { amount: 2500, payment_reference: 'NEW-REF' } ) ``` ### Cancel a subscription ```ruby client.subscriptions.cancel('SB123ABC', params: { metadata: { reason: 'customer_cancelled' } } ) ``` ``` -------------------------------- ### Billing Requests Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Orchestrate flexible hosted payment flows for mandates and payments. Billing Requests power GoCardless's hosted Instant Bank Pay and Direct Debit flows. ```APIDOC ## Create Billing Request ### Description Creates a billing request for a one-off payment and mandate. ### Method POST ### Endpoint `/billing_requests` ### Request Body - **params** (object) - Required - Parameters for creating the billing request. - **payment_request** (object) - Required - Details for the payment. - **amount** (integer) - Required - The amount to charge in the smallest currency unit. - **currency** (string) - Required - The currency code (e.g., 'GBP'). - **description** (string) - Required - A description for the payment. - **mandate_request** (object) - Required - Details for the mandate. - **currency** (string) - Required - The currency code for the mandate. - **scheme** (string) - Required - The payment scheme (e.g., 'bacs'). ### Response #### Success Response (200) - **id** (string) - The ID of the created billing request. ### Request Example ```ruby client.billing_requests.create( params: { payment_request: { amount: 3000, currency: 'GBP', description: 'First payment' }, mandate_request: { currency: 'GBP', scheme: 'bacs' } } ) ``` ``` ```APIDOC ## Create Billing Request Flow ### Description Creates a billing request flow to obtain a hosted URL for customer completion. ### Method POST ### Endpoint `/billing_request_flows` ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating the billing request flow. - **redirect_uri** (string) - Required - The URL to redirect the customer to after completion. - **exit_uri** (string) - Required - The URL to redirect the customer to if they cancel. - **links** (object) - Required - Links to related resources. - **billing_request** (string) - Required - The ID of the billing request. ### Response #### Success Response (200) - **authorisation_url** (string) - The URL for the hosted billing request flow. ### Request Example ```ruby client.billing_requests.create_flow( params: { redirect_uri: 'https://example.com/payment/complete', exit_uri: 'https://example.com/payment/cancelled', links: { billing_request: billing_request.id } } ) ``` ``` ```APIDOC ## Collect Customer Details ### Description Collects customer details for a billing request (server-side). ### Method POST ### Endpoint `/billing_requests/:id/customer_details` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the billing request. #### Request Body - **params** (object) - Required - Customer details. - **customer** (object) - Required - Customer information. - **given_name** (string) - Required - The customer's first name. - **family_name** (string) - Required - The customer's last name. - **email** (string) - Required - The customer's email address. - **country_code** (string) - Required - The customer's country code. ### Request Example ```ruby client.billing_requests.collect_customer_details(billing_request.id, params: { customer: { given_name: 'Jane', family_name: 'Smith', email: 'jane@example.com' } } ) ``` ``` ```APIDOC ## Collect Bank Account Details ### Description Collects bank account details for a billing request. ### Method POST ### Endpoint `/billing_requests/:id/bank_account` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the billing request. #### Request Body - **params** (object) - Required - Bank account details. - **account_holder_name** (string) - Required - The name of the account holder. - **sort_code** (string) - Required - The sort code of the bank account. - **account_number** (string) - Required - The account number. - **country_code** (string) - Required - The country code of the bank account. ### Request Example ```ruby client.billing_requests.collect_bank_account(billing_request.id, params: { account_holder_name: 'Jane Smith', sort_code: '20-00-00', account_number: '55779911', country_code: 'GB' } ) ``` ``` ```APIDOC ## Confirm Payer Details ### Description Confirms the payer details for a billing request (required for mandate requests). ### Method POST ### Endpoint `/billing_requests/:id/payer_details` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the billing request. ### Request Example ```ruby client.billing_requests.confirm_payer_details(billing_request.id) ``` ``` ```APIDOC ## Fulfil Billing Request ### Description Fulfils a billing request. ### Method POST ### Endpoint `/billing_requests/:id/fulfil` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the billing request. ### Request Example ```ruby client.billing_requests.fulfil(billing_request.id) ``` ``` ```APIDOC ## Cancel Billing Request ### Description Cancels a billing request. ### Method POST ### Endpoint `/billing_requests/:id/cancel` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the billing request. ### Request Example ```ruby client.billing_requests.cancel(billing_request.id) ``` ``` -------------------------------- ### Webhook Parsing and Validation Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Verify and deserialize incoming GoCardless webhook payloads. GoCardless signs every webhook with an HMAC-SHA256 signature. ```APIDOC ## Parse Webhook ### Description Verifies the signature of an incoming webhook and deserializes the payload into event objects. ### Method POST ### Endpoint `/webhooks` (Assumed endpoint for receiving webhooks) ### Parameters #### Request Body - **payload** (string) - Required - The raw webhook payload received from GoCardless. - **signature** (string) - Required - The HMAC-SHA256 signature provided by GoCardless. - **webhook_secret** (string) - Required - Your GoCardless webhook endpoint secret. ### Response #### Success Response (200) - Returns an array of `GoCardlessPro::Resources::Event` objects. ### Request Example ```ruby GoCardlessPro::Webhook.parse(payload, signature, webhook_secret) ``` ``` -------------------------------- ### Collect Customer Details for Billing Request Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Collects customer details server-side for a billing request. Use this if not relying solely on the hosted flow. ```ruby # Collect customer details (server-side, if not using hosted flow) client.billing_requests.collect_customer_details(billing_request.id, params: { customer: { given_name: 'Jane', family_name: 'Smith', email: 'jane@example.com' } } ) ``` -------------------------------- ### Redirect Flows Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Create hosted redirect flows for customer bank account authorization. Redirect Flows send customers to GoCardless-hosted pages to enter their bank account details and authorize a Direct Debit mandate. ```APIDOC ## Create Redirect Flow ### Description Creates a redirect flow to initiate the customer bank account authorization process. ### Method POST ### Endpoint `/redirect_flows` ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating the redirect flow. - **description** (string) - Required - A description for the redirect flow. - **session_token** (string) - Required - A unique token for verification on return. - **success_redirect_url** (string) - Required - The URL to redirect the customer to upon success. - **prefilled_customer** (object) - Optional - Prefilled customer details. - **given_name** (string) - Optional - The customer's first name. - **family_name** (string) - Optional - The customer's last name. - **email** (string) - Optional - The customer's email address. - **country_code** (string) - Optional - The customer's country code. ### Response #### Success Response (200) - **redirect_url** (string) - The URL to send the customer to for authorization. ### Request Example ```ruby client.redirect_flows.create( params: { description: 'Subscribe to Premium Plan', session_token: SecureRandom.uuid, success_redirect_url: 'https://example.com/confirm', prefilled_customer: { given_name: 'Jane', family_name: 'Smith', email: 'jane@example.com', country_code: 'GB' } } ) ``` ``` ```APIDOC ## Complete Redirect Flow ### Description Completes a redirect flow after the customer has authorized the mandate. ### Method POST ### Endpoint `/redirect_flows/:id/complete` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the redirect flow. #### Request Body - **params** (object) - Required - Parameters for completing the flow. - **session_token** (string) - Required - The session token used during creation for verification. ### Response #### Success Response (200) - **links** (object) - Links to related resources. - **mandate** (string) - The ID of the created mandate. - **customer** (string) - The ID of the created customer. ### Request Example ```ruby client.redirect_flows.complete(flow.id, params: { session_token: stored_session_token } ) ``` ``` -------------------------------- ### Retrieve a Customer Record Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Fetch a specific customer record using its unique ID. ```ruby # Retrieve a single customer customer = client.customers.get('CU123ABC') puts customer.email # => "jane@example.com" ``` -------------------------------- ### Retrieve a Bank Account Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Fetch a specific customer bank account using its ID. ```ruby # Retrieve a bank account ba = client.customer_bank_accounts.get('BA123ABC') puts ba.bank_name # => "BARCLAYS BANK PLC" ``` -------------------------------- ### Retrieve a Payment Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Fetches a specific payment using its ID. ```ruby # Retrieve a payment payment = client.payments.get('PM123ABC') ``` -------------------------------- ### Retrieve a Mandate Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Fetches a specific mandate using its ID. ```ruby # Retrieve a mandate mandate = client.mandates.get('MD123ABC') ``` -------------------------------- ### Validate and Parse GoCardless Webhooks Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md This controller action demonstrates how to validate the signature of an incoming GoCardless webhook and parse its content into event objects. It requires a webhook endpoint secret, typically stored in an environment variable, for signature verification. Handles invalid signatures by returning a 498 status code. ```ruby class WebhooksController < ApplicationController include ActionController::Live protect_from_forgery except: :create def create webhook_endpoint_secret = ENV['GOCARDLESS_WEBHOOK_ENDPOINT_SECRET'] begin events = GoCardlessPro::Webhook.parse( request_body: request.raw_post, signature_header: request.headers['Webhook-Signature'], webhook_endpoint_secret: webhook_endpoint_secret ) events.each do |event| puts event.id end render status: 200, nothing: true rescue GoCardlessPro::Webhook::InvalidSignatureError render status: 498, nothing: true end end end ``` -------------------------------- ### Retrieve a Refund Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Fetches a specific refund using its ID. ```ruby # Retrieve a refund refund = client.refunds.get('RF123ABC') ``` -------------------------------- ### Set Custom Idempotency Key for POST Request Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Provide a custom idempotency key for a POST request by including it in the 'headers' hash. This ensures unique request execution. ```ruby @client.customers.create( params: { given_name: "Pete", family_name: "Hamilton", ... }, headers: { "Idempotency-Key" => "1f9630a9-0487-418d-bd37-8b77793c9985" } ) ``` -------------------------------- ### Fulfil Billing Request Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Completes a billing request, finalizing any associated payments or mandates. Call this after all necessary details have been collected. ```ruby # Fulfil the billing request fulfilled = client.billing_requests.fulfil(billing_request.id) ``` -------------------------------- ### Pause a Subscription Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Pauses a subscription. Can be for a specific number of cycles or indefinitely. ```ruby # Pause a subscription for 2 billing cycles client.subscriptions.pause('SB123ABC', params: { pause_cycles: 2 } ) # Pause indefinitely (until resume is called) client.subscriptions.pause('SB123ABC') ``` -------------------------------- ### Supply Deterministic Idempotency Key in Ruby Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Override the auto-generated idempotency key for POST requests by providing a deterministic key in the headers option. This ensures that retrying the same call with the same key returns the same resource, preventing duplicate creation. ```ruby # Supply a deterministic idempotency key payment = client.payments.create( params: { amount: 5000, currency: 'GBP', links: { mandate: 'MD123ABC' } }, headers: { 'Idempotency-Key' => "payment-for-invoice-#{invoice.id}" } ) # Retry the same call safely – same key returns the same payment payment_again = client.payments.create( params: { amount: 5000, currency: 'GBP', links: { mandate: 'MD123ABC' } }, headers: { 'Idempotency-Key' => "payment-for-invoice-#{invoice.id}" } ) puts payment.id == payment_again.id # => true ``` -------------------------------- ### Auto-paginate Mandate Events Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Retrieves all mandate events created from a specific date onwards using auto-pagination. Filters by resource type and creation date. ```ruby # Auto-paginate all mandate events from today client.events.all( params: { resource_type: 'mandates', created_at: { gte: '2025-01-01T00:00:00Z' } } ).each { |e| puts "#{e.created_at} - #{e.action}" } ``` -------------------------------- ### Payments Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Create, retrieve, cancel, and retry Direct Debit payment charges. Payments are charges made against an active mandate. ```APIDOC ## Payments Service `client.payments` — Create, retrieve, cancel, and retry Direct Debit payment charges. Payments (ID prefix `"PM"`) are charges made against an active mandate. They can be created for one-off or recurring charges. The `cancel` action is only valid when a payment is `pending_submission`; the `retry` action applies to failed payments (up to 3 retries per payment). ### Create a payment ```ruby payment = client.payments.create( params: { amount: 1000, # in pence/cents currency: 'GBP', charge_date: '2025-02-01', description: 'Monthly subscription fee', links: { mandate: 'MD123ABC' }, metadata: { invoice_id: 'INV-001' } } ) puts payment.id # => "PM123ABC" puts payment.status # => "pending_submission" puts payment.amount # => 1000 ``` ### Retrieve a payment ```ruby payment = client.payments.get('PM123ABC') ``` ### Update payment metadata ```ruby client.payments.update('PM123ABC', params: { metadata: { invoice_id: 'INV-002' } } ) ``` ### Cancel a pending payment ```ruby client.payments.cancel('PM123ABC', params: { metadata: { reason: 'duplicate' } } ) ``` ### Retry a failed payment ```ruby retried = client.payments.retry('PM123ABC', params: { charge_date: '2025-03-01' } ) ``` ### Auto-paginate all failed payments ```ruby client.payments.all(params: { status: 'failed' }).each do |p| puts "Failed: #{p.id} for #{p.amount} #{p.currency}" end ``` ``` -------------------------------- ### List Mandates Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Retrieves a list of mandates, optionally filtered by status. ```ruby # List all mandates client.mandates.all(params: { status: 'active' }).each do |m| puts "#{m.id} - #{m.scheme}" end ``` -------------------------------- ### Customer Bank Accounts Service Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Link and manage bank accounts for customers. Bank accounts (IDs beginning 'BA') store the necessary details for creating mandates. ```APIDOC ## Customer Bank Accounts Service `client.customer_bank_accounts` — Link and manage bank accounts for customers. Customer bank accounts (IDs beginning `"BA"`) store the bank details needed to create mandates. Accounts can be created directly with sort code/account number (UK), IBAN, or local equivalents, and then used to authorise Direct Debit mandates. ```ruby # Create a bank account for a customer bank_account = client.customer_bank_accounts.create( params: { account_holder_name: 'Jane Smith', sort_code: '20-00-00', account_number: '55779911', country_code: 'GB', links: { customer: 'CU123ABC' } } ) puts bank_account.id # => "BA123ABC" puts bank_account.account_type # => "savings" or "checking" # Retrieve a bank account ba = client.customer_bank_accounts.get('BA123ABC') puts ba.bank_name # => "BARCLAYS BANK PLC" # List all bank accounts for a customer client.customer_bank_accounts.list( params: { customer: 'CU123ABC' } ).records.each { |ba| puts ba.id } # Disable a bank account client.customer_bank_accounts.disable('BA123ABC') ``` ``` -------------------------------- ### List Failed Payments Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Retrieves all payments with a 'failed' status, using auto-pagination. ```ruby # Auto-paginate all failed payments client.payments.all(params: { status: 'failed' }).each do |p| puts "Failed: #{p.id} for #{p.amount} #{p.currency}" end ``` -------------------------------- ### Complete Redirect Flow Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Finalizes a redirect flow after the customer has completed the authorization on the GoCardless-hosted page. Requires the flow ID and the stored session token for verification. ```ruby # After customer returns to success_redirect_url, complete the flow completed = client.redirect_flows.complete(flow.id, params: { session_token: stored_session_token }) puts completed.links.mandate # => "MD123ABC" – use for future payments puts completed.links.customer # => "CU123ABC" ``` -------------------------------- ### Cancel a Subscription Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Cancels a subscription outright. ```ruby # Cancel a subscription client.subscriptions.cancel('SB123ABC', params: { metadata: { reason: 'customer_cancelled' } } ) ``` -------------------------------- ### Remove a Customer Record Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Delete a customer record. This action is irreversible. ```ruby # Remove a customer (irreversible) client.customers.remove('CU123ABC') ``` -------------------------------- ### Iterate Through Listed Resources Source: https://github.com/gocardless/gocardless-pro-ruby/blob/master/README.md Iterate through the records of a list response using the .records method to access individual resources. ```ruby @client.customers.list.records.each do |customer| p customer.given_name end ``` -------------------------------- ### Update a Customer Record Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Modify an existing customer record by providing the customer ID and the parameters to update. ```ruby # Update a customer updated = client.customers.update('CU123ABC', params: { email: 'jane.new@example.com' } ) ``` -------------------------------- ### Update Refund Metadata Source: https://context7.com/gocardless/gocardless-pro-ruby/llms.txt Updates the metadata associated with an existing refund. ```ruby # Update refund metadata client.refunds.update('RF123ABC', params: { metadata: { reason: 'updated_reason' } } ) ```