PUT Commit a Transaction

PUT /payout/v1/transactions/{transactionId}/commit

Development Guide

The 'Commit a Transaction API' executes the transactionId and completes the payout of funds.


1. Prepare headers, authentication & parameters:

The application must call the 'Commit a Transaction'endpoint with a PUT HTTP method, providing the OAuth access_token , the transactionId as a path parameter and all other required headers.


Note:

  • MoneyGram uses the OAuth 2.0 framework. The application must use their OAuth client credentials to generate an access_token by calling the Get Access Token endpoint. The token is valid for 1 hour and must be passed as a header value in all subsequent API HTTP calls. Learn More
  • The transactionId should have been returned on the previous Retrieve a Tansaction endpoint response.

🚀

Launch Code Example:




2. Provide payoutId in the request body:

To Update a Transaction, it is required to pass the refundId which was returned on the previous Retrieve a Transaction API response and all other required fields.


🚀

Launch Code Example:




3. Make a request and handle the response:

The application must call the 'Update a transaction' endpoint with a PUT HTTP method and be able to handle the following response scenarios:


  • Success | Parse the Response | 200 OK HTTP Status
    When the 'Commit a transaction' endpoint responds with a 200 HTTP Status the application will have finalized and executed the Payout and the response will return the referenceNumber. The funds are marked for "settlement" on the MoneyGram ledger.

  • Failed | Handle the Error | 400 Bad Request HTTP Status
    When the 'Commit a Transaction' endpoint responds with 400 HTTP Status, specific error codes will be returned with an array of offending fields. The application will need to resolve these errors and resubmit the transaction for validation.

Note:

  • In some scenario's, enhanced due diligence is need to be undertaken on the consumer. A specific error code will be returned and an array of offending fields. The fields/values need to be provided and resubmitted on the Update API for further checks
  • In some cases, send or receive side taxes may be applied. Learn More
  • Only when the "readyForCommit": true, is returned can the application proceed to "Commit a Transaction" API and execute the payout of funds.

🚀

Launch Code Example:

.




4. You're Done! Payout the transaction and provide a receipt:

The application is recommended to display the referenceNumber clearly on the UI or a notification to customer. A receipt most be printed and handed to the customer.





Business Rules to Code:


🔎

  1. Idempotent: If the application does not receive a response from the Commit a Transaction API within 10-40 seconds, the application must send the request again. This must be retried up to 3 times. If the retry attempt fails, check the transactionStatus using the Status API to confirm if transaction was successful.

  2. Error Code 935: If error code 935 internal system error is returned on commit, it must be handled the same way as if the commit response is not received (see item 2).

  3. Handling Errors: Other errors can be returned on commit a transaction stopping the transaction. The application must handle scenarios where the transaction fails (an error code is returned) on commit. Learn More

  4. Receipts: Refer to Receipts module for detailed information and requirements for receipts. Learn More

  5. Reference Number Recycling policy: MoneyGram will recycle the reference numbers after the transactions have been closed/received for 4 to 6 months. If you are storing reference numbers in your database, you should also store the transaction date. The combination of the reference number and transaction date will be the unique key for a transaction.



Code Examples


const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

const commitTransaction = async () => {

    // Step 1: Read configuration values with upmost security
    const token = "your_access_token_from_oauth_response"
    // For production - api.moneygram.com & For test - sandboxapi.moneygram.com
    const transactionId = "current_transaction_id";
    const host = "sandboxapi.moneygram.com";
    const url = 'https://' + host + '/payout/v1/transactions/' + transactionId + '/commit';

    // Step 2: Create the PUT request headers & body

    const headers = {
        'Content-Type': 'application/json',
        'X-MG-ClientRequestId': uuidv4(), // New UUID for each request tracing
        'Authorization': 'Bearer ' + token,
    };

    const params = {
        agentPartnerId: "your_partner_id",
        targetAudience: "AGENT_FACING",
        userLanguage: "en-US"
    }

    const request = {
        payoutId: "current_payout_id", // generated during the retrieve transaction
        partnerTransactionId: "partner_transaction_id", //optional
    }

    try {
        // Step 3: Send the request and obtain the response
        axios.put(url, request, { params, headers })
            .then(function (response) {
                // Step 4: Parse the success response and process further
                console.log(JSON.stringify(response.data, null, 2))
            })
            .catch(function (error) {
                // Step 5: Parse the error response and handle the errors
                if (error.response) {
                    console.log('Response status:', error.response.status);
                    console.log('Response body:', error.response.data);
                } else {
                    // TODO: handle generic errors
                    console.error('Error:', error.message);
                }
            });
    } catch (error) {
        // TODO: handle exception
        console.error('Error:', error.message);
    }
};

commitTransaction();
import requests
import uuid
import json

def commit_transaction():

    # Step 1: Read configuration values with upmost security
    token = "your_access_token_from_oauth_response"
    # For production - api.moneygram.com & For test - sandboxapi.moneygram.com
    transactionId = "current_transaction_id";
    host = "sandboxapi.moneygram.com";
    url = 'https://' + host + '/payout/v1/transactions/' + transactionId + '/commit';

    # Step 2: Create the PUT request headers & body

    headers = {
        'Content-Type': 'application/json',
        'X-MG-ClientRequestId': str(uuid.uuid4()), # New UUID for each request tracing
        'Authorization': 'Bearer ' + token,
    }

    params = {
        'agentPartnerId': 'your_partner_id',
        'targetAudience': 'AGENT_FACING',
        'userLanguage': 'en-US'
    }

    request = {
        'payoutId': "current_payout_id", # generated during the retrieve transaction
        'partnerTransactionId': "partner_transaction_id", # optional
    }
    
    try:
        # Step 3: Send the request and obtain the response
        response = requests.put(url, json=request, params=params, headers=headers)

        # Step 4: Parse the success response and process further
        if response.status_code == 200:
            parsed_response = json.dumps(json.loads(response.text), indent=2)
            print(parsed_response)
        else:
            # Step 5: Parse the error response and handle the errors
            print("Request failed with status code:", response.status_code)
            print(json.dumps(json.loads(response.text), indent=2))

    except requests.exceptions.RequestException as e:
        # Print any error that occurred during the request
        # TODO: handle exception
        print("An error occurred:", e)

commit_transaction()

package payout;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

public class CommitTransaction {

    public static void main(String[] args) {
        // Step 1: Read configuration values with upmost security
        String token = "your_access_token_from_oauth_response";

        // For production - api.moneygram.com & For test - sandboxapi.moneygram.com
        String host = "sandboxapi.moneygram.com";
        String transactionId = "current_transaction_id";
        String uri = "https://" + host + "/payout/v1/transactions/" + transactionId + "/commit" + "?"
                + "agentPartnerId=" + agentPartnerId
                + "&userLanguage=" + userLanguage
                + (targetAudience.isBlank() ? "" : "&targetAudience=" + targetAudience);

        // Step 2: Create the PUT request header, params & body
        // Create a JSON object
        JsonObjectBuilder requestBuilder = Json.createObjectBuilder()
                .add("payoutId", "current_payout_id")
                .add("partnerTransactionId", "partner_transaction_id") // optional

        JsonObject jsonObject = requestBuilder.build();
        // Create a StringWriter to write the JSON string
        StringWriter stringWriter = new StringWriter();
        try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) {
            jsonWriter.writeObject(jsonObject);
        }
        // Get the JSON string from the StringWriter
        String jsonString = stringWriter.toString();

        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(uri))
                .PUT(HttpRequest.BodyPublishers.ofString(jsonString))
                .setHeader("Authorization", "Bearer " + token)
                .setHeader("X-MG-ClientRequestId", String.valueOf(UUID.randomUUID()))
                .build();

        try {
            // Step 3: Send the request and obtain the response
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            // Retrieve the status code and body from the response
            int statusCode = response.statusCode();

            // Step 4: Parse the success response and process further
            if (statusCode == 200) {
                String responseBody = response.body();
                System.out.println(responseBody);
            } else {
                // Step 5: Parse the error response and handle the errors
                String responseBody = response.body();
                System.out.println(responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
    }
}






API Structure


Header parameters

NameTypeRequired
/Optional
Description
X-MG-ClientRequestIdStringOptionalClient request ID that can be passed by the client application. Client request ID must be unique within a single session for unique requests. This attribute can be used for ensuring idempotent request processing for some APIs. MoneyGram recommends using a UUID for the value of this field.
X-MG-SessionIdStringRequiredA GUID MoneyGram generates for correlating multiple calls within a transaction session.

Note: The X-MG-SessionId is not required if the payoutId is passed in the request body.
X-MG-ConsumerIPAddressStringOptionalIP address of the system initiating the session.



Query parameters

FieldTypeRequired/
Optional
Description
targetAudienceStringOptionalTailors MoneyGram’s error messages and field metadata to an in-store, digital or crypto customer. (Enumerated value)

NOTE: For a full list of accepted target audience values. See the TARGET_AUDIENCE enumeration from the Reference Data Enumerations endpoint
userLanguageStringRequiredLanguage used by the user/operator.
agentPartnerIdStringRequiredUnique agent or partner identifier.
posIdStringOptionalPoint of sale identifier of the client performing the API Call
operatorIdStringOptionalOperator name or ID of the user performing the transaction. Name or ID must be populated from the agent/partner system and cannot be edited by the user.



Path parameters

FieldTypeRequired/
Optional
Description
transactionIdString
Max length: 36
RequiredUnique identifier for the transaction resource



Request body

FieldTypeRequired/
Optional
Description
partnerTransactionIdStringOptionalPartner’s unique session identifier
payoutIdStringRequiredUnique identifier for the transaction session

Note: The payoutId is not required if the X-MG-SessionId is passed as a header parameter.
additionalDetailsDynamicOptionalDynamic field key/values



Response fields

FieldTypeRequired/
Optional
Description
referenceNumberString
Max length: 8
RequiredMoneyGram's reference number for the transaction