From 69dd4c22df846def3b85d39bb094b952c5450a6c Mon Sep 17 00:00:00 2001 From: Lucas Barroso Date: Thu, 4 Dec 2025 23:14:44 -0300 Subject: [PATCH] docs: add README.md and LICENSE --- LICENSE | 201 +++++++++++++++++++++ README.md | 519 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 715 insertions(+), 5 deletions(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b148860 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or order names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 4230084..98c442a 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,527 @@ -# API de Pagamentos +# API de Pagamentos - SOAT Tech Challenge -## Build de imagens +Este repositório contém o **microsserviço de pagamentos** desenvolvido como parte da pós-graduação em **Arquitetura de Software** da **FIAP**. Este serviço é responsável por gerenciar todo o fluxo de pagamentos integrado ao **Mercado Pago**, desde a criação de QR codes dinâmicos até o processamento de notificações de pagamento. -### Desenvolvimento / Teste +## 📌 Menu + +- [Integrantes](#integrantes) +- [Sobre o Projeto](#sobre-o-projeto) +- [Arquitetura](#arquitetura) + - [Arquitetura Hexagonal](#arquitetura-hexagonal) + - [Domain-Driven Design (DDD)](#domain-driven-design-ddd) + - [Comunicação Assíncrona](#comunicação-assíncrona) +- [Funcionalidades](#funcionalidades) +- [Tecnologias](#tecnologias) +- [Estrutura do Projeto](#estrutura-do-projeto) +- [Configuração e Execução](#configuração-e-execução) + - [Pré-requisitos](#pré-requisitos) + - [Variáveis de Ambiente](#variáveis-de-ambiente) + - [Build das Imagens](#build-das-imagens) + - [Execução Local com Docker Compose](#execução-local-com-docker-compose) +- [Testes](#testes) +- [CI/CD](#cicd) +- [Implantação na AWS](#implantação-na-aws) +- [Endpoints da API](#endpoints-da-api) +- [Integração com Mercado Pago](#integração-com-mercado-pago) +- [Licença](#licença) + +## Integrantes + +| Nome | RM | Discord | +| ------------------------------------------ | -------- | ------------------------- | +| Carlos Eduardo Bastos Laet | RM361151 | CarlosLaet | +| Karen Lais Martins Pontes de Fávere Orrico | RM361158 | Karen Pontes | +| Lucas Martins Barroso | RM362732 | Lucas Barroso - RM362732 | +| Raphael Oliver | RM362129 | Raphael Oliver - RM362129 | + +## Sobre o Projeto + +Na **Fase 4** da pós-graduação, o projeto passou por uma transformação arquitetural significativa: a API monolítica original foi decomposta em uma **arquitetura de microsserviços**. Esta API é o microsserviço responsável exclusivamente pela gestão de pagamentos. + +O sistema completo é composto por: +- **[Lambda de Autenticação](https://github.com/SOAT-Tech-Challenge-2025/lambda-identification-auth)**: Autenticação e identificação de usuários +- **[Carrinho de Compras](https://github.com/SOAT-Tech-Challenge-2025/ms-shopping-cart)**: Gerenciamento de pedidos e produtos +- **[API de Pagamentos](https://github.com/SOAT-Tech-Challenge-2025/payment-api)**: Este repositório - gerenciamento de pagamentos +- **[API de Preparação](https://github.com/SOAT-Tech-Challenge-2025/preparation-api)**: Gerenciamento da fila de preparação de pedidos +- **[Infraestrutura](https://github.com/SOAT-Tech-Challenge-2025/infrastructure)**: Terraform para VPC, EKS e API Gateway +- **[Database](https://github.com/SOAT-Tech-Challenge-2025/database)**: Gestão de bancos de dados do projeto + +### Motivação da Separação + +O módulo de pagamentos foi modelado desde o início do projeto como um **Bounded Context** independente, seguindo os princípios de Domain-Driven Design. No monolito original, cada contexto já era implementado como um módulo bem isolado, sem relacionamentos entre tabelas de diferentes contextos no banco de dados. + +A decomposição em microsserviços na Fase 4 foi uma evolução natural dessa arquitetura, proporcionando: +- **Bounded Contexts bem definidos**: Cada microsserviço representa um contexto delimitado do domínio +- **Autonomia de dados**: Cada contexto possui seu próprio banco de dados, reforçando o isolamento +- **Escalabilidade independente**: Possibilidade de escalar cada serviço conforme sua demanda específica +- **Resiliência**: Falhas em um contexto não afetam diretamente outros contextos +- **Evolução independente**: Times podem evoluir cada bounded context de forma autônoma + +## Arquitetura + +### Arquitetura Hexagonal + +O projeto segue os princípios da **Arquitetura Hexagonal** (Ports and Adapters), organizando o código em camadas bem definidas com foco no domínio e isolamento de dependências externas: + +``` +payment_api/ +├── domain/ # Hexágono - Núcleo da aplicação +│ ├── entities/ # Entidades de domínio (Payment, Product) +│ ├── events/ # Eventos de domínio (PaymentClosedEvent) +│ ├── value_objects/ # Objetos de valor (PaymentStatus) +│ └── ports/ # Todas as portas (interfaces do hexágono) +│ ├── payment_repository.py # Interface para persistência +│ ├── payment_gateway.py # Interface para gateway de pagamento +│ ├── payment_closed_publisher.py # Interface para publicação de eventos +│ ├── qr_code_renderer.py # Interface para renderização de QR Code +│ └── mercado_pago_client.py # Interface para client Mercado Pago +│ +├── application/ # Casos de uso e orquestração +│ ├── commands/ # Comandos de entrada (DTOs) +│ └── use_cases/ # Implementação dos casos de uso +│ +├── adapters/ # Adaptadores (Ports & Adapters) +│ ├── inbound/ # Adaptadores condutores (driving) +│ │ ├── rest/ # API REST (FastAPI) +│ │ └── listeners/ # Consumer SQS (OrderCreatedListener) +│ └── out/ # Adaptadores conduzidos (driven) +│ ├── sa_payment_repository.py # Implementação da porta PaymentRepository +│ ├── mp_payment_gateway.py # Implementação da porta PaymentGateway +│ ├── boto_payment_closed_publisher.py # Implementação da porta PaymentClosedPublisher +│ ├── qr_code_renderer.py # Implementação da porta QRCodeRenderer +│ └── mercado_pago_client.py # Implementação da porta MercadoPagoClient +│ +├── infrastructure/ # Configurações e detalhes técnicos +│ ├── alembic/ # Migrations de banco de dados +│ ├── orm/ # Modelos SQLAlchemy +│ ├── mercado_pago/ # Cliente HTTP Mercado Pago +│ ├── config.py # Configurações da aplicação +│ └── factory.py # Injeção de dependências +│ +└── entrypoints/ # Pontos de entrada da aplicação + ├── api.py # FastAPI application + └── order_created_listener.py # Consumer de eventos +``` + +### Domain-Driven Design (DDD) + +O domínio de pagamentos é modelado com: + +**Entidades:** +- `Payment`: Representa um pagamento com ciclo de vida próprio +- `Product`: Produtos associados ao pedido + +**Value Objects:** +- `PaymentStatus`: Estado do pagamento (OPENED, APPROVED, REJECTED) + +**Eventos de Domínio:** +- `PaymentClosedEvent`: Disparado quando um pagamento é finalizado + +**Portas (Interfaces):** +- `PaymentRepository`: Persistência de pagamentos +- `PaymentGateway`: Integração com gateway de pagamento +- `PaymentClosedPublisher`: Publicação de eventos de pagamento +- `QRCodeRenderer`: Renderização de imagens QR Code +- `MercadoPagoClient`: Comunicação com API do Mercado Pago + +### Comunicação Assíncrona + +O microsserviço se comunica de forma assíncrona com outros serviços através de **AWS SNS/SQS**: + +**Consumo de Eventos (SQS):** +- **OrderCreatedEvent**: Recebe notificações de pedidos criados para gerar pagamentos + +**Publicação de Eventos (SNS):** +- **PaymentClosedEvent**: Notifica outros serviços quando um pagamento é finalizado (aprovado/rejeitado) + +``` +┌─────────────────┐ OrderCreated ┌──────────────────┐ +│ Shopping Cart │─────────(SQS)──────────>│ Payment API │ +└─────────────────┘ └──────────────────┘ + │ + PaymentClosed (SNS) + │ + v + ┌──────────────────┐ + │ Preparation API │ + └──────────────────┘ +``` + +## Funcionalidades + +### 1. Criação de Pagamento +- Recebe evento de pedido criado via SQS +- Cria registro de pagamento no banco de dados +- Gera QR code dinâmico no Mercado Pago +- Retorna informações do pagamento com QR code + +### 2. Consulta de Pagamento +- `GET /v1/payment/{payment_id}`: Busca informações de um pagamento +- Retorna status, valor total, data de expiração e informações do QR code + +### 3. Renderização de QR Code +- `GET /v1/payment/{payment_id}/qr`: Gera imagem PNG do QR code +- Facilita exibição em interfaces de usuário + +### 4. Webhook Mercado Pago +- `POST /v1/payment/notifications/mercado-pago`: Recebe notificações de pagamento +- Valida autenticidade através de webhook key +- Atualiza status do pagamento +- Publica evento `PaymentClosedEvent` via SNS + +## Tecnologias + +- **Python 3.14**: Linguagem de programação +- **Poetry**: Gerenciador de dependências e empacotamento +- **FastAPI**: Framework web assíncrono para REST API +- **Pydantic**: Validação de dados e serialização +- **SQLAlchemy + Asyncpg**: ORM assíncrono com PostgreSQL +- **Alembic**: Migrations de banco de dados +- **HTTPX**: Cliente HTTP assíncrono para Mercado Pago +- **QRCode + Pillow**: Geração de imagens QR code +- **AIOBoto3**: Cliente assíncrono AWS (SNS/SQS) +- **Pytest**: Framework de testes +- **Docker**: Containerização +- **Kubernetes**: Orquestração de containers +- **Terraform**: Infrastructure as Code +- **GitHub Actions**: CI/CD + +## Estrutura do Projeto + +``` +payment-api/ +├── payment_api/ # Código fonte principal +│ ├── adapters/ # Camada de adaptadores +│ ├── application/ # Casos de uso +│ ├── domain/ # Domínio do negócio +│ ├── entrypoints/ # Pontos de entrada +│ └── infrastructure/ # Configurações e infra +│ +├── tests/ # Testes unitários e integração +│ ├── unit/ # Testes unitários +│ └── integration/ # Testes de integração +│ +├── terraform/ # Infrastructure as Code +│ ├── k8s_*.tf # Recursos Kubernetes +│ ├── data.tf # Data sources +│ ├── locals.tf # Variáveis locais +│ ├── providers.tf # Providers Terraform +│ └── vars.tf # Variáveis de entrada +│ +├── docker-entrypoint/ # Scripts de inicialização +├── settings/ # Arquivos de configuração +├── .github/workflows/ # Pipelines CI/CD +│ ├── ci_cd.yml # Pipeline principal +│ └── destroy.yml # Destruição de infraestrutura +│ +├── Dockerfile # Multi-stage build +├── docker-compose.yml # Desenvolvimento local +├── docker-compose.test.yml # Ambiente de testes +├── pyproject.toml # Dependências Poetry +├── alembic.ini # Configuração Alembic +└── pytest.ini # Configuração Pytest +``` + +## Configuração e Execução + +### Pré-requisitos + +- Docker e Docker Compose +- Python 3.14+ (para desenvolvimento local sem Docker) +- Poetry (gerenciador de dependências Python) +- Conta no Mercado Pago com credenciais de API +- Conta AWS com acesso a SQS e SNS (para ambiente completo) + +### Variáveis de Ambiente + +O projeto utiliza múltiplos arquivos de configuração na pasta `settings/`. Crie os arquivos baseados nos exemplos (`.env.example`): + +**settings/app.env** +```env +TITLE="SOAT Tech Challenge Payment API" +VERSION="1.0.0" +ENVIRONMENT="development" +ROOT_PATH="/soat-fast-food" +``` + +**settings/database.env** +```env +DSN="postgresql+asyncpg://postgres:12345@db:5432/postgres" +ECHO=False +``` + +**settings/mercado_pago.env** +```env +ACCESS_TOKEN="seu_access_token" +USER_ID="seu_user_id" +POS="seu_pos_id" +CALLBACK_URL="https://seu-dominio.com/soat-fast-food/v1/payment/notifications/mercado-pago" +WEBHOOK_KEY="sua_chave_webhook" +``` + +**settings/aws.env** +```env +REGION_NAME="us-east-1" +ACCOUNT_ID="sua_conta_aws" +ACCESS_KEY_ID="sua_access_key" +SECRET_ACCESS_KEY="sua_secret_key" +``` + +**settings/order_created_listener.env** +```env +QUEUE_NAME="order-created-queue" +WAIT_TIME_SECONDS=20 +VISIBILITY_TIMEOUT_SECONDS=30 +MAX_NUMBER_OF_MESSAGES_PER_BATCH=10 +``` + +**settings/payment_closed_publisher.env** +```env +TOPIC_ARN="arn:aws:sns:us-east-1:123456789012:payment-closed" +GROUP_ID="payment-closed-group" +``` + +### Build das Imagens + +#### Desenvolvimento / Teste ```sh docker build --target development -t payment-api:dev . ``` -### Produção +#### Produção ```sh docker build --target production -t payment-api:latest . ``` +### Execução Local com Docker Compose + +1. **Configure as variáveis de ambiente**: + ```sh + cp docker-compose-env/app.env.example docker-compose-env/app.env + cp docker-compose-env/database.env.example docker-compose-env/database.env + ``` + +2. **Inicie os serviços**: + ```sh + docker compose up -d + ``` + +3. **Execute as migrations**: + ```sh + docker compose exec api alembic upgrade head + ``` + +4. **Acesse a API**: + - API: http://localhost:8000 + - Documentação Swagger: http://localhost:8000/docs + - ReDoc: http://localhost:8000/redoc + +5. **Pare os serviços**: + ```sh + docker compose down + ``` + ## Testes + +### Executar todos os testes +```sh +docker compose -f docker-compose.test.yml up -d +docker compose -f docker-compose.test.yml exec api pytest +``` + +### Executar com cobertura ```sh -docker run --rm payment-api:dev pytest +docker compose -f docker-compose.test.yml exec api pytest --cov=payment_api --cov-report=html +``` + +### Estrutura de Testes + +- **Testes Unitários** (`tests/unit/`): Testam componentes isoladamente +- **Testes de Integração** (`tests/integration/`): Testam integrações com banco de dados e APIs externas + +## CI/CD + +O projeto possui pipeline completa no **GitHub Actions** com as seguintes etapas: + +### Pipeline Principal (ci_cd.yml) + +1. **Test**: Execução de testes unitários e de integração +2. **SonarQube**: Análise de qualidade de código e cobertura +3. **Build and Push**: Build da imagem Docker e push para ECR público +4. **Deploy**: Implantação no Kubernetes via Terraform + +**Trigger**: Push em qualquer branch ou manualmente + +### Pipeline de Destruição (destroy.yml) + +Permite destruir a infraestrutura de forma controlada. + +**Trigger**: Manual (workflow_dispatch) + +## Implantação na AWS + +A infraestrutura é provisionada utilizando **Terraform** e implantada em **Amazon EKS**. + +### Recursos Kubernetes + +- **Namespace**: `tech-challenge-payment-api` +- **Deployment**: `payment-api-deployment` (API REST) +- **Deployment**: `order-created-listener-deployment` (Consumer SQS) +- **Service**: `payment-api-service` (ClusterIP) +- **Ingress**: Roteamento via NGINX Ingress Controller +- **HPA**: Auto-scaling baseado em CPU e memória (1-3 replicas) +- **ConfigMap**: Configurações não sensíveis +- **Secret**: Credenciais e tokens + +### Implantação Manual + +1. **Configure backend do Terraform**: + ```sh + cd terraform + cp backend.hcl.example backend.hcl + # Edite backend.hcl com suas configurações + ``` + +2. **Inicialize o Terraform**: + ```sh + terraform init -backend-config=backend.hcl + ``` + +3. **Execute o plan**: + ```sh + terraform plan -var-file=terraform.tfvars + ``` + +4. **Aplique as mudanças**: + ```sh + terraform apply -var-file=terraform.tfvars + ``` + +## Endpoints da API + +### Consultar Pagamento +```http +GET /soat-fast-food/v1/payment/{payment_id} +``` + +**Resposta:** +```json +{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "external_id": "123456789", + "payment_status": "OPENED", + "total_order_value": 50.00, + "qr_code": "00020126580014br.gov.bcb.pix...", + "expiration": "2025-12-04T15:30:00", + "created_at": "2025-12-04T15:15:00", + "timestamp": "2025-12-04T15:15:00" +} ``` + +### Renderizar QR Code +```http +GET /soat-fast-food/v1/payment/{payment_id}/qr +``` + +**Resposta**: Imagem PNG do QR code + +### Webhook Mercado Pago +```http +POST /soat-fast-food/v1/payment/notifications/mercado-pago?x-mp-webhook-key={key} +``` + +**Body:** +```json +{ + "action": "payment.created", + "type": "payment", + "data": { + "id": "123456789" + } +} +``` + +## Integração com Mercado Pago + +O serviço utiliza a API de **QR Code Dinâmico** do Mercado Pago para processar pagamentos presenciais. + +### Fluxo de Pagamento + +1. **Criação do Pedido**: Carrinho de compras cria pedido e publica evento +2. **Criação do Pagamento**: Payment API recebe evento e cria QR code no Mercado Pago +3. **Exibição do QR Code**: Cliente escaneia QR code no app Mercado Pago +4. **Pagamento**: Cliente confirma pagamento no app +5. **Notificação**: Mercado Pago envia webhook para API de pagamentos +6. **Finalização**: Payment API atualiza status e publica evento de pagamento fechado + +### Pré-requisitos para Testes + +Para realizar os testes da integração com Mercado Pago, há duas opções: + +#### Opção 1: Utilizar nossas credenciais de teste (Recomendado) + +Utilize as **credenciais de teste e usuário de teste** que enviamos na entrega do projeto. Essas credenciais já estão configuradas e prontas para uso: + +- Configure as variáveis de ambiente do Mercado Pago (`settings/mercado_pago.env`) com os valores fornecidos na entrega +- Utilize o **usuário de teste (comprador)** fornecido para realizar as compras no app Mercado Pago +- Teste o fluxo completo de pagamento sem necessidade de configuração adicional + +#### Opção 2: Configurar sua própria integração + +Caso prefira realizar sua própria integração com o Mercado Pago, siga os passos abaixo: + +1. Crie uma conta **de produção** no Mercado Pago +2. Acesse o [Portal do Desenvolvedor](https://www.mercadopago.com.br/developers) e **crie uma aplicação** +3. Gere **usuários de teste** vinculados à aplicação: + - Um usuário **vendedor** + - Um usuário **comprador** +4. Com a conta de vendedor, crie uma aplicação no portal do desenvolvedor +5. Nas **credenciais de produção** da aplicação, obtenha: + - `MERCADO_PAGO_ACCESS_TOKEN`: Access Token + - `MERCADO_PAGO_USER_ID`: User ID +6. Crie uma **store** via API do Mercado Pago: + ``` + POST https://api.mercadopago.com/users/{USER_ID}/stores + ``` +7. Crie um **POS** (ponto de venda) vinculado à store: + ``` + POST https://api.mercadopago.com/pos + ``` +8. O valor do campo `external_store_id` do POS deve ser usado na variável `MERCADO_PAGO_POS` +9. Gere um token aleatório e seguro para configurar como `MERCADO_PAGO_WEBHOOK_KEY` + +### Como Testar o Fluxo de Pagamento + +Para que o Mercado Pago consiga notificar a finalização do pagamento, a API precisa estar **acessível na web**. + +A URL configurada em `MERCADO_PAGO_CALLBACK_URL` deve seguir o formato: + +``` +https://{ENDERECO_DA_API}/soat-fast-food/v1/payment/notifications/mercado-pago +``` + +### Variáveis de Ambiente do Mercado Pago + +Configure as seguintes variáveis no arquivo `settings/mercado_pago.env`: + +- `ACCESS_TOKEN`: Token de autenticação da API do Mercado Pago +- `USER_ID`: ID do usuário vinculado à aplicação +- `POS`: Valor de `external_store_id` do POS criado via API +- `CALLBACK_URL`: URL que receberá notificações de pagamento (webhook) +- `WEBHOOK_KEY`: Token usado como parâmetro de query para validar as notificações + +### Segurança + +- Webhook protegido por key de autenticação (query parameter) +- Validação de assinatura do webhook +- HTTPS obrigatório em produção + +## Licença + +Este projeto está licenciado sob a **Apache License 2.0**. Consulte o arquivo [LICENSE](LICENSE) para mais detalhes. + +Desenvolvido para fins educacionais como parte da pós-graduação em Arquitetura de Software da FIAP. + +--- + +**Documentação complementar**: Para entender o sistema completo, consulte os repositórios dos demais microsserviços listados na seção [Sobre o Projeto](#sobre-o-projeto).