AS2 Messages

AS2 messages are the core of secure B2B document exchange. AS2aaS handles all aspects of AS2 message processing including encryption, digital signing, compression, and delivery confirmation for both sending and receiving messages.

Message Overview

AS2aaS provides comprehensive bidirectional message processing:

  • Outbound Messages - Send AS2 messages to trading partners
  • Inbound Messages - Receive AS2 messages from trading partners
  • Content Agnostic - Support for EDI, XML, JSON, and binary content
  • Security - Automatic encryption and digital signing
  • Compression - Optional payload compression for efficiency
  • Delivery Confirmation - MDN (Message Disposition Notification) handling
  • Status Tracking - Real-time visibility into message lifecycle

Sending Messages

Send AS2 Message

POST /v1/messages

Request (JSON payload):

{
  "partner_id": "prt_000001",
  "subject": "Invoice #12345",
  "payload": {
    "content": "ISA*00*          *00*          *ZZ*SENDER         *ZZ*RECEIVER       *240115*1030*U*00401*000000001*0*T*>~"
  },
  "content_type": "application/edi-x12",
  "mdn_mode": "async"
}

Request (File upload):

curl -X POST https://api.as2aas.com/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "partner_id=prt_000001" \
  -F "subject=Invoice #12345" \
  -F "[email protected]" \
  -F "content_type=application/edi-x12"

Response (202):

{
  "message": "Message queued for delivery",
  "data": {
    "id": "msg_000001",
    "message_id": "MSG_20240115_103000_ABC123",
    "partner": {
      "id": "prt_000001",
      "name": "Acme Corp",
      "as2_id": "ACME-CORP-AS2"
    },
    "status": "queued",
    "direction": "outbound",
    "subject": "Invoice #12345",
    "content_type": "application/edi-x12",
    "bytes": 1024,
    "mdn_mode": "async",
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Message Parameters

Required Fields:

  • partner_id (string) - Trading partner identifier
  • payload.content (string) or file (file) - Message content
  • content_type (string) - MIME type

Optional Fields:

  • subject (string) - Message subject line
  • mdn_mode (string) - sync, async, or none
  • compress (boolean) - Override partner compression setting
  • encrypt (boolean) - Override partner encryption setting
  • sign (boolean) - Override partner signing setting

Receiving Messages

AS2 Receiving Endpoint

AS2 Endpoint: https://as2.as2aas.com/as2/receive

Automatic Message Processing

When partners send messages to your AS2 endpoint:

  1. Message Reception - AS2 protocol handling
  2. Security Processing - Decryption and signature verification
  3. Payload Extraction - Business document extraction
  4. Storage - Secure payload storage
  5. MDN Generation - Automatic delivery confirmation
  6. Webhook Notification - Real-time event delivery

Configure Partners to Send to You

Provide trading partners with:

AS2 URL: https://as2.as2aas.com/as2/receive
AS2-To: YOUR_AS2_ID (from your dashboard)
MDN URL: https://as2.as2aas.com/as2/mdn (for async MDNs)

Inbound Message Webhook

{
  "event": "message.received",
  "data": {
    "id": "msg_000002", 
    "message_id": "PARTNER_MSG_20240115_103100_XYZ789",
    "partner": {
      "id": "prt_000001",
      "name": "Acme Corp",
      "as2_id": "ACME-CORP-AS2"
    },
    "status": "received",
    "direction": "inbound",
    "from_as2_id": "ACME-CORP-AS2",
    "to_as2_id": "YOUR-AS2-ID",
    "subject": "Purchase Order #67890",
    "content_type": "application/edi-x12",
    "bytes": 2048,
    "encrypted": true,
    "signed": true,
    "mdn_requested": true,
    "received_at": "2024-01-15T10:31:00Z"
  },
  "timestamp": "2024-01-15T10:31:00Z"
}

List Messages

Get All Messages

GET /v1/messages

Query Parameters:

  • partner_id (string) - Filter by partner
  • status (string) - Filter by status: queued, sent, delivered, failed, received
  • direction (string) - Filter by direction: inbound, outbound
  • from_date (string) - ISO 8601 date
  • to_date (string) - ISO 8601 date
  • search (string) - Search subjects or message IDs
  • content_type (string) - Filter by content type
  • page (integer) - Page number
  • per_page (integer) - Items per page (max 100)

Response (200):

{
  "data": [
    {
      "id": "msg_000001",
      "message_id": "MSG_20240115_103000_ABC123",
      "partner": {
        "id": "prt_000001",
        "name": "Acme Corp",
        "as2_id": "ACME-CORP-AS2"
      },
      "status": "delivered",
      "direction": "outbound",
      "subject": "Invoice #12345",
      "content_type": "application/edi-x12",
      "bytes": 1024,
      "sent_at": "2024-01-15T10:30:15Z",
      "delivered_at": "2024-01-15T10:30:45Z",
      "created_at": "2024-01-15T10:30:00Z"
    }
  ],
  "pagination": {
    "current_page": 1,
    "last_page": 5,
    "per_page": 20,
    "total": 100
  }
}

Message Details

Get Message

GET /v1/messages/{message_id}

Response (200):

{
  "data": {
    "id": "msg_000001",
    "message_id": "MSG_20240115_103000_ABC123",
    "partner": {
      "id": "prt_000001",
      "name": "Acme Corp",
      "as2_id": "ACME-CORP-AS2",
      "url": "https://acme.example.com/as2"
    },
    "status": "delivered",
    "direction": "outbound",
    "from_as2_id": "YOUR-AS2-ID",
    "to_as2_id": "ACME-CORP-AS2",
    "subject": "Invoice #12345",
    "content_type": "application/edi-x12",
    "bytes": 1024,
    "compressed": false,
    "encrypted": true,
    "signed": true,
    "mdn_mode": "async",
    "mdn_status": "received",
    "mdn_data": {
      "disposition": "automatic-action/MDN-sent-automatically; processed",
      "received_content_mic": "abc123def456...",
      "reporting_ua": "Acme AS2 Server/1.0",
      "original_message_id": "MSG_20240115_103000_ABC123"
    },
    "attempts": 1,
    "last_attempt_at": "2024-01-15T10:30:15Z",
    "sent_at": "2024-01-15T10:30:15Z",
    "delivered_at": "2024-01-15T10:30:45Z",
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:45Z"
  }
}

Download Message Payload

GET /v1/messages/{message_id}/payload

Response: Returns the original message content with appropriate Content-Type header.

Message Validation

Validate Message Format

POST /v1/messages/validate

Request (multipart/form-data):

curl -X POST https://api.as2aas.com/v1/messages/validate \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "[email protected]" \
  -F "validation_type=format"

Response (200):

{
  "valid": true,
  "format": "edi-x12",
  "version": "004010",
  "document_type": "850",
  "issues": [],
  "summary": "Valid X12 850 Purchase Order document"
}

Testing Messages

Send Test Message

POST /v1/messages/test

Request:

{
  "partner_id": "prt_000001",
  "message_type": "test",
  "encrypt": true,
  "sign": true,
  "request_mdn": true
}

Response (200):

{
  "success": true,
  "message": "Test message sent successfully",
  "data": {
    "message_id": "TEST_20240115_103000_ABC123",
    "status": "sent",
    "timeline": [
      {
        "step": "Preparing test payload",
        "status": "success",
        "timestamp": "2024-01-15T10:30:00Z"
      },
      {
        "step": "Validating partner configuration", 
        "status": "success",
        "timestamp": "2024-01-15T10:30:01Z"
      },
      {
        "step": "Sending AS2 message",
        "status": "success", 
        "timestamp": "2024-01-15T10:30:05Z"
      }
    ]
  }
}

Message Status Codes

StatusDescription
queuedMessage accepted and queued for processing
processingMessage preparation in progress
sentMessage successfully transmitted to partner
deliveredMDN received confirming delivery
failedTransmission failed with error details
receivedInbound message received from partner

Content Types

Supported MIME Types

Content TypeDescriptionUse Cases
application/edi-x12X12 EDI documentsPurchase orders, invoices, ASNs
application/edifactEDIFACT documentsInternational EDI
application/xmlXML business documentsCustom XML formats
application/jsonJSON documentsModern API integration
text/plainPlain text filesSimple document exchange
application/pdfPDF documentsReports, certificates
text/csvCSV filesData exports
application/zipCompressed archivesMultiple document bundles

Message Size Limits

PlanMax Message Size
Free50 MB
Starter100 MB
Professional500 MB
EnterpriseCustom (up to 2 GB)

Security Features

Encryption

  • Algorithms: AES128_CBC, AES192_CBC, AES256_CBC, 3DES
  • Certificate-based: Uses partner's public key for encryption
  • Automatic: Applied based on partner configuration

Digital Signing

  • Algorithms: SHA1withRSA, SHA256withRSA, SHA384withRSA, SHA512withRSA
  • Certificate-based: Uses your private key for signing
  • Non-repudiation: Provides proof of message origin

Compression

  • Algorithm: ZLIB compression
  • Automatic: Applied based on partner preferences
  • Efficiency: Reduces message size for faster transmission

Error Codes

Transmission Errors

Error CodeDescriptionResolution
PARTNER_UNREACHABLECannot connect to partner endpointCheck partner URL and network connectivity
CERTIFICATE_EXPIREDSigning/encryption certificate expiredUpdate certificate in dashboard
INVALID_SIGNATUREPartner rejected message signatureVerify signing certificate configuration
MESSAGE_TOO_LARGEMessage exceeds partner's size limitReduce message size or use compression
TIMEOUTPartner did not respond within timeoutCheck partner system status
INVALID_AS2_IDPartner AS2 ID mismatchVerify AS2 ID configuration

Processing Errors

Error CodeDescriptionResolution
INVALID_PAYLOADMalformed message contentValidate payload format
COMPRESSION_FAILEDCannot compress messageCheck payload content
ENCRYPTION_FAILEDCannot encrypt messageVerify partner's encryption certificate
SIGNING_FAILEDCannot sign messageCheck your signing certificate

Integration Examples

Basic Message Sending

const as2 = require('as2aas')('pk_test_your_api_key');

// Send EDI purchase order
const message = await as2.messages.create({
  partner: 'acme-corp',
  subject: 'Purchase Order #PO-2024-001',
  payload: {
    content: ediContent,
    filename: 'po-2024-001.edi'
  },
  contentType: 'application/edi-x12'
});

console.log('Message sent:', message.id);

Processing Received Messages

// Webhook handler for incoming messages
app.post('/webhooks/as2', async (req, res) => {
  const { event, data } = req.body;
  
  if (event === 'message.received') {
    // Download payload
    const payload = await as2.messages.getPayload(data.id);
    
    // Process based on content type
    switch (data.content_type) {
      case 'application/edi-x12':
        await processEDI(payload, data);
        break;
      case 'application/xml':
        await processXML(payload, data);
        break;
    }
  }
  
  res.status(200).send('OK');
});

Batch Message Processing

// Send multiple messages efficiently
const messages = [
  { partner: 'partner-1', payload: edi1 },
  { partner: 'partner-2', payload: edi2 },
  { partner: 'partner-3', payload: edi3 }
];

const results = await Promise.allSettled(
  messages.map(msg => as2.messages.create(msg))
);

// Handle results
results.forEach((result, index) => {
  if (result.status === 'fulfilled') {
    console.log(`Message ${index + 1} sent:`, result.value.id);
  } else {
    console.error(`Message ${index + 1} failed:`, result.reason);
  }
});

Error Handling

try {
  const message = await as2.messages.create({
    partner: 'unreachable-partner',
    payload: { content: ediContent },
    contentType: 'application/edi-x12'
  });
} catch (error) {
  switch (error.code) {
    case 'PARTNER_NOT_FOUND':
      console.log('Partner not configured');
      break;
    case 'PAYLOAD_TOO_LARGE':
      console.log('Message too large, try compression');
      break;
    case 'RATE_LIMITED':
      console.log('Rate limited, retry after delay');
      break;
    default:
      console.error('Unexpected error:', error.message);
  }
}

Message Monitoring

Real-time Status Updates

// Poll for message status updates
async function waitForDelivery(messageId) {
  let status = 'queued';
  
  while (status !== 'delivered' && status !== 'failed') {
    await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds
    
    const message = await as2.messages.get(messageId);
    status = message.status;
    
    console.log(`Message ${messageId} status: ${status}`);
    
    if (status === 'delivered') {
      console.log('MDN received:', message.mdn_data);
    } else if (status === 'failed') {
      console.error('Delivery failed:', message.error_message);
    }
  }
}

Usage Analytics

GET /v1/messages/analytics

Query Parameters:

  • period (string) - last_7_days, last_30_days, last_90_days
  • partner_id (string) - Filter by specific partner
  • direction (string) - inbound, outbound, or both

Response:

{
  "data": {
    "period": "last_30_days",
    "total_messages": 1250,
    "outbound_messages": 800,
    "inbound_messages": 450,
    "success_rate": 99.2,
    "avg_delivery_time_seconds": 12.5,
    "by_partner": [
      {
        "partner_id": "prt_000001",
        "partner_name": "Acme Corp",
        "outbound": 400,
        "inbound": 200,
        "success_rate": 99.5
      }
    ],
    "by_status": {
      "delivered": 1235,
      "failed": 10,
      "processing": 5
    }
  }
}

Advanced Features

Message Priorities

{
  "partner_id": "prt_000001",
  "priority": "high",
  "payload": { "content": "..." },
  "content_type": "application/edi-x12"
}

Priority levels:

  • low - Processed during off-peak hours
  • normal - Standard processing (default)
  • high - Priority processing queue

Custom Headers

{
  "partner_id": "prt_000001", 
  "payload": { "content": "..." },
  "headers": {
    "Document-Type": "PurchaseOrder",
    "Document-ID": "PO-2024-001",
    "Business-Unit": "Procurement"
  }
}

Message Scheduling

{
  "partner_id": "prt_000001",
  "payload": { "content": "..." },
  "scheduled_at": "2024-01-16T09:00:00Z"
}

Troubleshooting

Common Issues

Message Stuck in 'queued' Status

  • Check partner endpoint accessibility
  • Verify partner certificates are valid
  • Review partner configuration settings

MDN Not Received

  • Verify partner supports MDN
  • Check MDN endpoint configuration
  • Review partner's MDN implementation

Large Message Failures

  • Enable compression
  • Check partner's size limits
  • Consider splitting large documents

Debug Information

GET /v1/messages/{message_id}/debug

Returns detailed processing logs and error information for troubleshooting.

Getting Help

For message delivery issues:

  1. Check message logs in your dashboard
  2. Use testing tools to reproduce issues
  3. Review partner configuration for mismatches
  4. Contact support with message ID for investigation