Search code examples
ruby-on-railsrubyplaid

plaid ruby gem: exchange token throwing 'provided public token is in an invalid format' error


I am using Link in React to link to Items and then passing the public_token to my rails server where I'm attempting to exchange the public token for a access token. Link is successfully returning the public token to me which looks like public-sandbox-6df92f82-3260-4cb4-8489-65e6ac955e7a and I am passing that to my rails server where I use the plaid-ruby gem to attempt to exchange tokens. However, I'm getting an INVALID_INPUT error.

plaid-ruby code (params["plaidToken"] == public-sandbox-6df92f82-3260-4cb4-8489-65e6ac955e7a):

  def set_plaid_token
    client = Plaid::Client.new(env: :sandbox,
                               client_id: '*******',
                               secret: '*******',
                               public_key: params["plaidToken"])

    exchange_token_response = client.item.public_token.exchange('[Plaid Link public_token]')
    access_token = exchange_token_response.access_token

    #TODO users can add same bank twice.
    user = UserToken.find_by(token: params["userToken"]).user
    token = UserToken.new(user_id: user.id, token: access_token, token_type: "plaid_token")
    token.save
  end

The error message below just tells me to format the token like it is already formatted so I'm not sure what else could be wrong.

Error Message:

Plaid::InvalidInputError (
Error Type      : INVALID_INPUT
Error Code      : INVALID_PUBLIC_TOKEN
Error Message   : provided public token is in an invalid format. expected format: public-<environment>-<identifier>
Display Message : 
Request ID      : vaAqIgjQNZ2Zj07
):

Solution

  • In public_key you must use your key which is listed in the Plaid account. https://dashboard.plaid.com/account/keys

    def set_plaid_token
      public_token = params[:plaid_token]
    
      client = Plaid::Client.new(env: :sandbox,
                           client_id: ENV['plaid_client_id'],
                              secret: ENV['plaid_secret'],
                          public_key: ENV['plaid_public_key'])
    
      exchange_token_response = client.item.public_token.exchange(public_token)
      access_token = exchange_token_response.access_token
      ...
    end
    

    Link:

    let linkHandler = Plaid.create({
        clientName: 'Name',
        env: 'sandbox',
        key: 'your-public-key-from-dashboard',
        product: ['auth'],
        onSuccess: function(public_token, metadata) {
          $.post('/plaid/set_plaid_token', {
              plaid_token: public_token
          });
          console.log('Pub tok = ' + public_token);
          console.log('Account = ' + metadata.account_id);
        }
    });
    
    document.getElementById('linkButton').onclick = function() {
       linkHandler.open();
    };