Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PlaidService.php 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 $client_id;
  15. protected ?string $client_secret;
  16. protected ?string $environment;
  17. protected ?string $webhook_url;
  18. protected ?string $base_url;
  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->client_id = $this->config->get('plaid.client_id');
  41. $this->client_secret = $this->config->get('plaid.client_secret');
  42. $this->environment = $this->config->get('plaid.environment', 'sandbox');
  43. $this->webhook_url = $this->config->get('plaid.webhook_url');
  44. $this->setBaseUrl($this->environment);
  45. }
  46. public function setClientCredentials(?string $client_id, ?string $client_secret): self
  47. {
  48. $this->client_id = $client_id ?? $this->client_id;
  49. $this->client_secret = $client_secret ?? $this->client_secret;
  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->base_url = 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->base_url;
  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->base_url);
  80. if ($method === 'post') {
  81. $request = $request->withHeaders([
  82. 'PLAID-CLIENT-ID' => $this->client_id,
  83. 'PLAID-SECRET' => $this->client_secret,
  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): 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 $client_name, string $language, array $country_codes, array $user, array $products): object
  143. {
  144. $data = [
  145. 'client_name' => $client_name,
  146. 'language' => $language,
  147. 'country_codes' => $country_codes,
  148. 'user' => (object) $user,
  149. ];
  150. if ($products) {
  151. $data['products'] = $products;
  152. }
  153. if (! empty($this->webhook_url)) {
  154. $data['webhook'] = $this->webhook_url;
  155. }
  156. return $this->sendRequest('link/token/create', $data);
  157. }
  158. public function exchangePublicToken(string $public_token): object
  159. {
  160. $data = compact('public_token');
  161. return $this->sendRequest('item/public_token/exchange', $data);
  162. }
  163. public function getAccounts(string $accessToken, array $options = []): object
  164. {
  165. $data = [
  166. 'access_token' => $accessToken,
  167. 'options' => (object) $options,
  168. ];
  169. return $this->sendRequest('accounts/get', $data);
  170. }
  171. public function getInstitution(string $institution_id, string $country): object
  172. {
  173. $options = [
  174. 'include_optional_metadata' => true,
  175. ];
  176. $plaidCountry = $this->getCountry($country);
  177. return $this->getInstitutionById($institution_id, [$plaidCountry], $options);
  178. }
  179. public function getInstitutionById(string $institution_id, array $country_codes, array $options = []): object
  180. {
  181. $data = [
  182. 'institution_id' => $institution_id,
  183. 'country_codes' => $country_codes,
  184. 'options' => (object) $options,
  185. ];
  186. return $this->sendRequest('institutions/get_by_id', $data);
  187. }
  188. public function getTransactions(string $access_token, string $start_date, string $end_date, array $options = []): object
  189. {
  190. $data = [
  191. 'access_token' => $access_token,
  192. 'start_date' => $start_date,
  193. 'end_date' => $end_date,
  194. 'options' => (object) $options,
  195. ];
  196. return $this->sendRequest('transactions/get', $data);
  197. }
  198. public function fireSandboxWebhook(string $access_token, string $webhook_code, string $webhook_type): object
  199. {
  200. $data = compact('access_token', 'webhook_code', 'webhook_type');
  201. return $this->sendRequest('sandbox/item/fire_webhook', $data);
  202. }
  203. }