Soap.Package 1.1.0

dotnet add package Soap.Package --version 1.1.0
                    
NuGet\Install-Package Soap.Package -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Soap.Package" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Soap.Package" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Soap.Package" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Soap.Package --version 1.1.0
                    
#r "nuget: Soap.Package, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Soap.Package@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Soap.Package&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Soap.Package&version=1.1.0
                    
Install as a Cake Tool

Soap.Package 🚚

NuGet License: MIT .NET

Biblioteca C# completa para cálculos de frete e serviços de geolocalização, ideal para sistemas de logística e e-commerce.

📋 Sumário

🚀 Instalação

dotnet add package Soap.Package

Ou via NuGet Package Manager:

Install-Package Soap.Package

✨ Recursos

  • Cálculo de Frete SOAP: Integração com serviços de frete via protocolo SOAP
  • Geolocalização por CEP: Conversão de CEP para coordenadas geográficas
  • Cálculo de Distância: Distância entre CEPs usando rotas reais ou linha reta
  • Fallback Inteligente: Múltiplas estratégias para máxima confiabilidade

📦 Cálculo de Frete

ShippingCalculation

A classe ShippingCalculation oferece métodos para calcular fretes usando o serviço Total Express.

Métodos Disponíveis
// Gera detalhes da requisição SOAP (para debug/teste)
string GenerateRequestDetails(
    string originZip, 
    string destinationZip, 
    decimal weight, 
    decimal declaredValue, 
    string username, 
    string password
)

// Extrai dados da resposta SOAP
(string DeliveryTime, string ServiceValue) ExtractShippingData(string xml)

// Calcula frete de forma assíncrona
Task<string> CalculateShippingAsync(
    string originZip, 
    string destinationZip, 
    decimal weight, 
    decimal declaredValue, 
    string username, 
    string password
)
Exemplo de Uso - Cálculo de Frete
using Soap.Shipping;

// Parâmetros do cálculo
string originZip = "01310-100";
string destinationZip = "20040-020";
decimal weight = 1.5m; // kg
decimal declaredValue = 250.00m; // R$
string username = "seu_usuario";
string password = "sua_senha";

// Gerar requisição SOAP (útil para debug)
var requestDetails = ShippingCalculation.GenerateRequestDetails(
    originZip, destinationZip, weight, declaredValue, username, password
);

Console.WriteLine("=== REQUISIÇÃO SOAP ===");
Console.WriteLine(requestDetails);

// Calcular frete
try
{
    var soapResponse = await ShippingCalculation.CalculateShippingAsync(
        originZip, destinationZip, weight, declaredValue, username, password
    );

    // Extrair dados da resposta
    var (deliveryTime, serviceValue) = ShippingCalculation.ExtractShippingData(soapResponse);

    Console.WriteLine($"Prazo de entrega: {deliveryTime}");
    Console.WriteLine($"Valor do frete: R$ {serviceValue}");
}
catch (Exception ex)
{
    Console.WriteLine($"Erro ao calcular frete: {ex.Message}");
}
Exemplo de Payload SOAP
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:calcularFrete">
    <soapenv:Header/>
    <soapenv:Body>
        <urn:calcularFrete>
            <cepOrigem>01310100</cepOrigem>
            <cepDestino>20040020</cepDestino>
            <peso>1.50</peso>
            <valorDeclarado>250.00</valorDeclarado>
            <usuario>seu_usuario</usuario>
            <senha>sua_senha</senha>
        </urn:calcularFrete>
    </soapenv:Body>
</soapenv:Envelope>
Exemplo de Resposta SOAP
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns1:calcularFreteResponse xmlns:ns1="urn:calcularFrete">
            <Prazo>3</Prazo>
            <ValorServico>25.90</ValorServico>
        </ns1:calcularFreteResponse>
    </soapenv:Body>
</soapenv:Envelope>

🌍 Serviços de Geolocalização

ViaCepNominatimGeoDistanceService

Serviço para calcular distância entre CEPs usando APIs gratuitas (ViaCEP + Nominatim + OSRM).

Configuração
using Soap.ORS.Services;
using Soap.ORS.Interfaces;

// Configurar HttpClient
var httpClient = new HttpClient();

// O serviço configura automaticamente o User-Agent necessário
var geoService = new ViaCepNominatimGeoDistanceService(httpClient);
Exemplo de Uso - Distância entre CEPs
using Soap.ORS.Services;
using Soap.ORS.Interfaces;

// Criar serviço
var geoService = new ViaCepNominatimGeoDistanceService(new HttpClient());

// Calcular distância entre dois CEPs
try
{
    var distanceKm = await geoService.GetDistanceKmAsync(
        "86038672", // CEP origem (Londrina-PR)
        "86010190"  // CEP destino (Londrina-PR)
    );

    Console.WriteLine($"Distância: {distanceKm} km");
}
catch (Exception ex)
{
    Console.WriteLine($"Erro ao calcular distância: {ex.Message}");
}
Como Funciona
  1. Resolução de CEP: ViaCEP → Endereço completo
  2. Geocodificação: Nominatim → Coordenadas (lat/lng)
  3. Cálculo de Distância: OSRM (rota real) → Fallback Haversine (linha reta)
Exemplo de Resposta ViaCEP
{
  "cep": "86038-672",
  "logradouro": "Rua das Flores",
  "complemento": "",
  "bairro": "Centro",
  "localidade": "Londrina",
  "uf": "PR",
  "ibge": "4113700",
  "gia": "4145",
  "ddd": "43",
  "siafi": "7657"
}
Exemplo de Resposta Nominatim
[
  {
    "place_id": 123456,
    "licence": "Data © OpenStreetMap",
    "lat": "-23.3045",
    "lon": "-51.1628",
    "display_name": "Rua das Flores, Centro, Londrina, Paraná, Brasil",
    "type": "road"
  }
]

🔧 Exemplos Completos

Exemplo 1: Sistema Completo de Frete

using Soap.Shipping;
using Soap.ORS.Services;
using Soap.ORS.Interfaces;

public class ShippingService
{
    private readonly HttpClient _httpClient;
    private readonly IGeoDistanceService _geoService;

    public ShippingService()
    {
        _httpClient = new HttpClient();
        _geoService = new ViaCepNominatimGeoDistanceService(_httpClient);
    }

    public async Task<ShippingQuote> GetCompleteQuoteAsync(
        string originCep,
        string destinationCep,
        decimal weight,
        decimal declaredValue)
    {
        try
        {
            // 1. Calcular distância
            var distanceKm = await _geoService.GetDistanceKmAsync(originCep, destinationCep);

            // 2. Calcular frete
            var soapResponse = await ShippingCalculation.CalculateShippingAsync(
                originCep, destinationCep, weight, declaredValue, 
                "seu_usuario", "sua_senha"
            );

            var (deliveryTime, serviceValue) = ShippingCalculation.ExtractShippingData(soapResponse);

            return new ShippingQuote
            {
                OriginCep = originCep,
                DestinationCep = destinationCep,
                DistanceKm = distanceKm,
                DeliveryDays = int.Parse(deliveryTime),
                ShippingCost = decimal.Parse(serviceValue),
                TotalCost = decimal.Parse(serviceValue)
            };
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Erro ao calcular cotação completa", ex);
        }
    }
}

public class ShippingQuote
{
    public string OriginCep { get; set; }
    public string DestinationCep { get; set; }
    public decimal DistanceKm { get; set; }
    public int DeliveryDays { get; set; }
    public decimal ShippingCost { get; set; }
    public decimal TotalCost { get; set; }
}

Exemplo 2: Injeção de Dependência (ASP.NET Core)

// Program.cs
builder.Services.AddHttpClient<ViaCepNominatimGeoDistanceService>();
builder.Services.AddScoped<IGeoDistanceService, ViaCepNominatimGeoDistanceService>();
builder.Services.AddScoped<ShippingService>();

// Controller
[ApiController]
[Route("api/[controller]")]
public class ShippingController : ControllerBase
{
    private readonly ShippingService _shippingService;

    public ShippingController(ShippingService shippingService)
    {
        _shippingService = shippingService;
    }

    [HttpPost("quote")]
    public async Task<ActionResult<ShippingQuote>> GetQuote([FromBody] ShippingRequest request)
    {
        try
        {
            var quote = await _shippingService.GetCompleteQuoteAsync(
                request.OriginCep,
                request.DestinationCep,
                request.Weight,
                request.DeclaredValue
            );

            return Ok(quote);
        }
        catch (Exception ex)
        {
            return BadRequest(new { error = ex.Message });
        }
    }
}

⚠️ Tratamento de Erros

Exceções Comuns

try
{
    var distance = await geoService.GetDistanceKmAsync("123", "456");
}
catch (OrsGeocodingException ex)
{
    // Erro na geocodificação do CEP
    Console.WriteLine($"CEP inválido: {ex.Message}");
}
catch (OrsRoutingException ex)
{
    // Erro no cálculo de rota
    Console.WriteLine($"Erro de roteamento: {ex.Message}");
}
catch (HttpRequestException ex)
{
    // Erro de conexão
    Console.WriteLine($"Erro de rede: {ex.Message}");
}

Melhores Práticas

  • Sempre valide CEPs antes de enviar para a API
  • Implemente retry para chamadas de rede
  • Use timeout adequado para HttpClient
  • Logue erros para monitoramento
  • Cache resultados quando possível

🔐 Configuração de Ambiente

Variáveis de Ambiente

# .env
SHIPPING_USERNAME=seu_usuario_totalexpress
SHIPPING_PASSWORD=sua_senha_totalexpress
HTTP_TIMEOUT_SECONDS=30

Configuração de HttpClient

var httpClient = new HttpClient()
{
    Timeout = TimeSpan.FromSeconds(30)
};

httpClient.DefaultRequestHeaders.Add("User-Agent", "SeuApp/1.0");

📝 Notas Importantes

  • Rate Limiting: APIs gratuitas têm limites de requisição
  • User-Agent: Obrigatório para Nominatim
  • Fallback: Serviço usa Haversine se OSRM falhar
  • SOAP: Requer credenciais válidas do Total Express
  • Async: Todos os métodos são assíncronos

🤝 Contribuição

Contribuições são bem-vindas! Por favor:

  1. Fork o projeto
  2. Crie uma branch (git checkout -b feature/nova-funcionalidade)
  3. Commit suas mudanças (git commit -am 'Adiciona nova funcionalidade')
  4. Push para a branch (git push origin feature/nova-funcionalidade)
  5. Abra um Pull Request

📄 Licença

Este projeto está licenciado sob a Licença MIT. Veja o arquivo LICENSE para detalhes.

📞 Suporte


Desenvolvido com ❤️ por CodieDigital

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 114 4/2/2026
1.0.0 121 3/12/2026