Plaid Go Client Library

repository·master·Indexed 42 days ago

https://github.com/plaid/plaid-go

The official Go client library for the Plaid API, automatically generated from Plaid's OpenAPI schema. It provides support for the latest API endpoints, including Link token creation, public token exchange, TransactionsSync, and real-time balance data via AccountsBalanceGet. The library uses a request model pattern with setter methods for optional parameters and includes a helper function, plaid.ToPlaidError, for structured error handling.

Tokens
3.4K
Snippets
15
Records
16
Agent score
3%

What's inside Plaid

  1. Use dates and datetimes in requests

    master

    The Go client represents API date/datetime strings as time.Time types.

    • For fields with format: date, format your time.Time object using the YYYYMMDD pattern (e.g., 2006-01-02).
    • For fields with format: date-time, provide a full time.Time instance.

    Note: Time zone information is required for request fields that accept datetimes. Failing to include time zone information will result in an error.

    import (
        "time"
    )
    
    // For format: date
    const YYYYMMDD = "2006-01-02"
    myDate := time.Date(2019, time.December, 6, 22, 35, 49, 0, time.UTC).Format(YYYYMMDD)
    // Returns 2019-12-06
    
    // For format: date-time
    myDateTime := time.Date(2019, time.December, 6, 22, 35, 49, 0, time.UTC)
    // Returns 2019-12-06 22:35:49 +0000 UTC
  2. Migrate from pre-August 2021 versions to latest

    master

    If you are using a version of plaid-go released before August 2021, you must update your integration because the library was rewritten to be generated from OpenAPI. The new version introduces a different client initialization pattern, renamed endpoint methods (moving the verb to the end), mandatory context support, and a new request/response model using setter methods for optional parameters.

    // New Client Initialization Pattern
    configuration := plaid.NewConfiguration()
    configuration.AddDefaultHeader("PLAID-CLIENT-ID", os.Getenv("CLIENT_ID"))
    configuration.AddDefaultHeader("PLAID-SECRET", os.Getenv("SECRET"))
    configuration.UseEnvironment(plaid.Sandbox)
    
    client := plaid.NewAPIClient(configuration)
  3. Install the plaid-go client library

    master

    The library uses Go Modules. To install the latest version (or a specific version), add the module to your go.mod file and run the go get command. Note that the module path includes the major version (e.g., /v47).

    $ go get github.com/plaid/plaid-go/v47@{VERSION}
  4. Initialize the Plaid client (New API)

    master

    In the current version of the library, you initialize the client by creating a plaid.Configuration object, setting the required headers for PLAID-CLIENT-ID and PLAID-SECRET, specifying the environment (e.g., plaid.Sandbox), and then passing that configuration to plaid.NewAPIClient.

    configuration := plaid.NewConfiguration()
    configuration.AddDefaultHeader("PLAID-CLIENT-ID", os.Getenv("CLIENT_ID"))
    configuration.AddDefaultHeader("PLAID-SECRET", os.Getenv("SECRET"))
    configuration.UseEnvironment(plaid.Sandbox)
    
    client := plaid.NewAPIClient(configuration)
  5. Initialize the Plaid API client

    master

    To interact with the Plaid API, you must create a plaid.Configuration object, set your credentials using AddDefaultHeader, specify the environment (e.g., plaid.Production, plaid.Sandbox), and then create a client using plaid.NewAPIClient.

    configuration := plaid.NewConfiguration()
    configuration.AddDefaultHeader("PLAID-CLIENT-ID", {VALUE})
    configuration.AddDefaultHeader("PLAID-SECRET", {VALUE})
    configuration.UseEnvironment(plaid.Production)
    client := plaid.NewAPIClient(configuration)
  6. Use optional parameters in requests (New API)

    master

    Instead of passing all parameters in a single struct, the new API uses a builder-like pattern with setter methods. Create the request object using the plaid.New[RequestName] constructor for required fields, then use methods like .SetWebhook(), .SetLinkCustomizationName(), or .SetRedirectUri() to add optional parameters.

    user := plaid.LinkTokenCreateRequestUser{
      ClientUserId: "user-id-from-your-db",
    }
    request := plaid.NewLinkTokenCreateRequest(
      "Plaid Test",
      "en",
      []plaid.CountryCode{plaid.COUNTRYCODE_US},
    )
    request.SetUser(user)
    request.SetProducts([]plaid.Products{plaid.PRODUCTS_AUTH})
    
    // Optional parameters
    request.SetWebhook("https://webhook-uri.com")
    request.SetLinkCustomizationName("default")
    request.SetRedirectUri("https://domainname.com/oauth-page.html")
    
    resp, _, err := testClient.PlaidApi.LinkTokenCreate(ctx).LinkTokenCreateRequest(*request).Execute()
    linkToken := resp.GetLinkToken()
  7. Create a Link Token to initialize Plaid Link

    master

    Use LinkTokenCreate to generate a token required to initialize the Plaid Link UI. You must provide a LinkTokenCreateRequest specifying products, country codes, and optional user/webhook configurations.

    user := plaid.LinkTokenCreateRequestUser{
        ClientUserId: "USER_ID_FROM_YOUR_DB",
    }
    request := plaid.NewLinkTokenCreateRequest(
      "Plaid Test",
      "en",
      []plaid.CountryCode{plaid.COUNTRYCODE_US},
    )
    request.SetUser(user)
    request.SetProducts([]plaid.Products{plaid.PRODUCTS_AUTH})
    request.SetLinkCustomizationName("default")
    request.SetWebhook("https://webhook-uri.com")
    request.SetRedirectUri("https://domainname.com/oauth-page.html")
    request.SetAccountFilters(plaid.LinkTokenAccountFilters{
      Depository: &plaid.DepositoryFilter{
        AccountSubtypes: []plaid.AccountSubtype{plaid.ACCOUNTSUBTYPE_CHECKING, plaid.ACCOUNTSUBTYPE_SAVINGS},
      },
    })
    resp, _, err := testClient.PlaidApi.LinkTokenCreate(ctx).LinkTokenCreateRequest(*request).Execute()
    
    linkToken := resp.GetLinkToken()
  8. Retrieve transactions using TransactionsSync

    master

    The preferred method for retrieving transaction data is using the TransactionsSync endpoint, which provides a delta-based synchronization approach.

    request := plaid.NewTransactionsSyncRequest(
      accessToken
    )
    
    transactionsResp, _, err := testClient.PlaidApi.TransactionsSync(ctx).TransactionsSyncRequest(*request).Execute()
  9. Exchange a public token for an access token

    master

    After a user completes the Plaid Link flow, exchange the resulting public_token for a permanent access_token using ItemPublicTokenExchange.

    exchangePublicTokenReq := plaid.NewItemPublicTokenExchangeRequest(sandboxPublicTokenResp.GetPublicToken())
    exchangePublicTokenResp, _, err := client.PlaidApi.ItemPublicTokenExchange(ctx).ItemPublicTokenExchangeRequest(
      *exchangePublicTokenReq,
    ).Execute()
    accessToken := exchangePublicTokenResp.GetAccessToken()
  10. Retrieve real-time balance data

    master

    Use AccountsBalanceGet to retrieve current balance information for an account associated with an access_token.

    balancesGetReq := plaid.NewAccountsBalanceGetRequest(accessToken)
    
    balancesGetResp, _, err = testClient.PlaidApi.AccountsBalanceGet(ctx).AccountsBalanceGetRequest(
      *balancesGetReq,
    ).Execute()
  11. Handle Plaid API errors

    master

    When an endpoint returns an error, use plaid.ToPlaidError(err) to extract the specific Plaid error object. This allows you to access structured error information like ErrorMessage.

    response, httpResponse, err := client.PlaidApi.Endpoint(...)
    plaidErr, err := plaid.ToPlaidError(err)
    fmt.Println(plaidErr.ErrorMessage)