PUT Commit a Transaction

PUT /refund/v2/transactions/{transactionId}/commit

Development Guide

The Commit a Transaction endpoint executes the transactionId and completes the refund.



1. Prepare headers, authentication & parameters:

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


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 transaction endpoint response.

🚀

Launch Example Code




2. Provide refundId in the request body:

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


🚀

Launch Example Code




3. Make a request and handle the response:

The application must call 'Commit a transaction' endpoint with a PUT HTTP method. The application must build 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 response will typically return the following fields: referenceNumber, and expectedPayoutDate

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

🚀

Launch Example Code

.




4. You're Done! Communicate the refund confirmation:

The information returned can be used to display a "Refund Confirmation" on the application UI.





Business rules to code

🔎

Retrieving a transactionId: If the application does not store the transactionId, it can be retrieved using the refund/v2/transactions/?referenceNumber={referenceNumber} endpoint.

**Handling Timeout & Retry: **If the application experiences a "timeout" during commit you can retry the Commit transaction endpoint.




Video Tutorial





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 host = "sandboxapi.moneygram.com";
    const transactionId = "current_transaction_id";
    const url = 'https://' + host + '/refund/v2/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 request = {
        agentPartnerId: "your_partner_id",
        targetAudience: "AGENT_FACING",
        userLanguage: "en-US",
        refundId: "current_refund_id"
    }

    try {
        // Step 3: Send the request and obtain the response
        axios.put(url, request, { 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    
    host = "sandboxapi.moneygram.com";
    transactionId = "current_transaction_id";
    url = 'https://' + host + '/refund/v2/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,
    }
    request = {
        'agentPartnerId': 'your_partner_id',
        'targetAudience': 'AGENT_FACING',
        'userLanguage': 'en-US',
        'refundId': 'current_refund_id'
    }

    try:
        # Step 3: Send the request and obtain the response
        response = requests.put(url, json=request, 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 refund;

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 tokenEndpoint = "https://" + host + "/refund/v2/transactions/" + transactionId + "/commit";

        // Step 2: Create the PUT request headers & body
        // Create a JSON object
        JsonObjectBuilder requestBuilder = Json.createObjectBuilder()
                .add("agentPartnerId", "your_partner_id")
                .add("targetAudience", "AGENT_FACING")
                .add("userLanguage", "en-US")
                .add("refundId", "current_refund_id");

        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(tokenEndpoint))
                .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

Field

Type

Required
/Optional

Description

X-MG-ClientRequestId

String

Optional

Client 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-SessionId

String

Required

A GUID MoneyGram generates for correlating multiple calls within a transaction session.

X-MG-ConsumerIPAddress

String

Optional

IP Address of the system initiating the session




Path Parameters

Field

Type

Required
/Optional

Description

transactionId

string

Required

Unique id of the transaction resource




Request Body Parameters

Field

Type

Required/
Optional

Description

targetAudience

String
[Enumerated Values]

Required

Tailors 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 _

agentPartnerId

String
Max length: 8

Optional

Unique agent or partner ident

posId

String

Optional

Point of sale identifier of the client performing the API Call

userLanguage

String
Max length: 6

Optional

Language used by the operator

refundId

String

Required

Unique identifier for the transaction session

refundTargetAccount.tenderType

String [Enumerated Values]

Optional

Funding method, (Enumerated Values)

refundTargetAccount.provider

String

Optional

Name of the payment provider

refundTargetAccount.providerNetworkCode

String

Optional

Providers unique network identifier code

refundTargetAccount.providerAccountNumber

String

Optional

Account number of payment source

refundTargetAccount.accountIdentifier

String

Optional

MoneyGram's unique identifier for the consumer account

additionalDetails

Dynamic

Optional

Dynamic field key/values




Response Fields

Field

Type

Required/
Optional

Description

referenceNumber

String
Max Length: 8

Required

MoneyGram's reference number for the transaction

expectedPayoutDate

String
Length: 10
Format: CCYY-MM-DD

Required

Expected date for payout of funds

settlement.reconcileSendAmount.value

String
Min length: 0
Max length: 14
Max Decimal Value: 3

Optional

Send amount to be settled with MoneyGram

settlement.reconcileSendAmount.currencyCode

String
Max length: 3

Optional

The reconcileSendAmount.value currency code (ISO Alpha-3)

settlement.reconcileReceiveAmount.value

String
Min length: 0
Max length: 14
Max Decimal Value: 3

Optional

Receive amount to be settled with Money

settlement.reconcileReceiveAmount.currencyCode

String
Max length: 3

Optional

Settlement receive amount currency code (ISO Alpha-3)

settlement.walletAddress

String

Optional

MoneyGram settlement account/wallet details

settlement.walletMemo

String

Optional

MoneyGram settlement account/wallet memo