Created
September 19, 2023 20:02
-
-
Save alispat/1facf5974ea75281e908b4873f27886d to your computer and use it in GitHub Desktop.
Integração nova API Correios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CorreiosApiService | |
def self.get_token | |
token = nil | |
correios_token = CorreiosToken.all.first | |
if correios_token.nil? || correios_token.expires_at <= Time.now.utc - 30 * 60 | |
token_response = nil | |
begin | |
uri = URI("https://api.correios.com.br/token/v1/autentica/cartaopostagem") | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
request = Net::HTTP::Post.new(uri.path) | |
request['Accept'] = 'application/json' | |
codigo = Base64.strict_encode64("#{ENV["CORREIOS_USUARIO"]}:#{ENV["CORREIOS_CODIGO_ACESSO"]}") | |
request['Authorization'] = "Basic #{codigo}" | |
request.body = { "numero": "#{ENV["CORREIOS_CARTAO_POSTAGEM"]}" }.to_json | |
request['Content-Type'] = 'application/json' | |
response = http.request(request) | |
if response.code == '201' | |
response_body = response.body | |
token_response = JSON.parse(response_body) | |
CorreiosToken.destroy_all | |
CorreiosToken.create(token: token_response["token"], expires_at: token_response["expiraEm"].to_datetime) | |
token = token_response["token"] | |
elsif ['400', '500'].include?(response.code) | |
response_body = response.body | |
if !response_body.empty? | |
puts "*"*100 | |
puts response_body.inspect | |
puts "*"*100 | |
message_response = JSON.parse(response_body) | |
end | |
end | |
rescue StandardError => ex | |
puts "*"*100 | |
puts ex.inspect | |
puts "*"*100 | |
end | |
else | |
token = correios_token.token | |
end | |
token | |
end | |
def self.test | |
# pac 03298 | |
# sedex 03220 | |
token = get_token | |
resultado = CorreiosApiService.get_days(token, "03298", "05379000", "66045143") | |
#resultado = CorreiosApiService.get_price(token, "03220", "05379000", "66045143", "300", "20", "20", "20") | |
#resultado = CorreiosApiService.get_days_and_price(token, "03298", "05379000", "66045143", "300", "20", "20", "20") | |
#resultado = CorreiosApiService.get_days_and_price(token, "03220", "05379000", "66045143", "300", "20", "20", "20") | |
#resultado = CorreiosApiService.consultar("05379000", "66045143", 300, 20, 20, 20) | |
puts resultado.inspect | |
end | |
# {:days=>5, :domicile=>"N", :saturday=>"N", :erro=>false, :erro_message=>nil} | |
def self.get_days(token, cod_servico, cep_origem, cep_destino) | |
days = nil | |
begin | |
uri = URI("https://api.correios.com.br/prazo/v1/nacional/#{cod_servico}") | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
request = Net::HTTP::Get.new("https://api.correios.com.br/prazo/v1/nacional/#{cod_servico}?cepOrigem=#{cep_origem}&cepDestino=#{cep_destino}") | |
request['Accept'] = 'application/json' | |
request['Authorization'] = "Bearer #{token}" | |
request['Content-Type'] = 'application/json' | |
response = http.request(request) | |
if response.code == '200' | |
response_body = response.body | |
days_response = JSON.parse(response_body) | |
days = { | |
days: days_response["prazoEntrega"], | |
domicile: days_response["entregaDomiciliar"], | |
saturday: days_response["entregaSabado"], | |
erro: false, | |
erro_message: nil | |
} | |
elsif ['400', '500'].include?(response.code) | |
response_body = response.body | |
if !response_body.empty? | |
message_response = JSON.parse(response_body) | |
days = { | |
days: 0, | |
domicile: "N", | |
saturday: "N", | |
erro: true, | |
erro_message: message_response["msgs"][0] | |
} | |
end | |
end | |
rescue StandardError => ex | |
days = { | |
days: 0, | |
domicile: "N", | |
saturday: "N", | |
erro: true, | |
erro_message: ex.message | |
} | |
end | |
days | |
end | |
#{:price=>"11,32", :erro=>false, :erro_message=>nil} | |
def self.get_price(token, cod_servico, cep_origem, cep_destino, peso, comprimento, altura, largura) | |
token = get_token | |
preco = nil | |
begin | |
uri = URI("https://api.correios.com.br/preco/v1/nacional/#{cod_servico}") | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
request = Net::HTTP::Get.new("https://api.correios.com.br/preco/v1/nacional/#{cod_servico}?cepOrigem=#{cep_origem}&cepDestino=#{cep_destino}&psObjeto=#{peso}&largura=#{largura}&altura=#{altura}&comprimento=#{comprimento}") | |
request['Accept'] = 'application/json' | |
request['Authorization'] = "Bearer #{token}" | |
request['Content-Type'] = 'application/json' | |
response = http.request(request) | |
if response.code == '200' | |
response_body = response.body | |
preco_response = JSON.parse(response_body) | |
preco = { price: preco_response["pcFinal"], erro: false, erro_message: nil } | |
elsif ['400', '500'].include?(response.code) | |
response_body = response.body | |
if !response_body.empty? | |
message_response = JSON.parse(response_body) | |
preco = { price: 0, erro: true, erro_message: message_response["msgs"][0] } | |
end | |
end | |
rescue StandardError => ex | |
preco = { price: 0, erro: true, erro_message: ex.message } | |
end | |
preco | |
end | |
#{ price: 0, days: 0, domicile: "N", saturday: "N", erro: false, erro_message: nil } | |
def self.get_days_and_price(token, cod_servico, cep_origem, cep_destino, peso, comprimento, altura, largura) | |
cep_origem = "0#{cep_origem}" if !cep_origem.nil? && cep_origem.size == 7 | |
cep_destino = "0#{cep_destino}" if !cep_destino.nil? && cep_destino.size == 7 | |
result = { price: 0, days: 0, domicile: "N", saturday: "N", erro: false, erro_message: nil } | |
token = get_token | |
prazo = CorreiosApiService.get_days(token, cod_servico, cep_origem, cep_destino) | |
if prazo[:erro] == false | |
result[:days] = prazo[:days] | |
preco = CorreiosApiService.get_price(token, cod_servico, cep_origem, cep_destino, peso, comprimento, altura, largura) | |
if preco[:erro] == false | |
result[:price] = preco[:price] | |
else | |
result[:erro] = true | |
result[:erro_message] = preco[:erro_message] | |
end | |
else | |
result[:erro] = true | |
result[:erro_message] = prazo[:erro_message] | |
end | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment