TomorrowIdeas / plaid-sdk-php

PHP bindings for the Plaid API
MIT License
111 stars 42 forks source link

Cursor not associated with access_token #70

Open ahmad13544 opened 1 year ago

ahmad13544 commented 1 year ago

Facing an issue that it is returning following exception message. "cursor not associated with access_token".

levizoesch commented 9 months ago

You are trying to access a cursor ID that isnt available to the access_token that you are requesting transactions for.

You have

Access Token A Access Token B

You are trying to access Token A with a cursor ID that is for Token B.

On each iteration you store the cursor ID to your database and call that ID on each forward request. That will pickup where you last left off on the sync transactions process.


public function syncBankTransactions($id, $nextCursor = null): string
    {
        $plaid = new Plaid($this->PLAID_CLIENT_ID, $this->PLAID_SECRET, $this->PLAID_ENV);
        $plaidAct = PlaidAccount::where('id', $id)->first();
        $cursor = $nextCursor ?? $plaidAct->last_cursor;

        $transactions = $plaid->transactions->sync($plaidAct->plaid_access_token, $cursor, 500);

        // Are there additional transactions?
        $hasMore = $transactions->has_more;

        // Set new cursor as we have initiated the past cursor at this point.
        $nextCursor = $transactions->next_cursor;

        PlaidAccount::where('id', $id)->update([
            'last_cursor' => $nextCursor
        ]);

        foreach ($transactions->added as $transaction) {
            if (is_bool($transaction)) {
                continue;
            }
            if (!Transactions::where('trx_id', $transaction->transaction_id)->first()) {
                $encoded = json_encode($transaction, JSON_THROW_ON_ERROR);
                NewPlaidTransactionCreatedJob::dispatch($encoded, $plaidAct, $plaidAct->bank_id);
            }
        }

        if ($hasMore) {
            $this->syncBankTransactions($id, $nextCursor);
        }

        PlaidAccount::where('id', $plaidAct->id)->update([
            'available_balance' => $balanceDetails['balance']['available'],
            'balance' => $balanceDetails['balance']['current'],
            'syncd' => true,
            'last_update' => new DateTime('now')
        ]);

        return 'complete';
    }

Here is an example of how you would handle the syncing of bank transactions.