Skip to content
Chaidir Ali Assegaf
NoticesAll posts

Settling AX 2012 vendor invoices from outside AX: a custom AIF service for payment journals

AX 2012 has no standard service that creates vendor payments and settles invoices. Here's the custom AIF service behind a mobile app that does it, with the X++ and the .NET client.

Published
8 October 2026
Written by
Chaidir Ali Assegaf

In late 2023 I built AXFinMobile at PT Gandum Mas Kencana: a Flutter app and an ASP.NET Web API that let finance staff pay vendor invoices from a phone. They scan the QR code on each invoice, collect the invoices into a batch, and the API turns the batch into payment journals in Dynamics AX 2012 R2. The app cut manual entry by about 60%.

The interesting part sits inside AX. It's a custom AIF service that takes a list of invoice numbers and hands back unposted payment journals, with every invoice already marked for settlement.

The code below is a smaller rewrite of that service, with a Mob prefix and the same design. I checked every standard class, method and field it touches against the AX 2012 R2 source, and you can import the whole thing as one XPO (link at the end).

AX has no standard way in for vendor payments

AX 2012 ships 3 document services that come close:

  • LedgerGeneralJournalService creates general journals, but it has no settlement logic at all.
  • LedgerCustPaymJournalService creates customer payment journals and settles them. It has create and settlePayment.
  • LedgerVendorPaymentService only reads: find, findKeys, read, getKeys and getChangedKeys.

So customers get a settle operation and vendors get a read-only service. That gap is why I wrote my own.

The shape of a custom AIF service

In the AOT it's 4 pieces:

  • data contract classes for what goes in and comes out;
  • a service class, whose public methods become the operations;
  • a service node that lists those operations;
  • a service group, which is what you deploy.

Right-click the service group and pick Deploy Service Group. AX creates a basic inbound port with the same name. With the default ports, clients connect to net.tcp://<AOS>:8201/DynamicsAx/Services/MobVendPaymentServiceGroup, and the WSDL is at the same path on http://<AOS>:8101.

The request contract carries a journal name, a payment date, a description and the invoices. The list is where AIF gets fussy. A List member needs AifCollectionTypeAttribute twice, once for the parameter and once for the return value, so AIF knows what type to write into the WSDL:

[DataMemberAttribute('Invoices'),
 AifCollectionTypeAttribute('_invoices', Types::Class,
    classStr(MobVendInvoiceRef)),
 AifCollectionTypeAttribute('return', Types::Class,
    classStr(MobVendInvoiceRef))]
public List parmInvoices(List _invoices = invoices)
{
    invoices = _invoices;
    return invoices;
}

Each invoice in that list is just a vendor account and an invoice number:

// One invoice the app wants to pay: the vendor and the invoice
// number. No amount: AX works that out from the open balance.
[DataContractAttribute]
class MobVendInvoiceRef
{
    VendAccount     accountNum;
    VendInvoiceId   invoiceId;
}

Both operations also carry [SysEntryPointAttribute(true)]. The true makes AX check the caller's permissions on every call, which comes back to bite later (see the last section).

When deployment says "not a valid data member"

AIF checks data members harder than the compiler does. A parm method has to be public, take exactly one optional parameter, and return exactly that parameter's type, down to the same EDT. A str parameter on a method that returns Name compiles fine and still fails at deployment.

And if the code is right and it still fails, suspect stale CIL. What fixed it for me was clearing CIL properly: stop every AOS, truncate SysXppAssembly in the model database, empty XppIL on each AOS, then generate full CIL from one of them. Deleting XppIL alone isn't enough, because the AOS restores it from SysXppAssembly.

The app sends invoice numbers, AX does the math

Look at what the request doesn't have: amounts. The app says which invoices to pay and nothing about how much.

AX already knows each invoice's open balance and whatever cash discount applies. So the service marks the invoices and then asks AX what they add up to. The app can't send a wrong amount, because it never sends one.

One batch, one journal per vendor

A clerk can scan invoices from several vendors into a single batch. The service gives each vendor its own journal, so finance can review and post one vendor at a time.

To split the batch, I load it into a TempDB table and let SQL Server do the grouping:

[SysEntryPointAttribute(true),
 AifCollectionTypeAttribute('return', Types::Class,
    classStr(MobVendPaymentResult))]
public List settleVendorInvoices(
    MobVendSettlementRequest _request)
{
    LedgerJournalName   journalName;
    LedgerJournalTable  journal;
    LedgerJournalTrans  payment;
    MobVendInvoiceTmp   invoices;
    MobVendInvoiceTmp   vendors;
    VendAccount         vendAccount;
    List                results = new List(Types::Class);

    journalName = this.findPaymentJournalName(
        _request.parmJournalName());

    // One TempDB table, two buffers on the same rows: one walks
    // the vendors, the other finds each vendor's invoices.
    this.loadInvoices(_request.parmInvoices(), invoices);
    vendors.linkPhysicalTableInstance(invoices);

    ttsBegin;

    while select AccountNum from vendors
        group by AccountNum
    {
        vendAccount = vendors.AccountNum;

        journal = this.createJournal(
            journalName, vendAccount, _request.parmDescription());
        payment = this.createPaymentLine(
            journal, vendAccount, _request.parmTransDate());

        this.markInvoices(payment, invoices, vendAccount);
        this.setAmountFromMarks(payment);

        results.addEnd(
            this.buildResult(journal, payment, vendAccount));
    }

    ttsCommit;

    return results;
}

Two buffers point at the same rows through linkPhysicalTableInstance. The outer loop walks the vendors with group by, and markInvoices uses the other buffer to find each vendor's invoices.

Everything runs inside one ttsBegin/ttsCommit. If a single invoice fails, no vendor in the batch gets a journal, and the app gets the error instead.

The journal header

private LedgerJournalTable createJournal(
    LedgerJournalName   _journalName,
    VendAccount         _vendAccount,
    Name                _description)
{
    LedgerJournalTable journal;

    journal.initValue();
    journal.initFromLedgerJournalName(_journalName.JournalName);
    journal.JournalNum =
        JournalTableData::newTable(journal).nextJournalId();
    journal.Name = strFmt("%1 - %2", _vendAccount, _description);
    journal.insert();

    return journal;
}

initFromLedgerJournalName copies the journal name's settings onto the header: journal type, offset account, currency and voucher series. JournalTableData hands out the next journal number.

The payment line

private LedgerJournalTrans createPaymentLine(
    LedgerJournalTable  _journal,
    VendAccount         _vendAccount,
    TransDate           _transDate)
{
    LedgerJournalTrans  payment;
    LedgerJournalEngine engine;

    engine = LedgerJournalEngine::construct(_journal.JournalType);
    engine.newJournalActive(_journal);

    // initValue sets Company and the company currency.
    payment.initValue();
    payment.JournalNum      = _journal.JournalNum;
    payment.TransDate       = _transDate;
    payment.TransactionType = LedgerTransType::Payment;
    payment.Txt             = _journal.Name;

    // The header's series: it switches to temporary numbers
    // when the journal name allocates vouchers at posting.
    payment.Voucher = NumberSeq::newGetVoucherFromId(
        _journal.NumberSequenceTable).voucher();

    payment.OffsetAccountType = _journal.OffsetAccountType;
    payment.OffsetLedgerDimension =
        _journal.OffsetLedgerDimension;

    // The calls Microsoft's own AIF journal classes make after
    // setting an account. They fill in what the journal form
    // would: the vendor's currency, posting profile, method of
    // payment, bank account and default dimensions.
    payment.parmAccount(_vendAccount, LedgerJournalACType::Vend);
    payment.modifiedField(
        fieldNum(LedgerJournalTrans, LedgerDimension));
    engine.accountModified(payment);
    engine.currencyModified(payment);

    payment.insert();

    return payment;
}

2 things here are easy to get wrong.

The voucher comes from the header's number sequence. When a journal name allocates vouchers at posting, the header points at a temporary series, and the journal name's own series would bypass it.

Let AX fill the line the way the form does. After parmAccount, I call modifiedField on LedgerDimension and then accountModified on the journal engine. Microsoft's own AIF class for customer payment lines makes the same 2 calls after it sets the account. Together they bring in the vendor's currency, posting profile, method of payment, bank account and default dimensions. currencyModified then sets the exchange rate for whatever currency the vendor uses.

The offset account comes from the header, which copied it from the journal name.

Marking the invoices

This is the part the standard vendor service is missing. Marking means writing SpecTrans rows that tie the payment line to the vendor's open transactions. AX 2012 has a class that does it the same way the Settle transactions form does: CustVendOpenTransManager.

private void markInvoices(
    LedgerJournalTrans  _payment,
    MobVendInvoiceTmp   _invoices,
    VendAccount         _vendAccount)
{
    CustVendOpenTransManager    manager;
    VendTransOpen               vendTransOpen;
    VendTrans                   vendTrans;
    boolean                     found;

    // The same manager the Settle transactions form uses. It
    // writes the SpecTrans rows, takes cash discount into
    // account, and throws if another journal already marked
    // the transaction.
    manager = CustVendOpenTransManager::construct(_payment);

    while select Invoice from _invoices
        where _invoices.AccountNum == _vendAccount
    {
        found = false;

        // An invoice on a payment schedule has one open
        // transaction per instalment, so mark them all.
        // Prepayments stay out: updateTransMarked asks the user
        // to confirm those in a dialog box.
        while select vendTransOpen
            where vendTransOpen.AccountNum == _vendAccount
            join RecId from vendTrans
            where vendTrans.RecId == vendTransOpen.RefRecId
               && vendTrans.Invoice == _invoices.Invoice
               && vendTrans.Prepayment == NoYes::No
        {
            manager.updateTransMarked(vendTransOpen, NoYes::Yes);
            found = true;
        }

        if (!found)
        {
            throw error(strFmt(
                "Vendor %1 has no open balance on invoice %2.",
                _vendAccount, _invoices.Invoice));
        }
    }
}

updateTransMarked works out the cash discount the invoice qualifies for, writes the SpecTrans row for the amount after discount, and throws if another journal already marked the same transaction. That last check is one you'd otherwise have to write yourself.

Microsoft's own customer payment service takes a different road. The caller sends an amount, and AxdCustPaymJournal only calls SpecTransManager.insert when that amount matches the invoice after discount. The service here lets AX decide instead.

Two more details in that method:

  • Prepayments stay out of the query. For a prepayment, updateTransMarked asks for confirmation with Box::yesNo, and a service call has no user to click Yes.
  • An invoice on a payment schedule has one open transaction per instalment. The inner loop marks all of them, so the whole invoice gets paid.

Letting AX set the amount

private void setAmountFromMarks(LedgerJournalTrans _payment)
{
    AmountCur marked;

    marked =
        SpecTransManager::getTotalSettleAmountForSpecReference(
            _payment.DataAreaId,
            _payment.TableId,
            _payment.RecId,
            _payment.CurrencyCode,
            _payment.Company,
            _payment.TransDate);

    // Open vendor invoices carry negative amounts, so paying
    // them debits the vendor by the same amount.
    _payment.selectForUpdate(true);
    _payment.amountCur2DebCred(-marked);
    _payment.SettleVoucher = SettlementType::SelectedTransact;
    _payment.update();
}

getTotalSettleAmountForSpecReference adds up everything marked against the line, converted into the line's currency. It's the same call AX's payment proposal makes when it moves proposal lines into a journal (CustVendPaymProposalTransferToJournal).

Watch the sign. Open vendor invoices carry negative amounts, so the total comes back negative, and amountCur2DebCred(-marked) turns it into a debit on the vendor. A credit note in the same batch simply reduces the total.

SettleVoucher = SelectedTransact tells posting to settle exactly the marked transactions. Then the service stops. The journal stays unposted, and finance reviews it in AX and posts it themselves.

One ordering rule: build the response after this update. buildResult reads the line's amount, and before setAmountFromMarks runs, that amount is still zero.

Errors: let AX's message reach the app

Every failure in the service is either a throw error(...) or an exception from AX's own code. The transaction rolls back, AIF writes the infolog to its Exceptions log, and the client gets a fault.

There's a catch. By default the fault only says the request failed and points at the exception log. To get the real message out, open the inbound port and tick Include exceptions in fault on the Troubleshooting FastTab. It's the port's PropagateErrors flag; AifRequestProcessor.handleProcessingException swaps in the generic message when it's off.

With it on, "Vendor V-1001 has no open balance on invoice INV-881" reaches the API word for word, ready to pass on to the phone.

The read side

The app also needs a list of what can be paid:

[SysEntryPointAttribute(true),
 AifCollectionTypeAttribute('return', Types::Class,
    classStr(MobOpenVendInvoice))]
public List getOpenVendorInvoices(VendAccount _vendAccount)
{
    List                openInvoices = new List(Types::Class);
    MobOpenVendInvoice  openInvoice;
    VendTransOpen       vendTransOpen;
    VendTrans           vendTrans;
    SpecTrans           specTrans;

    // The notExists join hides anything already marked on
    // another journal, so two people can't pick the same invoice.
    while select AmountCur, DueDate from vendTransOpen
        where vendTransOpen.AccountNum == _vendAccount
        join Invoice, TransDate from vendTrans
            where vendTrans.RecId      == vendTransOpen.RefRecId
               && vendTrans.Invoice    != ''
               && vendTrans.Prepayment == NoYes::No
        notExists join specTrans
            where specTrans.RefCompany == vendTransOpen.DataAreaId
               && specTrans.RefTableId == tableNum(VendTransOpen)
               && specTrans.RefRecId   == vendTransOpen.RecId
    {
        openInvoice = new MobOpenVendInvoice();
        openInvoice.parmAccountNum(_vendAccount);
        openInvoice.parmInvoiceId(vendTrans.Invoice);
        openInvoice.parmTransDate(vendTrans.TransDate);
        openInvoice.parmDueDate(vendTransOpen.DueDate);
        openInvoice.parmAmountCur(vendTransOpen.AmountCur);
        openInvoices.addEnd(openInvoice);
    }

    return openInvoices;
}

The notExists join on SpecTrans hides every transaction that's already marked on some journal. An invoice sitting in an unposted journal drops off the list, so 2 people can't pick it at the same time. If the mark is removed, it comes back.

Calling it from modern .NET

AIF speaks WCF, and our API ran on .NET 7 and later .NET 8. I generated the client with dotnet-svcutil pointed at the WSDL, and the binding comes from the System.ServiceModel.NetTcp package.

var binding = new NetTcpBinding(SecurityMode.Transport)
{
    MaxReceivedMessageSize = 2_000_000
};
binding.Security.Transport.ClientCredentialType =
    TcpClientCredentialType.Windows;

var endpoint = new EndpointAddress(
    new Uri("net.tcp://ax-aos:8201/DynamicsAx/Services/"
        + "MobVendPaymentServiceGroup"),
    new UpnEndpointIdentity("svc-aos@corp.example"));

var client = new MobVendPaymentServiceClient(binding, endpoint);
var context = new CallContext { Company = "USMF" };

var request = new MobVendSettlementRequest
{
    JournalName = "VendPay",
    TransDate = DateTime.Today,
    Description = "Batch 2024-0117",
    Invoices = new[]
    {
        Invoice("V-1001", "INV-881"),
        Invoice("V-1001", "INV-902"),
        Invoice("V-2040", "SI/0457")
    }
};

try
{
    var reply = await client.settleVendorInvoicesAsync(
        context, request);
    foreach (var journal in reply.response)
    {
        Console.WriteLine($"{journal.AccountNum}: "
            + $"{journal.JournalNum} {journal.AmountCur:N2}");
    }
}
catch (FaultException<AifFault> fault)
{
    var lines = fault.Detail.InfologMessageList?
        .Select(m => m.Message).ToArray();
    Console.WriteLine(lines is { Length: > 0 }
        ? string.Join(Environment.NewLine, lines)
        : fault.Message);
}
finally
{
    await client.CloseAsync();
}

static MobVendInvoiceRef Invoice(string vendor, string number) =>
    new() { AccountNum = vendor, InvoiceId = number };

4 settings matter:

  • Transport security with Windows credentials. The API authenticates to the AOS as its own Windows account.
  • UpnEndpointIdentity names the account the AOS service runs as, so the Windows handshake can authenticate the server side too.
  • CallContext.Company picks the legal entity the journals go into.
  • FaultException<AifFault> carries AX's error once the port lets it through: the infolog lines in InfologMessageList when they're there, and the last error in Message.

What I'd change

Make a retry return the first answer. Phones drop connections. If the API sends the same batch twice, the second call hits invoices the first one already marked, updateTransMarked throws, and the app shows an error for a batch that went through. I'd store the request's key next to the journal in AX and, when the same key comes back, return the journals that already exist. An idempotency key kept in the API's memory disappears on every restart, so it belongs in a database.

Fail when an invoice has nothing left to pay. If someone settles an invoice in AX between the scan and the submit, the lookup finds no open transaction. Without a check, you get a payment line for zero that looks perfectly normal. The example throws instead.

Decide early who AX thinks is calling. Every call runs as the API's service account, so AX's created-by fields name the service, and the person who scanned the invoices only exists in the API's own database. CallContext.LogonAsUser makes AX run the call as a named user. I haven't wired it up myself, so prove it on a test AOS first.

Give the service account a small role from day one. With SysEntryPointAttribute(true), AX checks the caller's rights to the operation and to every table the code touches. That includes the tables standard classes reach on your behalf, like number sequences and dimensions. If the account starts out with broad rights, you meet every one of those checks on the same day, the day someone narrows them.

Everything that knows how to pay a vendor already ships with AX 2012: the marking manager, the settle-amount helper, the journal engine and its vendor defaults. The custom service only connects them to the outside world.

Download the example as one XPO (a TempDB table, 4 data contracts, the service class, the service and the service group). Import it into a development environment, compile it, generate incremental CIL, and deploy MobVendPaymentServiceGroup.