"""Correios freight quotes (CWS API: Token, Preço and Prazo), PAC and SEDEX. Written from the Correios manuals (API Preço, API Prazo) and exercised against a fake HTTP transport until app.correios_probe has run on Dropstar's contract. A quote is read-only: it creates no shipment and costs nothing. The token comes from the posting card (cartão de postagem) with the CWS user and its access code, lasts about a day and is reused until shortly before it expires. It also says the contract and its regional office (DR), which price the contract's own rates. Each box of the order (app/package.py) is one object: Correios price the larger of its real and cubic weight themselves, from the box's sides, so only the real weight is sent. """ import base64 import os import threading from datetime import datetime, timedelta, timezone from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal, InvalidOperation import httpx from .package import Package API = 'https://api.correios.com.br' ORIGIN = '14402310' # The contract's service codes ("contrato agência"); a setting overrides each. SERVICES = {'pac': ('CORREIOS_COD_PAC', '03298', 'Correios PAC'), 'sedex': ('CORREIOS_COD_SEDEX', '03220', 'Correios SEDEX')} PACKAGE = '2' MAX_KG = Decimal(30) BRASILIA = timezone(timedelta(hours=-3)) class CorreiosError(Exception): pass def digits(value): return ''.join(ch for ch in str(value or '') if ch.isdigit()) def required_settings(): return ('CORREIOS_USUARIO', 'CORREIOS_CODIGO_ACESSO', 'CORREIOS_CARTAO') def configured(): return bool(os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip()) def problem(response): """The Correios' own words for a refusal: txErro, or the gateway's msgs.""" try: data = response.json() except ValueError: return f'HTTP {response.status_code}' if isinstance(data, list): data = data[0] if data else {} if isinstance(data, dict): if data.get('txErro'): return data['txErro'] if data.get('msgs'): return '; '.join(map(str, data['msgs'])) return f'HTTP {response.status_code}' def cents(text): """'11,64' (or 11.64) in centavos.""" try: value = Decimal(str(text).replace('.', '').replace(',', '.')) if ',' in str(text) else Decimal(str(text)) except InvalidOperation: raise CorreiosError(f'preço ilegível: {text!r}') from None return int((value * 100).quantize(Decimal('1'), ROUND_HALF_UP)) class CorreiosQuotes: def __init__(self, user=None, access_code=None, card=None, origin=None, transport=None, clock=None): self.user = (user or os.environ.get('CORREIOS_USUARIO', '')).strip() self.access_code = (access_code or os.environ.get('CORREIOS_CODIGO_ACESSO', '')).strip() self.card = digits(card or os.environ.get('CORREIOS_CARTAO')) self.origin = digits(origin or os.environ.get('CORREIOS_ORIGEM_CEP') or ORIGIN) if not (self.user and self.access_code and self.card): raise RuntimeError('Correios needs ' + ', '.join(required_settings())) self.http = httpx.Client(base_url=API, timeout=15, transport=transport) self.clock = clock or (lambda: datetime.now(timezone.utc)) self.lock = threading.Lock() self.token = None self.expires = None self.contract = None self.dr = None def authenticate(self): basic = base64.b64encode(f'{self.user}:{self.access_code}'.encode()).decode() response = self.http.post('/token/v1/autentica/cartaopostagem', json={'numero': self.card}, headers={'Authorization': f'Basic {basic}'}) if response.status_code >= 400: raise CorreiosError(f'token recusado: {problem(response)}') data = response.json() card = data.get('cartaoPostagem') or {} self.token = data['token'] self.contract = card.get('contrato') or os.environ.get('CORREIOS_CONTRATO') or None self.dr = card.get('dr') or os.environ.get('CORREIOS_DR') or None try: # "2026-10-16T10:00:00", Brasília time unless it says otherwise. expires = datetime.fromisoformat(data['expiraEm']) self.expires = expires if expires.tzinfo else expires.replace(tzinfo=BRASILIA) except (KeyError, TypeError, ValueError): self.expires = self.clock() + timedelta(hours=23) def bearer(self, fresh=False): with self.lock: if fresh or not self.token or self.clock() >= self.expires - timedelta(minutes=10): self.authenticate() return self.token def get(self, path, params): """A GET with the token, renewed once if the Correios refuse it.""" for fresh in (False, True): response = self.http.get(path, params=params, headers={'Authorization': f'Bearer {self.bearer(fresh)}', 'Accept': 'application/json'}) if response.status_code != 401: break if response.status_code >= 400: raise CorreiosError(problem(response)) return response.json() def price(self, code, postal_code, grams, sides): """The contract's price in centavos for one package.""" length, width, height = (int(side.to_integral_value(ROUND_CEILING)) for side in sides) params = {'cepOrigem': self.origin, 'cepDestino': postal_code, 'psObjeto': str(grams), 'tpObjeto': PACKAGE, 'comprimento': str(length), 'largura': str(width), 'altura': str(height)} self.bearer() if self.contract and self.dr: params.update(nuContrato=str(self.contract), nuDR=str(self.dr)) data = self.get(f'/preco/v1/nacional/{code}', params) if data.get('txErro'): raise CorreiosError(data['txErro']) if data.get('pcFinal') in (None, ''): raise CorreiosError('sem preço na resposta') return cents(data['pcFinal']) def days(self, code, postal_code): """Delivery time in working days from posting, or None.""" data = self.get(f'/prazo/v1/nacional/{code}', {'cepOrigem': self.origin, 'cepDestino': postal_code}) if data.get('txErro'): raise CorreiosError(data['txErro']) return data.get('prazoEntrega') class CorreiosFreight(Package): """The Site's PAC and SEDEX options for the order's package.""" name = 'correios' def __init__(self, quotes=None): super().__init__() if not self.box_cm: raise RuntimeError('Correios price by the box: set JADLOG_CAIXA_CM') self.quotes = quotes or CorreiosQuotes() self.codes = {service: (os.environ.get(setting) or code).strip() for service, (setting, code, _) in SERVICES.items()} self.services = {service: label for service, (_, _, label) in SERVICES.items()} def quote(self, service, postal_code, metres=None, declared_cents=0): if service == 'pickup': return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''} if service not in self.codes or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit(): raise ValueError('Select pickup or Correios delivery with an eight-digit CEP') if metres is None or Decimal(str(metres)) <= 0: raise ValueError('The order length is required to quote freight') weights = self.box_weights_kg(metres) if max(weights) > MAX_KG: raise ValueError('Uma caixa passa de 30 kg, o limite dos Correios.') code = self.codes[service] try: # Boxes of the same weight cost the same: one price per weight. prices = {weight: self.quotes.price(code, postal_code, int(weight * 1000), self.box_cm) for weight in set(weights)} days = self.quotes.days(code, postal_code) except (CorreiosError, httpx.HTTPError) as error: raise ValueError(f'Não foi possível cotar o {self.services[service]} agora: {error}') from None return {'provider': self.name, 'service': service, 'postal_code': postal_code, 'total_cents': sum(prices[weight] for weight in weights), 'real_kg': str(sum(weights)), 'boxes': len(weights), 'days': None if days is None else int(days) + self.production_days, 'description': self.services[service]}