AbpExt.WhatsApp.Core 1.0.5

AbpExt.WhatsApp.Core

NuGet Version NuGet Downloads License: MIT

An ABP Framework extension for WhatsApp integration using Evolution API. This package provides a simple service interface and optional QR code scanning UI for WhatsApp Business operations.

Features

  • 🚀 Simple Integration: Easy-to-use service interface with FluentResults pattern
  • 📱 QR Code UI: Built-in Razor page for QR code scanning at /AbpExt/WhatsApp/Core
  • 🏢 Multi-tenant Support: Automatic tenant isolation using ABP's multi-tenancy
  • 🌐 Localization: Comprehensive localization support with error messages
  • 🔒 Type Safety: Full C# type safety with comprehensive DTOs
  • 📋 Logging: Integrated logging with privacy-conscious phone number masking
  • HttpClient: Proper HttpClient management using HttpClientFactory
  • 🎯 Evolution API: Built specifically for Evolution API v1.x

Quick Start

1. Install Package

Install via NuGet Package Manager:

dotnet add package AbpExt.WhatsApp.Core

Or via Package Manager Console:

Install-Package AbpExt.WhatsApp.Core

2. Add Module Dependency

Add WhatsApp services to your ABP module:

[DependsOn(typeof(AbpExtWhatsAppCoreModule))]
public class YourApplicationModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();
        
        // Add WhatsApp services
        context.Services.AddWhatsApp(options =>
        {
            options.BaseUri = "https://your-evolution-api.com";
            options.ApiKey = "your-api-key";
            options.DefaultInstanceName = "default";
        });
        
        // Or bind from configuration
        context.Services.AddWhatsApp(configuration.GetSection("WhatsApp"));
    }
}

3. Add Configuration

Add to your appsettings.json:

{
  "WhatsApp": {
    "BaseUri": "https://your-evolution-api.com",
    "ApiKey": "your-evolution-api-key",
    "DefaultInstanceName": "default",
    "TimeoutSeconds": 30,
    "EnableDetailedLogging": false
  }
}

4. Use the Service

Inject and use IWhatsAppService in your application:

public class MessageService : ITransientDependency
{
    private readonly IWhatsAppService _whatsAppService;
    
    public MessageService(IWhatsAppService whatsAppService)
    {
        _whatsAppService = whatsAppService;
    }
    
    public async Task<bool> SendWelcomeMessage(string phoneNumber)
    {
        var result = await _whatsAppService.SendTextMessageAsync(
            phoneNumber, 
            "Welcome to our service!");
            
        return result.IsSuccess;
    }
    
    public async Task<bool> IsConnected()
    {
        var stateResult = await _whatsAppService.GetInstanceStateAsync();
        return stateResult.IsSuccess && stateResult.Value == "open";
    }
}

5. Access QR Code UI

Navigate to /AbpExt/WhatsApp/Core in your application to scan QR codes and manage WhatsApp connections.

API Reference

IWhatsAppService

The main service interface for WhatsApp operations:

public interface IWhatsAppService
{
    /// <summary>
    /// Sends a text message to the specified phone number
    /// </summary>
    Task<Result> SendTextMessageAsync(string phoneNumber, string message);
    
    /// <summary>
    /// Gets the current connection state of the WhatsApp instance
    /// </summary>
    Task<Result<string>> GetInstanceStateAsync();
    
    /// <summary>
    /// Initiates connection to WhatsApp instance and returns QR code if needed
    /// </summary>
    Task<Result<WhatsAppInstanceDto>> ConnectInstanceAsync();
    
    /// <summary>
    /// Checks if a WhatsApp instance exists for the current tenant
    /// </summary>
    Task<Result<bool>> CheckIfInstanceExistsAsync();
    
    /// <summary>
    /// Logs out and disconnects the current WhatsApp instance
    /// </summary>
    Task<Result> LogoutAsync();
}

WhatsAppOptions

Configuration options for the WhatsApp service:

public class WhatsAppOptions
{
    [Required]
    [Url]
    public string BaseUri { get; set; } = string.Empty;
    
    [Required]
    [MinLength(1)]
    public string ApiKey { get; set; } = string.Empty;
    
    public string DefaultInstanceName { get; set; } = "default";
    
    public int TimeoutSeconds { get; set; } = 30;
    
    public bool EnableDetailedLogging { get; set; } = false;
}

Connection States

The service returns these connection states:

  • "open" - Connected and ready to send messages
  • "close" - Disconnected
  • "connecting" - Currently connecting
  • "qrCodeRead" - QR code has been scanned

Usage Examples

Basic Message Sending

public async Task SendNotification(string phoneNumber, string message)
{
    var result = await _whatsAppService.SendTextMessageAsync(phoneNumber, message);
    
    if (result.IsSuccess)
    {
        _logger.LogInformation("Message sent successfully");
    }
    else
    {
        _logger.LogError("Failed to send message: {Errors}", 
            string.Join(", ", result.Errors.Select(e => e.Message)));
    }
}

Connection Management

public async Task<string> GetConnectionStatus()
{
    var result = await _whatsAppService.GetInstanceStateAsync();
    
    return result.IsSuccess 
        ? $"Connection state: {result.Value}"
        : $"Error: {result.Errors.FirstOrDefault()?.Message}";
}

public async Task<string> ConnectToWhatsApp()
{
    var result = await _whatsAppService.ConnectInstanceAsync();
    
    if (result.IsSuccess)
    {
        var instance = result.Value;
        if (instance.IsOpen)
        {
            return "Already connected";
        }
        else if (!string.IsNullOrEmpty(instance.QrCode))
        {
            return $"QR Code: {instance.QrCode}";
        }
        else
        {
            return "Connecting...";
        }
    }
    
    return $"Error: {result.Errors.FirstOrDefault()?.Message}";
}

Error Handling

The package uses FluentResults for comprehensive error handling:

var result = await _whatsAppService.SendTextMessageAsync(phoneNumber, message);

if (result.IsFailed)
{
    foreach (var error in result.Errors)
    {
        _logger.LogError("WhatsApp error: {Error}", error.Message);
    }
    
    // Check for specific error types
    if (result.Errors.Any(e => e.Message.Contains("not connected")))
    {
        // Handle connection issues
        await _whatsAppService.ConnectInstanceAsync();
    }
}

Multi-tenancy

The package fully supports ABP's multi-tenancy:

  • Each tenant gets a separate WhatsApp instance
  • Instance names are automatically tenant-isolated
  • Configuration can be tenant-specific
  • QR codes are tenant-specific

Localization

The package includes comprehensive localization support. Override messages by adding to your localization resources:

{
  "Error:ConnectionFailed": "Unable to connect to WhatsApp service",
  "Error:MessageSendFailed": "Failed to send WhatsApp message",
  "QrCode:Title": "WhatsApp QR Code Scanner",
  "Success:MessageSent": "Message sent successfully"
}

Security Considerations

  • API keys are never logged
  • Phone numbers are masked in logs
  • All HTTP requests use secure headers
  • Input validation on all parameters
  • Proper error handling without information disclosure

Requirements

  • .NET 7.0 or later
  • ABP Framework 7.3.0 or later
  • Evolution API v1.x

Dependencies

  • Volo.Abp.Core (>= 7.3.0)
  • Volo.Abp.AspNetCore.Mvc.UI (>= 7.3.0)
  • Volo.Abp.MultiTenancy (>= 7.3.0)
  • FluentResults (>= 3.15.2)
  • Microsoft.Extensions.Http (>= 7.0.0)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support and questions:

  • Create an issue on GitHub
  • Check the documentation
  • Review the examples above

Changelog

v1.0.0

  • Initial release
  • Basic WhatsApp integration
  • QR code scanning UI
  • Multi-tenant support
  • Comprehensive error handling
  • Localization support

No packages depend on AbpExt.WhatsApp.Core.

Initial release of AbpExt.WhatsApp.Core: - WhatsApp integration using Evolution API - Simple service interface with FluentResults pattern - Built-in QR code scanning UI - Multi-tenant support - Comprehensive error handling and localization - Privacy-conscious logging

Version Downloads Last updated
1.0.5 6 08/04/2025