### Complete Webhook Integration Example Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/webhook-handler.md This example demonstrates a full webhook integration using the Go library. It includes setting up a custom logger to handle events and starting an HTTP server to listen for incoming webhook requests. ```go package main import ( "encoding/json" "fmt" "log" "net/http" gocardless "github.com/gocardless/gocardless-pro-go/v6" ) type WebhookLogger struct { events []gocardless.Event } func (w *WebhookLogger) HandleEventWithMeta( event gocardless.Event, webhookID string, ) error { log.Printf( "[%s] %s: %s/%s - %s", webhookID, event.Id, event.ResourceType, event.Action, event.CreatedAt, ) w.events = append(w.events, event) return nil } func main() { logger := &WebhookLogger{} handler, err := gocardless.NewWebhookHandler( "your_webhook_secret", logger, ) if err != nil { log.Fatal(err) } http.Handle("/webhooks/gocardless", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Complete Webhook Integration Example Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/webhook-handler.md A full Go example demonstrating how to set up an HTTP server to receive GoCardless webhooks, validate signatures, and process events. ```APIDOC ## Webhook Integration Example ### Description This example shows a complete Go application that sets up an HTTP server to listen for GoCardless webhooks. It uses the `gocardless.NewWebhookHandler` to automatically validate incoming webhook signatures and then processes the events using a custom logger. ### Code ```go package main import ( "encoding/json" "fmt" "log" "net/http" gocardless "github.com/gocardless/gocardless-pro-go/v6" ) type WebhookLogger struct { events []gocardless.Event } func (w *WebhookLogger) HandleEventWithMeta( event gocardless.Event, webhookID string, ) error { log.Printf( "[%s] %s: %s/%s - %s", webhookID, event.Id, event.ResourceType, event.Action, event.CreatedAt, ) w.events = append(w.events, event) return nil } func main() { logger := &WebhookLogger{} handler, err := gocardless.NewWebhookHandler( "your_webhook_secret", logger, ) if err != nil { log.Fatal(err) } http.Handle("/webhooks/gocardless", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` ### Usage 1. Replace `"your_webhook_secret"` with your actual GoCardless webhook secret. 2. Run the Go program. 3. Configure your GoCardless webhook endpoint to point to `http://:8080/webhooks/gocardless`. ``` -------------------------------- ### Basic GoCardless Client Initialization Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md Initialize the GoCardless client with a basic access token. This is the simplest way to get started. ```go config, err := gocardless.NewConfig("access_token") client, err := gocardless.New(config) ``` -------------------------------- ### Full Refund Workflow Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/refund.md Demonstrates a complete refund workflow, starting from getting a payment, creating a full refund, and then checking its status. This is useful for scenarios requiring a complete reversal of a payment amount. ```go // Step 1: Get the payment payment, err := client.Payments.Get(ctx, "PM123") if err != nil { return err } // Step 2: Create full refund refund, err := client.Refunds.Create(ctx, gocardless.RefundCreateParams{ Amount: payment.Amount, Links: gocardless.RefundCreateParamsLinks{ Payment: payment.Id, }, Reference: "Customer request", }) if err != nil { return err } // Step 3: Wait for status update (via webhook or polling) fmt.Printf("Refund %s initiated (status: %s)\n", refund.Id, refund.Status) // Step 4: Check refund status later refund, err = client.Refunds.Get(ctx, refund.Id) if err != nil { return err } fmt.Printf("Refund status: %s\n", refund.Status) ``` -------------------------------- ### Create Recurring Subscription with Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md This example shows how to create a recurring subscription, specifying the amount, currency, interval, and linking it to an existing mandate. ```go subscription, _ := client.Subscriptions.Create(ctx, gocardless.SubscriptionCreateParams{ Amount: 4999, Currency: "GBP", Interval: 1, IntervalUnit: "monthly", Name: "Monthly Plan", Links: gocardless.SubscriptionCreateParamsLinks{Mandate: mandate.Id}, }) ``` -------------------------------- ### Explicitly Get GoCardless Pro Go Package Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Alternatively, explicitly get the gocardless-pro-go package using go get. ```sh go get -u github.com/gocardless/gocardless-pro-go@v6.3.0 ``` -------------------------------- ### List Customers with Filtering and Pagination in Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/customer.md This example demonstrates how to list customers, applying filters for sorting and pagination. It shows how to set parameters like limit, sort field, and sort direction, and how to process the paginated results. ```go listParams := gocardless.CustomerListParams{ Limit: 50, SortField: "name", SortDirection: "asc", } result, err := client.Customers.List(ctx, listParams) if err != nil { return err } for _, customer := range result.Customers { fmt.Printf("%s: %s\n", customer.Id, customer.Email) } // Fetch next page if result.Meta.Cursors.After != "" { listParams.After = result.Meta.Cursors.After nextResult, err := client.Customers.List(ctx, listParams) } ``` -------------------------------- ### Action Service Methods Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/MANIFEST.md Shows how to use Create, Get, List, All, and specific action methods for services like Payments (Cancel, Retry). ```go payment, _ := client.Payments.Create(ctx, params) payment, _ := client.Payments.Cancel(ctx, id, params) payment, _ := client.Payments.Retry(ctx, id, params) ``` -------------------------------- ### Configure GoCardless Client Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md Provides an example of how to create a new GoCardless client configuration, specifying the endpoint (e.g., Sandbox) and an optional custom HTTP client. ```go config, _ := gocardless.NewConfig(token, gocardless.WithEndpoint(gocardless.SandboxEndpoint), gocardless.WithClient(customHttpClient), ) client, _ := gocardless.New(config) ``` -------------------------------- ### Webhook Handler Setup Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/overview.md Set up a webhook handler to receive and process real-time events from GoCardless. Ensure the webhook secret is correct. ```go handler, err := gocardless.NewWebhookHandler( "webhook_secret", gocardless.EventHandlerFunc(func(event gocardless.Event) error { fmt.Printf("Event: %s/%s\n", event.ResourceType, event.Action) return nil }), ) http.Handle("/webhooks", handler) ``` -------------------------------- ### Standard CRUD Service Methods Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/MANIFEST.md Demonstrates the standard Create, Get, List, All, Update, and Remove methods for CRUD services like Customers. ```go customer, _ := client.Customers.Create(ctx, params) customer, _ := client.Customers.Get(ctx, id) result, _ := client.Customers.List(ctx, params) iterator := client.Customers.All(ctx, params) customer, _ := client.Customers.Update(ctx, id, params) customer, _ := client.Customers.Remove(ctx, id, params) ``` -------------------------------- ### Initialize GoCardless Client with Custom HTTP Client Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Initialize the GoCardless client with a customized http client, for example, to set a timeout. ```go customHttpClient := &http.Client{ Timeout: time.Second * 10, } config, err := gocardless.NewConfig(token, gocardless.WithClient(customHttpClient)) if err != nil { fmt.Printf("got err in initialising config: %s", err.Error()) return } client, err := gocardless.New(config) if err != nil { fmt.Printf("error in initialisating client: %s", err.Error()) return } ``` -------------------------------- ### Read-Only Service Methods Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/MANIFEST.md Illustrates the Get, List, and All methods for read-only services such as Events and Balances. ```go event, _ := client.Events.Get(ctx, id) result, _ := client.Events.List(ctx, params) iterator := client.Events.All(ctx, params) ``` -------------------------------- ### Create Mandate and Schedule First Payment Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/mandate.md This example demonstrates the common pattern of first creating a mandate and then, after it's active, creating a payment linked to that mandate. Ensure you handle the mandate activation process, potentially by listening for webhooks. ```go // Step 1: Create mandate mandate, err := client.Mandates.Create(ctx, gocardless.MandateCreateParams{ Reference: "Monthly subscription", Scheme: "bacs", Links: gocardless.MandateCreateParamsLinks{ Creditor: "CR123", Customer: "CU123", CustomerBankAccount: "BA456", }, }) ``` ```go if err != nil { return err } ``` ```go // Step 2: Wait for activation (may require customer action) // In production, listen for webhook events // Step 3: Create first payment once active payment, err := client.Payments.Create(ctx, gocardless.PaymentCreateParams{ Amount: 10000, // 100.00 GBP Currency: "GBP", ChargeDate: "2024-02-01", Links: gocardless.PaymentCreateParamsLinks{ Mandate: mandate.Id, }, }) ``` -------------------------------- ### Handle Webhooks with Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md This example demonstrates how to set up a webhook handler to process incoming events from GoCardless. It uses a switch statement to differentiate between event actions like 'created' and 'failed'. ```go handler, _ := gocardless.NewWebhookHandler("secret", gocardless.EventHandlerFunc(func(event gocardless.Event) error { switch event.Action { case "created": fmt.Printf("%s created\n", event.ResourceType) case "failed": fmt.Printf("%s failed\n", event.ResourceType) } return nil })) http.Handle("/webhooks", handler) ``` -------------------------------- ### Go: Payment Creation with Charge Date Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/types.md Example of creating a payment, specifying the charge date in 'YYYY-MM-DD' format. Ensure dates adhere to the specified format. ```go params := PaymentCreateParams{ ChargeDate: "2024-02-15", // YYYY-MM-DD format } ``` -------------------------------- ### Fetch a Single Customer Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Use the `Get` method to retrieve a single customer by their ID. Ensure you have the customer's ID. ```Go ctx := context.TODO() customer, err := client.Customers.Get(ctx, "CU123") ``` -------------------------------- ### Cursor-Based Pagination Example Flow Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/endpoints.md Illustrates the flow of cursor-based pagination. Subsequent requests use the 'after' cursor from the previous response to fetch the next page of results. ```http Request 1: GET /customers?limit=50 Response 1: [customers], meta.cursors.after = "XYZ123" Request 2: GET /customers?limit=50&after=XYZ123 Response 2: [customers], meta.cursors.after = "ABC456" Request 3: GET /customers?limit=50&after=ABC456 Response 3: [customers], meta.cursors.after = null (no more pages) ``` -------------------------------- ### Create Payment Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/payment.md Creates a new payment against a mandate. Ensure the mandate is in an active or pending state. This example demonstrates setting amount, currency, charge date, mandate link, description, reference, and metadata. ```Go ctx := context.TODO() payment, err := client.Payments.Create(ctx, gocardless.PaymentCreateParams{ Amount: 10000, // 100.00 GBP Currency: "GBP", ChargeDate: "2024-02-01", Links: gocardless.PaymentCreateParamsLinks{ Mandate: "MD123", }, Description: "Monthly subscription", Reference: "INV-2024-001", Metadata: map[string]string{ "invoice_id": "INV-2024-001", }, }) if err != nil { return err } fmt.Printf("Created payment: %s (status: %s)\n", payment.Id, payment.Status) ``` -------------------------------- ### List customers (paginated) Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Use the `List` method to fetch customers in a collection, one page at a time. You can specify `After` to get the next page. ```APIDOC ## GET /customers ### Description Lists customer resources, supporting pagination. ### Method GET ### Endpoint `/customers` ### Parameters #### Query Parameters - **after** (string) - Optional - Returns resources after this cursor. ### Request Example ```go ctx := context.TODO() customerListParams := gocardless.CustomerListParams{} customers, err := client.Customers.List(ctx, customerListParams) cursor := customers.Meta.Cursors.After customerListParams.After = cursor nextPageCustomers, err := client.Customers.List(ctx, customerRemoveParams) ``` ``` -------------------------------- ### Go: Date Range Parameters Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/types.md Defines parameters for filtering resources by date ranges. Use 'Gte' for greater than or equal to and 'Lt' for less than. Example shows usage with CustomerListParams. ```go type CreatedAtParams struct { Gt string // Greater than Gte string // Greater than or equal Lt string // Less than Lte string // Less than or equal } // Usage: params := CustomerListParams{ CreatedAt: &CustomerListParamsCreatedAt{ Gte: "2024-01-01", Lt: "2024-02-01", }, } ``` -------------------------------- ### Initialize GoCardless Client with Access Token Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/configuration.md Use `NewConfig` to create a configuration object with your access token, then pass it to `New` to create the client. Ensure the token is not empty. ```go config, err := gocardless.NewConfig("your_access_token") if err != nil { return err } client, err := gocardless.New(config) ``` -------------------------------- ### Initialize GoCardless Client and Access Services Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Demonstrates how to initialize the GoCardless client with configuration and access various service interfaces like Customers, Payments, and Mandates. ```go client, err := gocardless.New(config) // Access services via: // client.Customers // client.Payments // client.Mandates // client.Refunds // ... etc ``` -------------------------------- ### Instalment Schedules Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/endpoints.md Manage instalment schedules, including creation, retrieval, listing, updating, cancellation, and pagination. ```APIDOC ## Create Instalment Schedule ### Description Creates a new instalment schedule. ### Method POST ### Endpoint /instalment_schedules ### Parameters #### Request Body - **InstalmentScheduleCreateParams** (object) - Required - Parameters for creating an instalment schedule. ### Response #### Success Response (200) - **InstalmentSchedule** (*InstalmentSchedule) - The created instalment schedule. ``` ```APIDOC ## Get Instalment Schedule ### Description Retrieves a specific instalment schedule by its ID. ### Method GET ### Endpoint /instalment_schedules/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the instalment schedule. ### Response #### Success Response (200) - **InstalmentSchedule** (*InstalmentSchedule) - The requested instalment schedule. ``` ```APIDOC ## List Instalment Schedules ### Description Retrieves a list of instalment schedules, with optional filtering. ### Method GET ### Endpoint /instalment_schedules ### Parameters #### Query Parameters - **InstalmentScheduleListParams** (object) - Optional - Parameters for filtering the list of instalment schedules. ### Response #### Success Response (200) - **InstalmentScheduleListResult** (*InstalmentScheduleListResult) - A list of instalment schedules. ``` ```APIDOC ## List All Instalment Schedules (Paginated) ### Description Retrieves all instalment schedules using pagination. ### Method GET ### Endpoint /instalment_schedules ### Parameters #### Query Parameters - **InstalmentScheduleListParams** (object) - Optional - Parameters for filtering the list of instalment schedules. ### Response #### Success Response (200) - **InstalmentScheduleListPagingIterator** (*InstalmentScheduleListPagingIterator) - An iterator for paginating through instalment schedules. ``` ```APIDOC ## Update Instalment Schedule ### Description Updates an existing instalment schedule. ### Method PUT ### Endpoint /instalment_schedules/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the instalment schedule to update. #### Request Body - **InstalmentScheduleUpdateParams** (object) - Required - Parameters for updating the instalment schedule. ### Response #### Success Response (200) - **InstalmentSchedule** (*InstalmentSchedule) - The updated instalment schedule. ``` ```APIDOC ## Cancel Instalment Schedule ### Description Cancels a specific instalment schedule. ### Method POST ### Endpoint /instalment_schedules/{id}/actions/cancel ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the instalment schedule to cancel. ### Response #### Success Response (200) - **InstalmentSchedule** (*InstalmentSchedule) - The cancelled instalment schedule. ``` -------------------------------- ### Create Customer in Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/overview.md Use this snippet to create a new customer with basic details. Ensure the `ctx` and `client` are properly initialized. ```go customer, _ := client.Customers.Create(ctx, gocardless.CustomerCreateParams{ GivenName: "John", FamilyName: "Doe", Email: "john@example.com", CountryCode: "GB", }) ``` -------------------------------- ### Retrieve a Customer Resource by ID Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Fetches a specific customer resource using its unique identifier. The `Get` method performs a GET request to the API and automatically retries up to 3 times on failure. ```go customer, err := client.Customers.Get(ctx, "CU123") if err != nil { return err } fmt.Printf("Customer email: %s\n", customer.Email) ``` -------------------------------- ### Get Subscription Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/subscription.md Retrieves a specific subscription by its ID. ```APIDOC ## Get Subscription ### Description Retrieves a specific subscription by its ID. ### Method GET ### Endpoint /subscriptions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Unique subscription identifier ### Response #### Success Response (200) - **Subscription** (*Subscription) - Details of the subscription #### Response Example { "id": "sub_abc123", "amount": 1000, "currency": "GBP", "status": "active", "name": "Monthly Newsletter", "description": "", "interval": 1, "interval_unit": "monthly", "day_of_month": null, "month": null, "start_date": "2023-01-01", "end_date": null, "count": null, "app_fee": 0, "created_at": "2022-12-01T10:00:00Z", "metadata": {}, "links": { "mandate": "man_abc123", "creditor": "cred_abc123", "customer": "cus_abc123" } } ``` -------------------------------- ### Initialize GoCardless Pro Go Client Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/overview.md Create a new configuration with your access token and then initialize the GoCardless client. Ensure you handle potential errors during initialization. ```go import gocardless "github.com/gocardless/gocardless-pro-go/v6" // Create configuration config, err := gocardless.NewConfig("your_access_token") if err != nil { return err } // Initialize client client, err := gocardless.New(config) if err != nil { return err } ``` -------------------------------- ### Configure GoCardless Client for Live or Sandbox Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/overview.md Use `gocardless.NewConfig` to initialize the client. The default endpoint is live; use `gocardless.WithEndpoint(gocardless.SandboxEndpoint)` for sandbox testing. ```go // Live (default) config, _ := gocardless.NewConfig(token) ``` ```go // Sandbox for testing config, _ := gocardless.NewConfig( token, gocardless.WithEndpoint(gocardless.SandboxEndpoint), ) ``` -------------------------------- ### Get Mandate Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/mandate.md Retrieves a specific mandate by its ID. ```APIDOC ## Get Mandate ### Description Retrieves a specific mandate by its ID. ### Method GET ### Endpoint /mandates/{identity} ### Parameters #### Path Parameters - **identity** (string) - Required - The unique identifier of the mandate (e.g., "MD123"). ### Response #### Success Response (200) - **Mandate** (*Mandate) - The mandate object. ``` -------------------------------- ### Get Payment Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/payment.md Retrieves a specific payment by its unique identifier. ```APIDOC ## Get Payment ### Description Retrieves a single payment by its ID. ### Method `Get` ### Parameters - `ctx` (context.Context) - The request context. - `identity` (string) - The unique identifier of the payment (e.g., "PM123"). - `opts` (...RequestOption) - Optional request configuration. ### Returns - `*Payment` - A pointer to the Payment object. - `error` - An error if the payment was not found or retrieval failed. ``` -------------------------------- ### Create a Payment with Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md This snippet shows the steps to create a payment, including creating a customer, bank account, and mandate before the payment itself. Ensure all necessary IDs are correctly linked. ```go // 1. Create customer customer, _ := client.Customers.Create(ctx, gocardless.CustomerCreateParams{ GivenName: "John", FamilyName: "Doe", Email: "john@example.com", CountryCode: "GB", }) // 2. Create bank account bankAccount, _ := client.CustomerBankAccounts.Create(ctx, gocardless.CustomerBankAccountCreateParams{ AccountHolderName: "John Doe", CountryCode: "GB", Links: gocardless.CustomerBankAccountCreateParamsLinks{Customer: customer.Id}, }) // 3. Create mandate mandate, _ := client.Mandates.Create(ctx, gocardless.MandateCreateParams{ Reference: "Subscription", Scheme: "bacs", Links: gocardless.MandateCreateParamsLinks{ Creditor: creditorId, Customer: customer.Id, CustomerBankAccount: bankAccount.Id, }, }) // 4. Create payment payment, _ := client.Payments.Create(ctx, gocardless.PaymentCreateParams{ Amount: 10000, Currency: "GBP", ChargeDate: "2024-02-01", Links: gocardless.PaymentCreateParamsLinks{Mandate: mandate.Id}, }) ``` -------------------------------- ### Get Mandate Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/mandate.md Retrieves a single mandate by its unique identifier. ```APIDOC ## Get Mandate ### Description Retrieves a single mandate by ID. ### Method `Get` ### Parameters #### Path Parameters - **identity** (string) - Required - The unique identifier of the mandate to retrieve. #### Request Body This method does not accept a request body. ### Response #### Success Response - **Mandate** - An object containing the current status and details of the mandate. #### Error Response - **error** - Returned if the mandate is not found or another error occurs. ### Example ```go mandate, err := client.Mandates.Get(ctx, "MD123") if err != nil { return err } fmt.Printf("Mandate %s: %s (status: %s) ", mandate.Id, mandate.Reference, mandate.Status) ``` ``` -------------------------------- ### InstalmentSchedules Service Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Provides access to recurring instalment payments. ```APIDOC ## InstalmentSchedules ### Description Recurring instalment payments. ### Resource Type InstalmentSchedule ``` -------------------------------- ### Initialize Go Modules Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Initialize Go Modules for your project. Ensure your project has a go.mod file. ```sh go mod init go mod tidy ``` -------------------------------- ### Get Customer Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/customer.md Retrieves a specific customer record by its unique identifier. ```APIDOC ## Get Customer ### Description Retrieves a specific customer record. ### Method GET ### Endpoint `/customers/{identity}` ### Parameters #### Path Parameters - **identity** (string) - Required - The unique identifier of the customer (e.g., "CU123"). ### Response #### Success Response (200 OK) - **customer** (Customer) - The customer object. #### Response Example ```json { "customer": { "id": "CU123", "given_name": "John", "family_name": "Doe", "email": "john.doe@example.com", "address_line1": "123 Main St", "city": "Anytown", "postal_code": "12345", "country_code": "US", "created_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Initialize GoCardless Client with Default Config Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Initialize the GoCardless client with an access token. This configuration uses the GoCardless live environment by default. ```go token := "your_access_token" config, err := gocardless.NewConfig(token) if err != nil { fmt.Printf("got err in initialising config: %s", err.Error()) return } client, err := gocardless.New(config) if err != nil { fmt.Printf("error in initialisating client: %s", err.Error()) return } ``` -------------------------------- ### Get Refund Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/refund.md Retrieves a specific refund by its ID. Useful for checking the status of a refund. ```APIDOC ## Get Retrieves a specific refund by its ID. **Example** ```go refund, err := client.Refunds.Get(ctx, refund.Id) ``` ``` -------------------------------- ### Get Refund Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/refund.md Retrieves a specific refund by its identity. This operation is accessed via `client.Refunds.Get`. ```APIDOC ## Get Refund ### Description Retrieves a specific refund by its identity. ### Method `Get(ctx context.Context, identity string, opts ...RequestOption) (*Refund, error)` ### Parameters - `ctx` (context.Context) - The context for the request. - `identity` (string) - The unique identifier of the refund. - `opts` (...RequestOption) - Optional request options. ### Returns - `*Refund` - The requested refund object. - `error` - An error if the refund retrieval failed. ``` -------------------------------- ### Fetch a single customer Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Use the `Get` method to fetch a single customer by their ID. ```APIDOC ## GET /customers/:id ### Description Fetches a single customer resource. ### Method GET ### Endpoint `/customers/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the customer. ### Request Example ```go ctx := context.TODO() customer, err := client.Customers.Get(ctx, "CU123") ``` ``` -------------------------------- ### Initialize GoCardless Client for Sandbox Environment Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Initialize the GoCardless client with a custom endpoint for the sandbox environment. ```go token := "your_access_token" config, err := gocardless.NewConfig(token, gocardless.WithEndpoint(gocardless.SandboxEndpoint)) if err != nil { fmt.Printf("got err in initialising config: %s", err.Error()) return } client, err := gocardless.New(config) if err != nil { fmt.Printf("error in initialisating client: %s", err.Error()) return } ``` -------------------------------- ### Create Payment Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/payment.md Creates a new payment. This can be used for one-off payments or as part of a recurring payment setup. ```APIDOC ## Create Payment ### Description Creates a new payment. This can be used for one-off payments or as part of a recurring payment setup. ### Method POST ### Endpoint /payments ### Parameters #### Request Body - **Amount** (integer) - Required - The amount to charge in the smallest currency unit (e.g., pence for GBP). - **Currency** (string) - Required - The ISO currency code (e.g., "GBP"). - **ChargeDate** (string) - Required - The date the payment should be charged, in "YYYY-MM-DD" format. - **Links** (object) - Required - Contains links to related resources. - **Mandate** (string) - Required - The ID of the mandate to use for this payment. - **Description** (string) - Optional - A description for the payment. - **Metadata** (object) - Optional - Key-value pairs for custom metadata. ``` -------------------------------- ### List Payments with Pagination in Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/overview.md Demonstrates how to list payments using pagination. Includes fetching the first page, then the next page using cursors, and finally using an iterator for all payments. ```go // Get first page result, _ := client.Payments.List(ctx, gocardless.PaymentListParams{Limit: 100}) fmt.Printf("Page 1: %d payments\n", len(result.Payments)) // Fetch next page if result.Meta.Cursors.After != "" { nextResult, _ := client.Payments.List(ctx, gocardless.PaymentListParams{ Limit: 100, After: result.Meta.Cursors.After, }) fmt.Printf("Page 2: %d payments\n", len(nextResult.Payments)) } // Or use automatic iterator iterator := client.Payments.All(ctx, gocardless.PaymentListParams{}) for iterator.Next() { result, _ := iterator.Value(ctx) for _, payment := range result.Payments { fmt.Printf("Payment: %s\n", payment.Id) } } ``` -------------------------------- ### Get Refund Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/refund.md Retrieves a single refund by its unique identifier. Useful for checking the status or details of a specific refund. ```APIDOC ## Get Refund ### Description Retrieves a single refund by ID. ### Method `Get` ### Parameters - **ctx** (context.Context) - The context for the request. - **identity** (string) - The unique identifier of the refund to retrieve. - **opts** (...RequestOption) - Optional request options. ### Returns - `*Refund` - A Refund object with current status and details. - `error` - An error if the refund is not found or another issue occurs. ### Example ```go refund, err := client.Refunds.Get(ctx, "RF123") if err != nil { return err } fmt.Printf("Refund %s: %d %s (status: %s)", refund.Id, refund.Amount, refund.Currency, refund.Status) ``` ``` -------------------------------- ### Set Up GoCardless Webhook Handler Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md Illustrates how to create a webhook handler using a shared secret and an event handler function, then register it with an HTTP server. ```go handler, _ := gocardless.NewWebhookHandler(secret, eventHandler) http.Handle("/webhooks", handler) ``` -------------------------------- ### Read-Only Services Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/MANIFEST.md Offers Get, List, and All methods for services that primarily provide data retrieval, such as Events and Balances. ```APIDOC ## Read-Only Services ### Description These services are designed for data retrieval and provide Get, List, and All methods. ### Services Events, Balances, Institutions, CurrencyExchangeRates. ### Methods - **Get**: Retrieves a specific resource by ID. - **List**: Lists resources with optional filtering parameters. - **All**: Retrieves all resources, potentially returning an iterator. ### Example Usage (Go) ```go // Get an event by ID event, err := client.Events.Get(ctx, id) // List events with parameters result, err := client.Events.List(ctx, params) // Get an iterator for all events iterator := client.Events.All(ctx, params) ``` ``` -------------------------------- ### Create a Subscription Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/subscription.md Use this snippet to create a new subscription. Ensure you provide all required parameters like amount, currency, interval, interval unit, and mandate ID. Optional parameters can customize the subscription further. ```go ctx := context.TODO() subscription, err := client.Subscriptions.Create(ctx, gocardless.SubscriptionCreateParams{ Amount: 9999, // £99.99 Currency: "GBP", Interval: 1, IntervalUnit: "monthly", StartDate: "2024-02-01", EndDate: "2025-02-01", Name: "Premium Plan", Description: "Annual premium subscription", Links: gocardless.SubscriptionCreateParamsLinks{ Mandate: "MD123", }, Metadata: map[string]string{ "plan_id": "plan_premium", }, }) if err != nil { return err } fmt.Printf("Created subscription: %s\n", subscription.Id) ``` -------------------------------- ### Get Resource Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Retrieves a single resource by its unique identifier. This operation is safe to retry automatically and defaults to 3 retry attempts. ```APIDOC ## Get Resource ### Description Retrieves a single resource by ID. ### Method Signature ```go func (s *ServiceImpl) Get(ctx context.Context, identity string, opts ...RequestOption) (*Resource, error) ``` ### Parameters #### Path Parameters - **identity** (string) - Required - Resource ID to fetch #### Query Parameters None #### Request Body Parameters - **ctx** (context.Context) - Required - Request context - **opts** (...RequestOption) - Optional - Optional request options ### Request Example ```go customer, err := client.Customers.Get(ctx, "CU123") if err != nil { return err } fmt.Printf("Customer email: %s\n", customer.Email) ``` ### Response #### Success Response (200) - **Resource** (*Resource) - All fields populated from server #### Error Response - **error** (error) - If resource not found (404) or request fails ### Behavior - GET request to `/{endpoint}/{resource}/{identity}` - Default retry count: 3 attempts - Safe to retry automatically ``` -------------------------------- ### Get a Mandate by ID in Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/mandate.md Retrieves a single mandate using its unique identifier. Handles potential errors during the API call. ```go mandate, err := client.Mandates.Get(ctx, "MD123") if err != nil { return err } fmt.Printf("Mandate %s: %s (status: %s)\n", mandate.Id, mandate.Reference, mandate.Status) ``` -------------------------------- ### Create a New Customer Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Use the `Create` method to create a new customer. Provide all required customer details in the `CustomerCreateParams` struct. ```Go ctx := context.TODO() customerCreateParams := gocardless.CustomerCreateParams{ AddressLine1: "9 Acer Gardens" City: "Birmingham", PostalCode: "B4 7NJ", CountryCode: "GB", Email: "bbr@example.com", GivenName: "Bender Bending", FamilyName: "Rodgriguez", } customer, err := client.Customers.Create(ctx, customerCreateParams) ``` -------------------------------- ### Using Request Options in Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Demonstrates how to pass optional request parameters like retries, idempotency keys, and custom headers to service methods. Options are applied from left to right. ```go customer, err := client.Customers.Create(ctx, params, gocardless.WithRetries(5), gocardless.WithIdempotencyKey("custom-key-123"), gocardless.WithHeaders(map[string]string{ "Accept-Language": "fr", }), ) ``` -------------------------------- ### Get Subscription Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/subscription.md Retrieves a single subscription by its unique identifier. This method allows you to fetch the current status and payment schedule of a specific subscription. ```APIDOC ## Get Subscription ### Description Retrieves a single subscription by ID. This method allows you to fetch the current status and payment schedule of a specific subscription. ### Method ```go func (s *SubscriptionServiceImpl) Get(ctx context.Context, identity string, opts ...RequestOption) (*Subscription, error) ``` ### Parameters #### Path Parameters - **identity** (string) - Required - The unique identifier of the subscription to retrieve. #### Request Body This method does not accept a request body. ### Response #### Success Response - **Subscription** (*Subscription) - An object containing the subscription details, including its current status and payment schedule. #### Error Response - **error** - An error object if the subscription is not found or another issue occurs. ### Example ```go subscription, err := client.Subscriptions.Get(ctx, "SB123") if err != nil { return err } fmt.Printf("Subscription: %s - %s (%s) ", subscription.Id, subscription.Name, subscription.Status) fmt.Printf("Amount: %d %s every %d %s ", subscription.Amount, subscription.Currency, subscription.Interval, subscription.IntervalUnit) ``` ``` -------------------------------- ### List Customers Page by Page Source: https://github.com/gocardless/gocardless-pro-go/blob/master/README.md Use the `List` method to fetch customers in pages. You can use the `After` cursor to paginate through results. ```Go ctx := context.TODO() customerListParams := gocardless.CustomerListParams{} customers, err := client.Customers.List(ctx, customerListParams) for _, customer := range customers.Customers { fmt.Printf("customer: %v", customer) } cursor := customers.Meta.Cursors.After customerListParams.After = cursor nextPageCustomers, err := client.Customers.List(ctx, customerRemoveParams) ``` -------------------------------- ### Bulk Create Customers Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/customer.md Demonstrates how to create multiple customers in bulk by iterating over provided data and using the client.Customers.Create method. ```APIDOC ## Bulk Create Customers ### Description This code snippet illustrates how to perform a bulk creation of customers. It iterates through a dataset (e.g., from CSV data), creating each customer using the `client.Customers.Create` method and collecting their IDs. Error handling is included for individual creation failures. ### Example ```go var customerIDs []string for _, data := range csvData { customer, err := client.Customers.Create(ctx, gocardless.CustomerCreateParams{ GivenName: data.FirstName, FamilyName: data.LastName, Email: data.Email, CountryCode: data.Country, Metadata: map[string]string{ "source": "bulk_import", }, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create customer: %v\n", err) continue } customerIDs = append(customerIDs, customer.Id) } ``` ``` -------------------------------- ### Process Refunds with Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/README.md This snippet illustrates how to process a refund for a payment. It includes fetching the payment details, creating a refund (full or partial), and monitoring its status. ```go // Get payment payment, _ := client.Payments.Get(ctx, "PM123") // Create refund refund, _ := client.Refunds.Create(ctx, gocardless.RefundCreateParams{ Amount: payment.Amount, // Full refund Links: gocardless.RefundCreateParamsLinks{Payment: payment.Id}, }) // Monitor status refund, _ = client.Refunds.Get(ctx, refund.Id) fmt.Printf("Status: %s\n", refund.Status) ``` -------------------------------- ### Client Configuration Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/MANIFEST.md Details on how to initialize and configure the GoCardless client service and its options. ```APIDOC ## Client Configuration ### Main Entry Points - **`New(config Config)`**: Initializes and returns a new client service with the provided configuration. - **`NewConfig(token string, opts ...ConfigOption)`**: Creates a new configuration object, requiring an API token and accepting optional configuration settings. ### Configuration Options These options can be passed to `NewConfig` or used to modify an existing configuration: - **`WithEndpoint(endpoint string)`**: Sets the base URL for API requests. - **`WithClient(client *http.Client)`**: Allows providing a custom `http.Client` instance. ### Constants - **`LiveEndpoint`**: The default endpoint for the live GoCardless API (`https://api.gocardless.com`). - **`SandboxEndpoint`**: The default endpoint for the GoCardless sandbox API (`https://api-sandbox.gocardless.com`). ``` -------------------------------- ### Get a single refund by ID Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/refund.md Use this method to retrieve the details of a specific refund using its unique identifier. Ensure you have the refund's ID. ```go refund, err := client.Refunds.Get(ctx, "RF123") if err != nil { return err } fmt.Printf("Refund %s: %d %s (status: %s)\n", refund.Id, refund.Amount, refund.Currency, refund.Status) ``` -------------------------------- ### Context Usage for API Calls in Go Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Shows how to create and manage `context.Context` for API operations, including simple contexts, contexts with timeouts, and contexts with cancellation signals. ```go // Simple context ctx := context.TODO() // Context with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // Context with cancellation ctx, cancel := context.WithCancel(context.Background()) // ... call API operations cancel() // Stop operations customer, err := client.Customers.Create(ctx, params) ``` -------------------------------- ### List Resources Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/core-services.md Fetches a single page of resources with support for filtering, pagination, and sorting. This method performs a GET request and uses cursor-based pagination. ```APIDOC ## List Resources ### Description Fetches a single page of resources. This method performs a GET request and uses cursor-based pagination. ### Method GET ### Endpoint (Resource-specific endpoint, e.g., /customers) ### Parameters #### Query Parameters - **After** (string) - Optional - Cursor for forward pagination (from previous response's `Meta.Cursors.After`) - **Before** (string) - Optional - Cursor for backward pagination (from previous response's `Meta.Cursors.Before`) - **Limit** (int) - Optional - Number of results per page (default varies, typically 25-100) - **SortField** (string) - Optional - Field to sort by (resource-specific) - **SortDirection** (string) - Optional - "asc" or "desc" - **[Resource-specific filters]** (type) - Optional - Varies by service (e.g., `Customer`, `Status`, `CreatedAt`). ### Request Example ```go listParams := gocardless.CustomerListParams{ Limit: 50, } result, err := client.Customers.List(ctx, listParams) if err != nil { return err } fmt.Printf("Returned %d customers\n", len(result.Customers)) fmt.Printf("Next cursor: %s\n", result.Meta.Cursors.After) ``` ### Response #### Success Response (200) - **Resources** ([]Resource) - Array of the requested resource type - **Meta** (ListResultMeta) - Pagination metadata - **Linked** (ListResultLinked) - Optional: related resources included via ?include parameter ```json { "Resources": [ // ... resource objects ... ], "Meta": { "Cursors": { "After": "cursor_after_123", "Before": "cursor_before_456" }, "Limit": 50 }, "Linked": {} } ``` ``` -------------------------------- ### Create Yearly Subscription with Specific Month Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/api-reference/subscription.md Set up a yearly subscription that renews on a specific date and month. The StartDate and Month parameters are used to define the renewal date. ```go // Renews every March 15th subscription, err := client.Subscriptions.Create(ctx, gocardless.SubscriptionCreateParams{ Amount: 199 * 100, // £199.00 annually Currency: "GBP", Interval: 1, IntervalUnit: "yearly", StartDate: "2024-03-15", Month: "March", Name: "Annual Plan", Links: gocardless.SubscriptionCreateParamsLinks{ Mandate: mandate.Id, }, }) ``` -------------------------------- ### Standard CRUD Services Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/MANIFEST.md Provides methods for standard Create, Get, List, All, Update, and Remove operations across various services like Customers and Creditors. ```APIDOC ## Standard CRUD Operations ### Description These methods follow a standard Create, Get, List, All, Update, and Remove pattern for managing resources. ### Services Customers, Creditors, CreditorBankAccounts, CustomerBankAccounts, etc. ### Methods - **Create**: Creates a new resource. - **Get**: Retrieves a specific resource by ID. - **List**: Lists resources with optional filtering parameters. - **All**: Retrieves all resources, potentially returning an iterator. - **Update**: Updates an existing resource by ID. - **Remove**: Deletes a specific resource by ID. ### Example Usage (Go) ```go // Create a customer customer, err := client.Customers.Create(ctx, params) // Get a customer by ID customer, err := client.Customers.Get(ctx, id) // List customers with parameters result, err := client.Customers.List(ctx, params) // Get an iterator for all customers iterator := client.Customers.All(ctx, params) // Update a customer by ID customer, err := client.Customers.Update(ctx, id, params) // Remove a customer by ID customer, err := client.Customers.Remove(ctx, id, params) ``` ``` -------------------------------- ### Configure Client with Sandbox Endpoint Source: https://github.com/gocardless/gocardless-pro-go/blob/master/_autodocs/configuration.md Use `WithEndpoint` with `gocardless.SandboxEndpoint` to direct API requests to the sandbox environment. This is useful for testing. ```go config, err := gocardless.NewConfig( token, gocardless.WithEndpoint(gocardless.SandboxEndpoint), ) client, err := gocardless.New(config) ```