PaymentConfirmController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CommodityModel;
  5. use Models\CprModel;
  6. use Models\PaymentModel;
  7. use Psr\Http\Message\ServerRequestInterface;
  8. use Services\B3CprService;
  9. use Services\TokenCreateService;
  10. class PaymentConfirmController
  11. {
  12. private PaymentModel $paymentModel;
  13. private CprModel $cprModel;
  14. private B3CprService $b3Service;
  15. private CommodityModel $commodityModel;
  16. private TokenCreateService $tokenCreateService;
  17. private \PDO $pdo;
  18. public function __construct()
  19. {
  20. if (!isset($GLOBALS['pdo']) || !$GLOBALS['pdo'] instanceof \PDO) {
  21. throw new \RuntimeException('Global PDO connection not initialized');
  22. }
  23. $this->pdo = $GLOBALS['pdo'];
  24. $this->paymentModel = new PaymentModel();
  25. $this->cprModel = new CprModel();
  26. $this->b3Service = new B3CprService();
  27. $this->commodityModel = new CommodityModel();
  28. $this->tokenCreateService = new TokenCreateService();
  29. }
  30. public function __invoke(ServerRequestInterface $request)
  31. {
  32. $body = json_decode((string)$request->getBody(), true) ?? [];
  33. $paymentId = isset($body['payment_id']) ? (int)$body['payment_id'] : 0;
  34. if ($paymentId <= 0) {
  35. return ResponseLib::sendFail('payment_id inválido', [], 'E_VALIDATE')->withStatus(400);
  36. }
  37. $payment = $this->paymentModel->findById($paymentId);
  38. if (!$payment) {
  39. return ResponseLib::sendFail('Pagamento não encontrado', [], 'E_NOT_FOUND')->withStatus(404);
  40. }
  41. $statusId = (int)($payment['status_id'] ?? 0);
  42. if ($statusId === 0) {
  43. return ResponseLib::sendFail('Pagamento ainda não confirmado', ['payment_id' => $paymentId], 'E_PAYMENT_PENDING')->withStatus(409);
  44. }
  45. if ($statusId !== 1) {
  46. return ResponseLib::sendFail('Pagamento em status inválido', ['status_id' => $statusId], 'E_PAYMENT_STATUS')->withStatus(409);
  47. }
  48. $cpr = $this->cprModel->findByPaymentId($paymentId);
  49. if (!$cpr) {
  50. return ResponseLib::sendFail('Nenhuma CPR vinculada ao pagamento', [], 'E_CPR_NOT_FOUND')->withStatus(404);
  51. }
  52. try {
  53. $payload = $this->b3Service->mapToB3($cpr);
  54. $token = $this->resolveB3Token($request, $body);
  55. $result = $this->b3Service->postCpr($token, $payload);
  56. } catch (\Throwable $e) {
  57. return ResponseLib::sendFail('Falha ao enviar CPR à B3: ' . $e->getMessage(), [], 'E_EXTERNAL')->withStatus(502);
  58. }
  59. if (isset($result['error'])) {
  60. return ResponseLib::sendFail('cURL error during B3 CPR request', ['error' => $result['error']], 'E_EXTERNAL')->withStatus(502);
  61. }
  62. try {
  63. $tokenResult = $this->createTokenFromCpr($cpr);
  64. } catch (\Throwable $e) {
  65. return ResponseLib::sendFail(
  66. 'Falha ao gerar token: ' . $e->getMessage(),
  67. [],
  68. 'E_TOKEN_CREATE'
  69. )->withStatus(500);
  70. }
  71. return ResponseLib::sendOk([
  72. 'message' => 'CPR enviada e token criado com sucesso',
  73. 'payment_id' => $paymentId,
  74. 'b3_response' => $result['json'] ?? ($result['raw'] ?? null),
  75. 'token_id' => $tokenResult['token_id'],
  76. 'token_external_id' => $tokenResult['token_external_id'],
  77. 'tx_hash' => $tokenResult['tx_hash'],
  78. ], 'S_CPR_SENT');
  79. }
  80. private function resolveB3Token(ServerRequestInterface $request, array $body): string
  81. {
  82. $token = $body['b3_access_token'] ?? ($body['access_token'] ?? null);
  83. if (!$token) {
  84. $b3Auth = $request->getHeaderLine('X-B3-Authorization') ?: '';
  85. if (stripos($b3Auth, 'Bearer ') === 0) {
  86. $token = trim(substr($b3Auth, 7));
  87. }
  88. }
  89. if (!$token) {
  90. $token = $request->getHeaderLine('X-B3-Access-Token') ?: null;
  91. }
  92. if (!$token) {
  93. $token = $this->b3Service->getAccessToken();
  94. }
  95. return $token;
  96. }
  97. private function createTokenFromCpr(array $cpr): array
  98. {
  99. $inputs = $this->prepareTokenInputs($cpr);
  100. return $this->tokenCreateService->createToken(
  101. $inputs['token_commodities_amount'],
  102. $inputs['token_commodities_value'],
  103. $inputs['token_uf'],
  104. $inputs['token_city'],
  105. $inputs['token_content'],
  106. $inputs['token_flag'],
  107. $inputs['wallet_id'],
  108. $inputs['chain_id'],
  109. $inputs['commodities_id'],
  110. $inputs['cpr_id'],
  111. $inputs['user_id']
  112. );
  113. }
  114. /**
  115. * @return array{
  116. * token_commodities_amount:int,
  117. * token_commodities_value:int,
  118. * token_uf:string,
  119. * token_city:string,
  120. * token_content:string,
  121. * token_flag:string,
  122. * wallet_id:int,
  123. * chain_id:int,
  124. * commodities_id:int,
  125. * cpr_id:int,
  126. * user_id:int
  127. * }
  128. */
  129. private function prepareTokenInputs(array $cpr): array
  130. {
  131. $cprId = (int)($cpr['cpr_id'] ?? 0);
  132. if ($cprId <= 0) {
  133. throw new \InvalidArgumentException('CPR sem identificador válido.');
  134. }
  135. $userId = (int)($cpr['user_id'] ?? 0);
  136. if ($userId <= 0) {
  137. throw new \InvalidArgumentException('CPR sem usuário associado.');
  138. }
  139. $companyId = (int)($cpr['company_id'] ?? 0);
  140. if ($companyId <= 0) {
  141. throw new \InvalidArgumentException('CPR sem empresa associada.');
  142. }
  143. $wallet = $this->findWalletByCompanyId($companyId);
  144. $commoditiesName = $this->requireStringField($cpr, ['cpr_product_name'], 'cpr_product_name');
  145. $commoditiesId = $this->resolveCommodityId($commoditiesName);
  146. $tokenCommoditiesAmount = $this->requireNumericField(
  147. $cpr,
  148. ['cpr_product_quantity', 'cpr_issue_quantity'],
  149. 'quantidade do produto'
  150. );
  151. $tokenCommoditiesValue = $this->requireNumericField(
  152. $cpr,
  153. ['cpr_issue_value', 'cpr_issue_financial_value'],
  154. 'valor do produto'
  155. );
  156. $tokenUf = $this->requireStringField(
  157. $cpr,
  158. ['cpr_deliveryPlace_state_acronym', 'cpr_issuers_state_acronym'],
  159. 'UF'
  160. );
  161. $tokenCity = $this->requireStringField(
  162. $cpr,
  163. ['cpr_deliveryPlace_city_name', 'cpr_issuers_city_name'],
  164. 'cidade'
  165. );
  166. return [
  167. 'token_commodities_amount' => $tokenCommoditiesAmount,
  168. 'token_commodities_value' => $tokenCommoditiesValue,
  169. 'token_uf' => $tokenUf,
  170. 'token_city' => $tokenCity,
  171. 'token_content' => (string)$cprId,
  172. 'token_flag' => '',
  173. 'wallet_id' => $wallet['wallet_id'],
  174. 'chain_id' => $wallet['chain_id'],
  175. 'commodities_id' => $commoditiesId,
  176. 'cpr_id' => $cprId,
  177. 'user_id' => $userId,
  178. ];
  179. }
  180. private function findWalletByCompanyId(int $companyId): array
  181. {
  182. $stmt = $this->pdo->prepare(
  183. 'SELECT wallet_id, chain_id
  184. FROM "wallet"
  185. WHERE company_id = :company_id
  186. ORDER BY wallet_id ASC
  187. LIMIT 1'
  188. );
  189. $stmt->execute(['company_id' => $companyId]);
  190. $wallet = $stmt->fetch(\PDO::FETCH_ASSOC);
  191. if (!$wallet) {
  192. throw new \RuntimeException('Nenhuma carteira encontrada para a empresa informada.');
  193. }
  194. return [
  195. 'wallet_id' => (int)$wallet['wallet_id'],
  196. 'chain_id' => (int)$wallet['chain_id'],
  197. ];
  198. }
  199. private function resolveCommodityId(string $name): int
  200. {
  201. $commodityId = $this->commodityModel->getIdByName($name);
  202. if ($commodityId === null) {
  203. throw new \RuntimeException('Commodity não encontrada para o produto: ' . $name);
  204. }
  205. return $commodityId;
  206. }
  207. private function requireStringField(array $cpr, array $candidates, string $label): string
  208. {
  209. foreach ($candidates as $field) {
  210. if (!array_key_exists($field, $cpr)) {
  211. continue;
  212. }
  213. $value = $this->normalizeStringValue($cpr[$field]);
  214. if ($value !== '') {
  215. return $value;
  216. }
  217. }
  218. throw new \InvalidArgumentException("Campo {$label} ausente ou inválido na CPR.");
  219. }
  220. private function requireNumericField(array $cpr, array $candidates, string $label): int
  221. {
  222. foreach ($candidates as $field) {
  223. if (!array_key_exists($field, $cpr)) {
  224. continue;
  225. }
  226. $value = $this->normalizeNumericValue($cpr[$field]);
  227. if ($value !== null) {
  228. return $value;
  229. }
  230. }
  231. throw new \InvalidArgumentException("Campo {$label} ausente ou inválido na CPR.");
  232. }
  233. private function normalizeStringValue($value): string
  234. {
  235. if (is_array($value)) {
  236. $value = reset($value);
  237. }
  238. if (!is_scalar($value)) {
  239. return '';
  240. }
  241. $stringValue = trim((string)$value);
  242. if ($stringValue === '') {
  243. return '';
  244. }
  245. $parts = preg_split('/\s*;\s*/', $stringValue) ?: [];
  246. $first = $parts[0] ?? $stringValue;
  247. return trim((string)$first);
  248. }
  249. private function normalizeNumericValue($value): ?int
  250. {
  251. if (is_array($value)) {
  252. $value = reset($value);
  253. }
  254. if (is_string($value)) {
  255. $value = str_replace([' ', ','], ['', '.'], $value);
  256. }
  257. if (is_numeric($value)) {
  258. return (int)round((float)$value);
  259. }
  260. return null;
  261. }
  262. }