您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CreateConnectedAccount.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PlaidSuccess;
  4. use App\Models\Banking\Institution;
  5. use App\Models\Company;
  6. use App\Services\PlaidService;
  7. use Illuminate\Support\Facades\DB;
  8. class CreateConnectedAccount
  9. {
  10. protected PlaidService $plaid;
  11. /**
  12. * Create the event listener.
  13. */
  14. public function __construct(PlaidService $plaid)
  15. {
  16. $this->plaid = $plaid;
  17. }
  18. /**
  19. * Handle the event.
  20. */
  21. public function handle(PlaidSuccess $event): void
  22. {
  23. DB::transaction(function () use ($event) {
  24. $this->processPlaidSuccess($event);
  25. });
  26. }
  27. public function processPlaidSuccess(PlaidSuccess $event): void
  28. {
  29. $accessToken = $event->accessToken;
  30. $company = $event->company;
  31. $authResponse = $this->plaid->getAccounts($accessToken);
  32. $institutionResponse = $this->plaid->getInstitution($authResponse->item->institution_id, $company->profile->country);
  33. $this->processInstitution($authResponse, $institutionResponse, $company, $accessToken);
  34. }
  35. public function processInstitution($authResponse, $institutionResponse, Company $company, $accessToken): void
  36. {
  37. $institution = Institution::updateOrCreate([
  38. 'external_institution_id' => $authResponse->item->institution_id ?? null,
  39. ], [
  40. 'name' => $institutionResponse->institution->name ?? null,
  41. 'logo' => $institutionResponse->institution->logo ?? null,
  42. 'website' => $institutionResponse->institution->url ?? null,
  43. ]);
  44. foreach ($authResponse->accounts as $plaidAccount) {
  45. $this->processConnectedBankAccount($plaidAccount, $company, $institution, $authResponse, $accessToken);
  46. }
  47. }
  48. public function processConnectedBankAccount($plaidAccount, Company $company, Institution $institution, $authResponse, $accessToken): void
  49. {
  50. $identifierHash = md5($institution->external_institution_id . $plaidAccount->name . $plaidAccount->mask);
  51. $company->connectedBankAccounts()->updateOrCreate([
  52. 'identifier' => $identifierHash,
  53. ], [
  54. 'institution_id' => $institution->id,
  55. 'external_account_id' => $plaidAccount->account_id,
  56. 'access_token' => $accessToken,
  57. 'item_id' => $authResponse->item->item_id,
  58. 'currency_code' => $plaidAccount->balances->iso_currency_code ?? 'USD',
  59. 'current_balance' => $plaidAccount->balances->current ?? 0,
  60. 'name' => $plaidAccount->name,
  61. 'mask' => $plaidAccount->mask,
  62. 'type' => $plaidAccount->type,
  63. 'subtype' => $plaidAccount->subtype,
  64. 'import_transactions' => false,
  65. ]);
  66. }
  67. }