Class: CorreiosApi::Client

Inherits:
Ac::Base
  • Object
show all
Defined in:
lib/correios_api/client.rb

Constant Summary collapse

BASE_URL =
"https://api.correios.com.br"
MAX_RETRIES =
4
SAVE_RESPONSES =
true
TIMEOUT =
4
SERVICES =
[
  {
    code: "03220",
    name: "SEDEX CONTRATO AG"
  },
  {
    code: "04553",
    name: "SEDEX CONTRATO AGENCIA TA"
  },
  {
    code: "03298",
    name: "PAC CONTRATO AG"
  },
  {
    code: "04596",
    name: "PAC CONTRATO AGENCIA TA"
  },
  {
    code: "04227",
    name: "CORREIOS MINI ENVIOS CTR AG"
  }
]
SERVICE_NAMES =
{
  "03220" => "SEDEX CONTRATO AG",
  "04553" => "SEDEX CONTRATO AGENCIA TA",
  "03298" => "PAC CONTRATO AG",
  "04596" => "PAC CONTRATO AGENCIA TA",
  "04227" => "CORREIOS MINI ENVIOS CTR AG"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(username:, password:, post_card:, contract_number: nil, access_token: nil, token_expires_at: nil) ⇒ Client

Returns a new instance of Client.



39
40
41
42
43
44
45
46
# File 'lib/correios_api/client.rb', line 39

def initialize username:, password:, post_card:, contract_number: nil, access_token: nil, token_expires_at: nil
  @username = username
  @password = password
  @post_card = post_card
  @contract_number = contract_number
  @access_token = access_token
  @token_expires_at = token_expires_at
end

Instance Attribute Details

#contract_numberObject (readonly)

Returns the value of attribute contract_number.



38
39
40
# File 'lib/correios_api/client.rb', line 38

def contract_number
  @contract_number
end

#passwordObject (readonly)

Returns the value of attribute password.



38
39
40
# File 'lib/correios_api/client.rb', line 38

def password
  @password
end

#post_cardObject (readonly)

Returns the value of attribute post_card.



38
39
40
# File 'lib/correios_api/client.rb', line 38

def post_card
  @post_card
end

#token_expires_atObject (readonly)

Returns the value of attribute token_expires_at.



38
39
40
# File 'lib/correios_api/client.rb', line 38

def token_expires_at
  @token_expires_at
end

#usernameObject (readonly)

Returns the value of attribute username.



38
39
40
# File 'lib/correios_api/client.rb', line 38

def username
  @username
end

Instance Method Details

#create_label(pre_shipping) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/correios_api/client.rb', line 126

def create_label pre_shipping
  body = {
    codigosObjeto: [
      pre_shipping.tracking_code
    ],
    idCorreios: @username,
    numeroCartaoPostagem: @post_card,
    tipoRotulo: "P", # P (padrão) ou R (reduzido)
    formatoRotulo: "ET", # ET (Etiqueta) ou EV (Envelope)
    imprimeRemetente: "S", # S (Sim) ou N (não)
    layoutImpressao: "PADRAO" # PADRAO, LINEAR_100_150, LINEAR_100_80, LINEAR_A4, LINEAR_A
  }
  response = post("/prepostagem/v1/prepostagens/rotulo/assincrono/pdf", body:)
  sleep(0.5) # Tem que esperar o PDF ficar pronto
  get_label(response.idRecibo)
end

#create_pre_shipping(shipper_name:, shipper_tax_id:, shipper_zipcode:, shipper_street:, shipper_address_number:, shipper_district:, shipper_city:, shipper_state_code:, receiver_name:, receiver_tax_id:, receiver_zipcode:, receiver_street:, receiver_address_number:, receiver_district:, receiver_city:, receiver_state_code:, service_code:, price:, items:, weight_g:, height_cm: 15, width_cm: 15, length_cm: 15) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/correios_api/client.rb', line 80

def create_pre_shipping shipper_name:, shipper_tax_id:, shipper_zipcode:, shipper_street:, shipper_address_number:, shipper_district:, shipper_city:, shipper_state_code:, receiver_name:, receiver_tax_id:, receiver_zipcode:, receiver_street:, receiver_address_number:, receiver_district:, receiver_city:, receiver_state_code:, service_code:, price:, items:, weight_g:, height_cm: 15, width_cm: 15, length_cm: 15
  body = {
    idCorreios: @username,
    remetente: {
      nome: shipper_name,
      cpfCnpj: shipper_tax_id,
      endereco: {
        cep: shipper_zipcode,
        logradouro: shipper_street,
        numero: shipper_address_number,
        bairro: shipper_district,
        cidade: shipper_city,
        uf: shipper_state_code
      }
    },
    destinatario: {
      nome: receiver_name,
      cpfCnpj: receiver_tax_id,
      endereco: {
        cep: receiver_zipcode,
        logradouro: receiver_street,
        numero: receiver_address_number,
        bairro: receiver_district,
        cidade: receiver_city,
        uf: receiver_state_code
      }
    },
    codigoServico: service_code,
    precoPrePostagem: price,
    numeroCartaoPostagem: @post_card,
    itensDeclaracaoConteudo: items, # conteudo, quantidade, valor
    pesoInformado: weight_g,
    codigoFormatoObjetoInformado: "2",
    alturaInformada: height_cm,
    larguraInformada: width_cm,
    comprimentoInformado: length_cm,
    cienteObjetoNaoProibido: "1",
    modalidadePagamento: "2" # 1-à vista, 2-à faturar, 3- à avista e à afaturar e 4- Prestação de contas recebimento ou pagamento
    # solicitarColeta: "N",
    # dataPrevistaPostagem: "29/09/2024"
  }

  response = post("/prepostagem/v1/prepostagens", body:)
  PreShipping.new(response)
end

#create_rates(zipcode_from:, zipcode_to:, weight_g: 1000, height_cm: 15, width_cm: 15, length_cm: 15) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/correios_api/client.rb', line 148

def create_rates zipcode_from:, zipcode_to:, weight_g: 1000, height_cm: 15, width_cm: 15, length_cm: 15
  services_with_time = delivery_time(zipcode_from, zipcode_to)
  services_with_cost = delivery_cost(zipcode_from, zipcode_to, weight_g, height_cm, width_cm, length_cm)
  rates = services_with_time.map do |service_time|
    service_cost = services_with_cost.find { |service| service["coProduto"] == service_time["coProduto"] }
    next if service_cost.nil?

    Rate.new(
      service_name: SERVICE_NAMES[service_time.coProduto],
      service_code: service_time.coProduto,
      price: service_cost["pcFinal"],
      delivery_time_in_days: service_time["prazoEntrega"],
      max_delivery_time: service_time["dataMaxima"],
      message: service_time["msgPrazo"],
      errors: [
        service_cost["txErro"],
        service_time["txErro"]
      ].compact
    )
  end.compact
  ShippingQuotes.new(rates)
end

#default_optionsObject



48
49
50
51
52
53
54
55
56
# File 'lib/correios_api/client.rb', line 48

def default_options
  {
    headers: {
      "Content-Type" => "application/json",
      "X-Idempotency-Key" => SecureRandom.uuid
    },
    timeout: TIMEOUT
  }
end

#delivery_cost(zipcode_from, zipcode_to, weight_g, height_cm, width_cm, length_cm) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/correios_api/client.rb', line 181

def delivery_cost zipcode_from, zipcode_to, weight_g, height_cm, width_cm, length_cm
  zipcode_from_digits = CodigoPostal.new(zipcode_from).cep_digits
  zipcode_to_digits = CodigoPostal.new(zipcode_to).cep_digits
  params_produto = SERVICES.map do |service|
    {
      coProduto: service[:code],
      nuRequisicao: "1",
      cepOrigem: zipcode_from_digits,
      cepDestino: zipcode_to_digits,
      psObjeto: weight_g,
      altura: height_cm,
      largura: width_cm,
      comprimento: length_cm,
      tpObjeto: "2"
    }
  end
  body = {
    idLote: "1",
    parametrosProduto: params_produto
  }

  post("/preco/v1/nacional", body:) { _1[0].coProduto }
end

#delivery_time(zipcode_from, zipcode_to) ⇒ Object



171
172
173
174
175
176
177
178
179
# File 'lib/correios_api/client.rb', line 171

def delivery_time zipcode_from, zipcode_to
  zipcode_from_digits = CodigoPostal.new(zipcode_from).cep_digits
  zipcode_to_digits = CodigoPostal.new(zipcode_to).cep_digits
  body = {
    idLote: "1",
    parametrosPrazo: SERVICES.map { |service| {coProduto: service[:code], nuRequisicao: 1, cepOrigem: zipcode_from_digits, cepDestino: zipcode_to_digits} }
  }
  post("/prazo/v1/nacional", body:) { _1[0].coProduto }
end

#get_label(id) ⇒ Object



143
144
145
146
# File 'lib/correios_api/client.rb', line 143

def get_label id
  response = get("/prepostagem/v1/prepostagens/rotulo/download/assincrono/#{id}")
  Label.new(response)
end

#refresh_tokenObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/correios_api/client.rb', line 58

def refresh_token
  headers = {
    "Authorization" => "Basic #{Base64.strict_encode64("#{@username}:#{@password}")}",
  }
  body = {
    numero: @post_card
  }
  response = post(
    "/token/v1/autentica/cartaopostagem",
    headers:,
    body:,
    skip_authentication: true
  )
  @access_token = response.token
  @token_expires_at = response.expiraEm.to_time
end

#tracking_package(tracking_code, result_type = "T") ⇒ Object



75
76
77
78
# File 'lib/correios_api/client.rb', line 75

def tracking_package tracking_code, result_type = "T"
  response = get("/srorastro/v1/objetos/#{tracking_code}?resultado=#{result_type}")
  Tracking.new(response)
end