Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

PlaidService.php 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Company;
  4. use GuzzleHttp\Psr7\Message;
  5. use Illuminate\Contracts\Config\Repository as Config;
  6. use Illuminate\Http\Client\Factory as HttpClient;
  7. use Illuminate\Http\Client\RequestException;
  8. use Illuminate\Http\Client\Response;
  9. use Illuminate\Support\Facades\Log;
  10. use RuntimeException;
  11. class PlaidService
  12. {
  13. public const API_VERSION = '2020-09-14';
  14. protected ?string $clientId;
  15. protected ?string $clientSecret;
  16. protected ?string $environment;
  17. protected ?string $webhookUrl;
  18. protected ?string $baseUrl;
  19. protected HttpClient $client;
  20. protected Config $config;
  21. protected array $plaidSupportedLanguages = [
  22. 'da', 'nl', 'en',
  23. 'et', 'fr', 'de',
  24. 'it', 'lv', 'lt',
  25. 'no', 'pl', 'pt',
  26. 'ro', 'es', 'sv',
  27. ];
  28. protected array $plaidSupportedCountries = [
  29. 'US', 'GB', 'ES',
  30. 'NL', 'FR', 'IE',
  31. 'CA', 'DE', 'IT',
  32. 'PL', 'DK', 'NO',
  33. 'SE', 'EE', 'LT',
  34. 'LV', 'PT', 'BE',
  35. ];
  36. public function __construct(HttpClient $client, Config $config)
  37. {
  38. $this->client = $client;
  39. $this->config = $config;
  40. $this->clientId = $this->config->get('plaid.client_id');
  41. $this->clientSecret = $this->config->get('plaid.client_secret');
  42. $this->environment = $this->config->get('plaid.environment', 'sandbox');
  43. $this->webhookUrl = $this->config->get('plaid.webhook_url');
  44. $this->setBaseUrl($this->environment);
  45. }
  46. public function setClientCredentials(?string $clientId, ?string $clientSecret): self
  47. {
  48. $this->clientId = $clientId ?? $this->clientId;
  49. $this->clientSecret = $clientSecret ?? $this->clientSecret;
  50. return $this;
  51. }
  52. public function setEnvironment(?string $environment): self
  53. {
  54. $this->environment = $environment ?? $this->environment;
  55. $this->setBaseUrl($this->environment);
  56. return $this;
  57. }
  58. public function setBaseUrl(?string $environment): void
  59. {
  60. $this->baseUrl = match ($environment) {
  61. 'development' => 'https://development.plaid.com',
  62. 'production' => 'https://production.plaid.com',
  63. default => 'https://sandbox.plaid.com', // Default to sandbox, including if environment is null
  64. };
  65. }
  66. public function getBaseUrl(): string
  67. {
  68. return $this->baseUrl;
  69. }
  70. public function getEnvironment(): string
  71. {
  72. return $this->environment;
  73. }
  74. public function buildRequest(string $method, string $endpoint, array $data = []): Response
  75. {
  76. $request = $this->client->withHeaders([
  77. 'Plaid-Version' => self::API_VERSION,
  78. 'Content-Type' => 'application/json',
  79. ])->baseUrl($this->baseUrl);
  80. if ($method === 'post') {
  81. $request = $request->withHeaders([
  82. 'PLAID-CLIENT-ID' => $this->clientId,
  83. 'PLAID-SECRET' => $this->clientSecret,
  84. ]);
  85. }
  86. return $request->{$method}($endpoint, $data);
  87. }
  88. public function sendRequest(string $endpoint, array $data = []): object
  89. {
  90. try {
  91. $response = $this->buildRequest('post', $endpoint, $data)->throw()->object();
  92. if ($response === null) {
  93. throw new RuntimeException('Plaid API returned null response.');
  94. }
  95. return $response;
  96. } catch (RequestException $e) {
  97. $statusCode = $e->response->status();
  98. $message = "Plaid API request returned status code {$statusCode}";
  99. $summary = Message::bodySummary($e->response->toPsrResponse(), 1000);
  100. if ($summary !== null) {
  101. $message .= ":\n{$summary}\n";
  102. }
  103. Log::error($message);
  104. throw new RuntimeException('An error occurred while communicating with the Plaid API.');
  105. }
  106. }
  107. public function createPlaidUser(Company $company): array
  108. {
  109. return array_filter([
  110. 'client_user_id' => (string) $company->owner->id,
  111. 'legal_name' => $company->owner->name,
  112. 'phone_number' => $company->profile->phone_number,
  113. 'email_address' => $company->owner->email,
  114. ], static fn ($value): bool => $value !== null);
  115. }
  116. public function getLanguage(string $language): string
  117. {
  118. if (in_array($language, $this->plaidSupportedLanguages, true)) {
  119. return $language;
  120. }
  121. return 'en';
  122. }
  123. public function getCountry(?string $country = null): string
  124. {
  125. if (in_array($country, $this->plaidSupportedCountries, true)) {
  126. return $country;
  127. }
  128. return 'US';
  129. }
  130. public function createToken(string $language, string $country, array $user, array $products = []): object
  131. {
  132. $plaidLanguage = $this->getLanguage($language);
  133. $plaidCountry = $this->getCountry($country);
  134. return $this->createLinkToken(
  135. 'ERPSAAS',
  136. $plaidLanguage,
  137. [$plaidCountry],
  138. $user,
  139. $products,
  140. );
  141. }
  142. public function createLinkToken(string $clientName, string $language, array $countryCodes, array $user, array $products): object
  143. {
  144. $data = [
  145. 'client_name' => $clientName,
  146. 'language' => $language,
  147. 'country_codes' => $countryCodes,
  148. 'user' => (object) $user,
  149. ];
  150. if ($products) {
  151. $data['products'] = $products;
  152. }
  153. if (! empty($this->webhookUrl)) {
  154. $data['webhook'] = $this->webhookUrl;
  155. }
  156. return $this->sendRequest('link/token/create', $data);
  157. }
  158. public function exchangePublicToken(string $publicToken): object
  159. {
  160. $data = [
  161. 'public_token' => $publicToken,
  162. ];
  163. return $this->sendRequest('item/public_token/exchange', $data);
  164. }
  165. public function getAccounts(string $accessToken, array $options = []): object
  166. {
  167. $data = [
  168. 'access_token' => $accessToken,
  169. 'options' => (object) $options,
  170. ];
  171. return $this->sendRequest('accounts/get', $data);
  172. }
  173. public function getInstitution(string $institutionId, string $country): object
  174. {
  175. $options = [
  176. 'include_optional_metadata' => true,
  177. ];
  178. $plaidCountry = $this->getCountry($country);
  179. return $this->getInstitutionById($institutionId, [$plaidCountry], $options);
  180. }
  181. public function getInstitutionById(string $institutionId, array $countryCodes, array $options = []): object
  182. {
  183. $data = [
  184. 'institution_id' => $institutionId,
  185. 'country_codes' => $countryCodes,
  186. 'options' => (object) $options,
  187. ];
  188. return $this->sendRequest('institutions/get_by_id', $data);
  189. }
  190. public function getTransactions(string $accessToken, string $startDate, string $endDate, array $options = []): object
  191. {
  192. $data = [
  193. 'access_token' => $accessToken,
  194. 'start_date' => $startDate,
  195. 'end_date' => $endDate,
  196. 'options' => (object) $options,
  197. ];
  198. return $this->sendRequest('transactions/get', $data);
  199. }
  200. public function fireSandboxWebhook(string $accessToken, string $webhookCode, string $webhookType): object
  201. {
  202. $data = [
  203. 'access_token' => $accessToken,
  204. 'webhook_code' => $webhookCode,
  205. 'webhook_type' => $webhookType,
  206. ];
  207. return $this->sendRequest('sandbox/item/fire_webhook', $data);
  208. }
  209. public function refreshTransactions(string $accessToken): object
  210. {
  211. $data = [
  212. 'access_token' => $accessToken,
  213. ];
  214. return $this->sendRequest('transactions/refresh', $data);
  215. }
  216. public function removeItem(string $accessToken): object
  217. {
  218. $data = [
  219. 'access_token' => $accessToken,
  220. ];
  221. return $this->sendRequest('item/remove', $data);
  222. }
  223. }