Sindika.AspNet.Midtrans 1.1.1

dotnet add package Sindika.AspNet.Midtrans --version 1.1.1
                    
NuGet\Install-Package Sindika.AspNet.Midtrans -Version 1.1.1
                    
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="Sindika.AspNet.Midtrans" Version="1.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sindika.AspNet.Midtrans" Version="1.1.1" />
                    
Directory.Packages.props
<PackageReference Include="Sindika.AspNet.Midtrans" />
                    
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 Sindika.AspNet.Midtrans --version 1.1.1
                    
#r "nuget: Sindika.AspNet.Midtrans, 1.1.1"
                    
#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 Sindika.AspNet.Midtrans@1.1.1
                    
#: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=Sindika.AspNet.Midtrans&version=1.1.1
                    
Install as a Cake Addin
#tool nuget:?package=Sindika.AspNet.Midtrans&version=1.1.1
                    
Install as a Cake Tool

Sindika.AspNet.Midtrans

NuGet

A .NET library for integrating Midtrans payment gateway (Snap, Core API, and Iris) into ASP.NET Core applications. This package provides typed HTTP clients, middleware for webhook handling with automatic signature validation, and comprehensive support for Midtrans payment flows.

Features

  • Snap API - Create payment tokens and redirect URLs
  • Core API - Direct charge, transaction status, refund, cancel
  • Iris API - Disbursement and payout operations
  • Webhook Handler - Automatic signature validation and model binding
  • Middleware - Request buffering and logging for notifications
  • Options Pattern - Easy configuration with sandbox/production toggle
  • Typed Clients - Strongly-typed models for all API operations

Installation

Install via NuGet Package Manager:

dotnet add package Sindika.AspNet.Midtrans

Or via Package Manager Console:

Install-Package Sindika.AspNet.Midtrans

Quick Start

1. Configure Services

Add Midtrans configuration to appsettings.json:

{
  "Midtrans": {
    "ServerKey": "SB-Mid-server-xxxxxx",
    "ClientKey": "SB-Mid-client-xxxxxx",
    "IsProduction": false
  }
}

Register services in Program.cs:

using Sindika.AspNet.Midtrans.Core.Extensions;
using Sindika.AspNet.Midtrans.AspNetCore.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Register Midtrans services
builder.Services.AddMidtrans(options =>
{
    builder.Configuration.GetSection("Midtrans").Bind(options);
});

// Add controllers with Midtrans model binders
builder.Services.AddControllers().AddMidtrans();

var app = builder.Build();

// Enable Midtrans notification middleware
app.UseMidtransNotifications();
app.MapControllers();

app.Run();

2. Create Payment

using Sindika.AspNet.Midtrans.Core.Contracts;
using Sindika.AspNet.Midtrans.Core.Models.Request.Snap;
using Sindika.AspNet.Midtrans.Core.Models.Common;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/payment")]
public class PaymentController : ControllerBase
{
    private readonly IMidtransClient _midtrans;

    public PaymentController(IMidtransClient midtrans)
    {
        _midtrans = midtrans;
    }

    [HttpPost]
    public async Task<IActionResult> CreatePayment([FromBody] PaymentRequest request)
    {
        var snapRequest = new SnapTransactionRequest
        {
            TransactionDetails = new TransactionDetails
            {
                OrderId = $"ORDER-{Guid.NewGuid():N}",
                GrossAmount = request.Amount
            },
            CustomerDetails = new CustomerDetails
            {
                Email = request.Email,
                FirstName = request.Name
            }
        };

        var response = await _midtrans.Snap.CreateTransactionAsync(snapRequest);
        
        return Ok(new 
        { 
            token = response.Token,
            redirectUrl = response.RedirectUrl 
        });
    }
}

3. Handle Webhook Notifications

using Sindika.AspNet.Midtrans.AspNetCore.Filters;
using Sindika.AspNet.Midtrans.AspNetCore.ModelBinders;
using Sindika.AspNet.Midtrans.Core.Models.Notification;
using Sindika.AspNet.Midtrans.Core.Enums;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/webhooks/midtrans")]
public class WebhookController : ControllerBase
{
    private readonly ILogger<WebhookController> _logger;

    public WebhookController(ILogger<WebhookController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    [ValidateMidtransSignature]
    public IActionResult Handle(
        [ModelBinder(BinderType = typeof(MidtransNotificationBinder))] 
        MidtransNotification notification)
    {
        // Update order status in your database
        switch (notification.TransactionStatus)
        {
            case TransactionStatus.Settlement:
                _logger.LogInformation("Payment successful for order {OrderId}", notification.OrderId);
                // Mark order as paid
                break;
            case TransactionStatus.Pending:
                _logger.LogInformation("Payment pending for order {OrderId}", notification.OrderId);
                break;
            case TransactionStatus.Deny:
            case TransactionStatus.Cancel:
            case TransactionStatus.Expire:
                _logger.LogWarning("Payment failed for order {OrderId}", notification.OrderId);
                // Mark order as failed/cancelled
                break;
        }

        return Ok();
    }
}

Advanced Usage

Core API - Direct Charge

var chargeRequest = new ChargeRequest
{
    PaymentType = PaymentType.CreditCard,
    TransactionDetails = new TransactionDetails
    {
        OrderId = "ORDER-123",
        GrossAmount = 150000
    },
    CreditCard = new CreditCardChargeRequest
    {
        Card = new CreditCardDetails
        {
            TokenId = "token-from-frontend"
        }
    }
};

var response = await _midtrans.CoreApi.ChargeAsync(chargeRequest);

Check Transaction Status

var status = await _midtrans.CoreApi.GetTransactionStatusAsync("ORDER-123");
Console.WriteLine($"Status: {status.TransactionStatus}");

Refund Transaction

var refundRequest = new RefundRequest
{
    Amount = 150000,
    Reason = "Customer request"
};

await _midtrans.CoreApi.RefundAsync("ORDER-123", refundRequest);

Configuration Options

Option Description Default
ServerKey Midtrans server key (required) -
ClientKey Midtrans client key (required) -
IsProduction Use production environment false
SnapTimeout Snap API request timeout 30 seconds
CoreApiTimeout Core API request timeout 30 seconds
IrisTimeout Iris API request timeout 30 seconds

Testing with ngrok

For local webhook testing:

ngrok http 5000

Set the ngrok HTTPS URL as your notification URL in Midtrans dashboard:

https://xxxx-xx-xx-xx-xx.ngrok-free.app/api/webhooks/midtrans

Documentation

License

MIT License - see LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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.1 293 11/26/2025
1.1.0 197 11/25/2025
1.0.3 203 11/25/2025
1.0.2 418 11/20/2025
1.0.1 421 11/20/2025
1.0.0 421 11/20/2025