B3CprService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <?php
  2. namespace Services;
  3. class B3CprService
  4. {
  5. public function getAccessToken(): string
  6. {
  7. $b3Url = $_ENV['B3_URL'] ?? null;
  8. $grantType = $_ENV['GRANT_TYPE'] ?? 'client_credentials';
  9. $certPass = $_ENV['CERT_PASS'] ?? null;
  10. if (!$b3Url || !$grantType) {
  11. throw new \RuntimeException('Missing required env vars: B3_URL, GRANT_TYPE');
  12. }
  13. $certPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . '319245319-320109623_PROD.cer';
  14. $keyPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . '319245319-320109623_PROD.key';
  15. if (!file_exists($certPath) || !file_exists($keyPath)) {
  16. throw new \RuntimeException('Client certificate or key not found');
  17. }
  18. $postFields = 'grant_type=' . ($grantType);
  19. $ch = curl_init($b3Url);
  20. curl_setopt($ch, CURLOPT_POST, true);
  21. $headers = [
  22. 'Content-Type: application/x-www-form-urlencoded',
  23. 'Accept: application/json',
  24. ];
  25. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  26. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  27. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  28. curl_setopt($ch, CURLOPT_SSLCERT, $certPath);
  29. curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
  30. curl_setopt($ch, CURLOPT_SSLKEY, $keyPath);
  31. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  32. if ($certPass) {
  33. curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $certPass);
  34. }
  35. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  36. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  37. $responseBody = curl_exec($ch);
  38. $curlErrNo = curl_errno($ch);
  39. $curlErr = curl_error($ch);
  40. $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
  41. curl_close($ch);
  42. if ($curlErrNo !== 0) {
  43. throw new \RuntimeException('cURL error: ' . $curlErr);
  44. }
  45. $decoded = json_decode((string)$responseBody, true);
  46. if (!is_array($decoded)) {
  47. throw new \RuntimeException('Invalid token response (non-JSON), HTTP ' . $httpCode);
  48. }
  49. $token = $decoded['access_token'] ?? null;
  50. if (!is_string($token) || $token === '') {
  51. throw new \RuntimeException('access_token not present in token response');
  52. }
  53. return $token;
  54. }
  55. public function mapToB3(array $cpr): array
  56. {
  57. $instrument = [
  58. 'cprTypeCode' => $cpr['cpr_type_code'] ?? null,
  59. 'otcRegisterAccountCode' => $cpr['cpr_otc_register_account_code'] ?? null,
  60. 'otcCustodianAccountCode' => $cpr['cpr_otc_custodian_account_code'] ?? null,
  61. 'electronicEmissionIndicator' => $this->mapIndicator($cpr['cpr_electronic_emission_indicator'] ?? null),
  62. 'issueDate' => $this->convertDate($cpr['cpr_issue_date'] ?? null),
  63. 'maturityDate' => $this->convertDate($cpr['cpr_maturity_date'] ?? null),
  64. 'issueQuantity' => $cpr['cpr_issue_quantity'] ?? null,
  65. 'issueValue' => $cpr['cpr_issue_value'] ?? null,
  66. 'issueFinancialValue' => $cpr['cpr_issue_financial_value'] ?? null,
  67. 'profitabilityStartDate' => $this->convertDate($cpr['cpr_profitability_start_date'] ?? null),
  68. 'automaticExpirationIndicator' => $this->mapIndicator($cpr['cpr_automatic_expiration_indicator'] ?? null),
  69. 'collaterals' => [[
  70. 'collateralTypeCode' => $cpr['cpr_collateral_type_code'] ?? null,
  71. 'collateralTypeName' => $cpr['cpr_collateral_type_name'] ?? null,
  72. 'constitutionProcessIndicator' => $this->mapIndicator($cpr['cpr_constitution_process_indicator'] ?? null),
  73. 'otcBondsmanAccountCode' => $cpr['cpr_otc_bondsman_account_code'] ?? null,
  74. ]],
  75. 'products' => [[
  76. 'cprProductName' => $cpr['cpr_product_name'] ?? null,
  77. 'cprProductClassName' => $cpr['cpr_product_class_name'] ?? null,
  78. 'cprProductHarvest' => $cpr['cpr_product_harvest'] ?? null,
  79. 'cprProductDescription' => $cpr['cpr_product_description'] ?? null,
  80. 'cprProductQuantity' => $cpr['cpr_product_quantity'] ?? null,
  81. 'measureUnitName' => $cpr['cpr_measure_unit_name'] ?? null,
  82. 'packagingWayName' => $cpr['cpr_packaging_way_name'] ?? null,
  83. 'cprProductStatusCode' => $cpr['cpr_product_status_code'] ?? null,
  84. 'productionTypeCode' => $cpr['cpr_production_type_code'] ?? null,
  85. ]],
  86. 'deliveryPlace' => [
  87. 'documentDeadlineDaysNumber' => $cpr['cpr_document_deadline_days_number'] ?? null,
  88. 'placeName' => $cpr['cpr_place_name'] ?? null,
  89. 'stateAcronym' => $cpr['cpr_deliveryPlace_state_acronym'] ?? null,
  90. 'cityName' => $cpr['cpr_deliveryPlace_city_name'] ?? null,
  91. ],
  92. 'issuers' => [[
  93. 'cprIssuerName' => $cpr['cpr_issuer_name'] ?? null,
  94. 'documentNumber' => $cpr['cpr_issuers_document_number'] ?? null,
  95. 'personTypeAcronym' => $cpr['cpr_issuers_person_type_acronym'] ?? null,
  96. 'issuerLegalNatureCode' => $cpr['cpr_issuer_legal_nature_code'] ?? null,
  97. 'stateAcronym' => $cpr['cpr_issuers_state_acronym'] ?? null,
  98. 'cityName' => $cpr['cpr_issuers_city_name'] ?? null,
  99. ]],
  100. 'scr' => [
  101. 'scrTypeCode' => $cpr['cpr_scr_type_code'] ?? null,
  102. 'finalityCode' => $cpr['cpr_finality_code'] ?? null,
  103. 'contractCode' => $cpr['cpr_contract_code'] ?? null,
  104. ],
  105. 'creditor' => [
  106. 'creditorName' => $cpr['cpr_creditor_name'] ?? null,
  107. 'documentNumber' => $cpr['cpr_creditor_document_number'] ?? null,
  108. ],
  109. 'productionPlaces' => [[
  110. 'productionPlaceName' => $cpr['cpr_production_place_name'] ?? null,
  111. 'propertyRegistrationNumber' => $cpr['cpr_property_registration_number'] ?? null,
  112. 'notaryName' => $cpr['cpr_notary_name'] ?? null,
  113. 'totalProductionAreaInHectaresNumber' => $cpr['cpr_total_production_area_in_hectares_number'] ?? null,
  114. 'totalAreaInHectaresNumber' => $cpr['cpr_total_area_in_hectares_number'] ?? null,
  115. 'carCode' => $cpr['cpr_car_code'] ?? null,
  116. 'latitudeCode' => $cpr['cpr_latitude_code'] ?? null,
  117. 'longitudeCode' => $cpr['cpr_longitude_code'] ?? null,
  118. 'zipCode' => $cpr['cpr_zip_code'] ?? null,
  119. ]],
  120. ];
  121. return ['data' => ['instrument' => $instrument]];
  122. }
  123. private function convertDate(?string $date): ?string
  124. {
  125. if (!is_string($date) || trim($date) === '') {
  126. return null;
  127. }
  128. $t = trim($date);
  129. if (mb_strtoupper($t, 'UTF-8') === 'NA') {
  130. return null;
  131. }
  132. $dt = \DateTime::createFromFormat('Y-m-d', $t);
  133. if ($dt instanceof \DateTime) {
  134. return $dt->format('d/m/Y');
  135. }
  136. $alt = \DateTime::createFromFormat('d/m/Y', $t);
  137. if ($alt instanceof \DateTime) {
  138. return $t;
  139. }
  140. return $t;
  141. }
  142. private function mapIndicator($value): ?string
  143. {
  144. if (!is_string($value)) {
  145. return null;
  146. }
  147. $v = mb_strtoupper(trim($value), 'UTF-8');
  148. if ($v === 'SIM' || $v === 'S') {
  149. return 'S';
  150. }
  151. if ($v === 'N' || $v === 'NAO' || $v === 'NÃO') {
  152. return 'N';
  153. }
  154. if ($v === 'NA') {
  155. return null;
  156. }
  157. return $value;
  158. }
  159. public function sanitize(array $payload): array
  160. {
  161. return $this->removeNulls($payload);
  162. }
  163. private function removeNulls($value)
  164. {
  165. if (is_array($value)) {
  166. $isAssoc = $this->isAssoc($value);
  167. $result = [];
  168. foreach ($value as $k => $v) {
  169. if (is_string($v) && mb_strtoupper(trim($v), 'UTF-8') === 'NA') {
  170. $v = null;
  171. }
  172. $v = $this->removeNulls($v);
  173. if (is_array($v) && count($v) === 0) {
  174. continue;
  175. }
  176. $result[$k] = $v;
  177. }
  178. if (!$isAssoc) {
  179. $result = array_values($result);
  180. }
  181. return $result;
  182. }
  183. if (is_string($value) && mb_strtoupper(trim($value), 'UTF-8') === 'NA') {
  184. return null;
  185. }
  186. return $value;
  187. }
  188. private function isAssoc(array $arr): bool
  189. {
  190. return array_keys($arr) !== range(0, count($arr) - 1);
  191. }
  192. public function postCpr(string $accessToken, array $payload): array
  193. {
  194. $url = $_ENV['B3_URL_CPR'] ?? null;
  195. if (!$url) {
  196. throw new \RuntimeException('B3_URL_CPR not configured');
  197. }
  198. $json = json_encode($this->sanitize($payload), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  199. if ($json === false) {
  200. throw new \RuntimeException('Failed to encode payload');
  201. }
  202. $certPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . '319245319-320109623_PROD.cer';
  203. $keyPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . '319245319-320109623_PROD.key';
  204. $certPass = $_ENV['CERT_PASS'] ?? null;
  205. if (!file_exists($certPath) || !file_exists($keyPath)) {
  206. throw new \RuntimeException('Client certificate or key not found');
  207. }
  208. $ch = curl_init($url);
  209. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  210. $headers = [
  211. 'Accept: application/json',
  212. 'Content-Type: application/json',
  213. 'Authorization: Bearer ' . $accessToken,
  214. ];
  215. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  216. curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
  217. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  218. curl_setopt($ch, CURLOPT_SSLCERT, $certPath);
  219. curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
  220. curl_setopt($ch, CURLOPT_SSLKEY, $keyPath);
  221. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  222. if ($certPass) {
  223. curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $certPass);
  224. }
  225. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  226. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  227. $responseBody = curl_exec($ch);
  228. $curlErrNo = curl_errno($ch);
  229. $curlErr = curl_error($ch);
  230. $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
  231. curl_close($ch);
  232. if ($curlErrNo !== 0) {
  233. return ['error' => $curlErr, 'status' => 0];
  234. }
  235. $decoded = json_decode((string)$responseBody, true);
  236. if ($decoded === null) {
  237. return ['raw' => $responseBody, 'status' => $httpCode ?: 502];
  238. }
  239. return ['json' => $decoded, 'status' => $httpCode ?: 200];
  240. }
  241. }