GET Retrieve Transaction History

GET /consumer/v2/profiles/{profileId}/transactions

Development Guide:

The retrieve consumer transaction history API returns an array of a consumer's transaction history.



1. Prepare headers & authentication:

The application must call the Retrieve Transaction History endpoint with a GET HTTP method, providing the OAuth access_token in the header and all other required header values.


NOTE: MoneyGram uses the OAuth 2.0 framework. The application must use their OAuth client credentials to generate an accessToken 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


🚀

Launch Example Code




2. Provide profileId as a path parameter:

The application must provide theprofileId as a path parameter.


🚀

Launch Example Code




3. Provide query parameters:

The application must provide all the required fields userLanguage, agentPartnerId, startDate, and endDate details and any other REQUIRED fields in the request.


🚀

Launch Example Code




4. Make the request and handle the response:

The application will call the 'Retrieve Transaction History' endpoint with a GET HTTP method. The 'Retrieve Transaction History' will generate a response with the consumer name details and an array of the consumer's transaction history for the date range provided. The application must build to handle the following response scenarios.


  • Success | Parse the Response | 200 OK HTTP Status
    When the 'Retrieve Transaction History' endpoint responds with a 200 HTTP Status. An array of the consumers transaction history will be returned for the dates provided.

  • Success | Transaction history has no content | 204 No Content HTTP Status
    When the 'Retrieve Transaction History' endpoint responds with 204 HTTP Status. The 'Retrieve Transaction History' endpoint API will return a message of "The resource content not found".

  • Failed | Handle the Error | 400 Bad Request HTTP Status
    When the 'Retrieve Transaction History' 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 transaction for reversal.

🚀

Launch Example Code

.

.





Business Rules to Code:


🔎

  • Ready for Payout & Available status: The transaction can only be paid out if the transaction is in an AVAILABLE status and the "availableForPayout": true is returned in the response.
  • Send & Payout at the same store: A Payout cannot be received at the same store location where the transaction was sent (i.e. The application cannot Payout a transaction using the same partnerAgentId that was used to send the transfer).



Code Examples

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

const transactionHistory = 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 url = 'https://' + host + '/consumer/v2/profiles';

    // Step 2: Create the GET request headers & params
    const headers = {
        'Content-Type': 'application/json',
        'X-MG-ClientRequestId': uuidv4(), // New UUID for each request tracing
        'Authorization': 'Bearer ' + token,
    };
    
    const profileId = "your_profile_id";
    const params = {
        'agentPartnerId': 'your_partner_id',    
        'userLanguage': 'en-US',
        'startDate': '2024-01-01',
        'endDate': '2024-01-16',
        'targetAudience': 'AGENT_FACING',
        'pageNumber': '1',
        'perPage': '20'
    }

    try {
        // Step 3: Send the request and obtain the response
        axios.get(url + '/' + profileId + '/transactions', { 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);
    }
};

transactionHistory();

import requests
import uuid
import json

def transaction_history():

    # 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"
    url = 'https://' + host + '/consumer/v2/profiles'

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

    profileId = "your_profile_id"
    params = {
        'agentPartnerId': 'your_partner_id',    
        'userLanguage': 'en-US',
        'startDate': '2024-01-01',
        'endDate': '2024-01-16',
        'targetAudience': 'AGENT_FACING',
        'pageNumber': '1',
        'perPage': '20'
    }

    try:
        # Step 3: Send the request and obtain the response
        response = requests.get(url + '/' + profileId + '/transactions', 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:
            # Print the error message if request fails
            # TODO: handle exception
            print("Request failed with status code:", response.status_code)
            print(json.loads(json.dumps(response.text, indent=4)))

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

transaction_history()

package consumer;

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 TransactionHistory {

    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";

        // Step 2: Create the GET request headers & params
        // Mandatory Query params
        String agentPartnerId = "your_partner_id";
        String userLanguage = "en-US";
        String startDate = "2024-01-01";
        String endDate = "2024-01-16";

        // Optional Query params
        String targetAudience = "AGENT_FACING";
        Integer pageNumber = null;
        Integer perPage = null;

        // Mandatory Path params
        String profileId = "your_profile_id";

        String uri = "https://" + host + "/consumer/v2/profiles/" + profileId + "/transactions?"
                + "agentPartnerId=" + agentPartnerId
                + "&userLanguage=" + userLanguage
                + "&startDate=" + startDate
                + "&endDate=" + endDate
                + (targetAudience.isBlank() ? "" : "&targetAudience=" + targetAudience)
                + (pageNumber == null ? "" : "&pageNumber=" + pageNumber)
                + (perPage == null ? "" : "&perPage=" + perPage);

        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(uri))
                .GET()
                .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

FieldTypeRequired/OptionalDescription
X-MG-ClientRequestIdStringRequiredClient 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-ConsumerIPAddressStringOptionalIP address of the system initiating the session.



Query Parameters

FieldTypeRequired/
Optional
Description
profileIdStringRequiredConsumer's unique identifier
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.
startDateStringRequiredStart date in UTC format of the period from when the transaction events are requested
endDateStringRequiredThe end date of the requested transactions events in UTC format.
pageNumberStringOptionalPage number (cursor) returned with each of the transaction results
perPageStringOptionalNumber of results returned per page



Response Fields

FieldTypeRequired/
Optional
Description
consumer.name.firstNameString
Min length: 1
Max length: 20
RequiredFirst Name
consumer.name.middleNameString
Min length: 1
Max length: 20
OptionalMiddle Name (if applicable)
consumer.name.lastNameString
Min length: 1
Max length: 30
RequiredLast Name
consumer.name.secondLastNameString
Min length: 1
Max length: 30
OptionalConsumer's Second Last Name (if applicable)
consumerTransactionHistory.transactionIdString
Max length: 36
OptionalUnique identifier for the transaction resource
consumerTransactionHistory.referenceNumberString
Max length: 8
OptionalMoneyGram's reference number for the transaction
consumerTransactionHistory.transactionStatusStringOptionalMoneyGram's transaction status
consumerTransactionHistory.transactionSubStatusArrayOptionalMoneyGrams' lastest substatus of transaction
consumerTransactionHistory.destinationCountryCodeString
Max Length: 3
RequiredTransaction Destination Country (ISO alpha-3 code)
consumerTransactionHistory.serviceOptionCodeString
Max length: 21
RequiredUnique category code to identify the transaction method
consumerTransactionHistory.serviceOptionNameString
Max length: 50
OptionalConsumer facing name to identify the transaction method
consumerTransactionHistory.serviceOptionRoutingCodeString
Max length: 21
OptionalUnique identifier of the individual banking, wallet, or card provider for the service option.
consumerTransactionHistory.serviceOptionRoutingNameString
Max length: 50
OptionalUnique name of the individual banking, wallet, or card provider for the service option.
consumerTransactionHistory.sendAmount.amountString
Min length: 0
Max length: 14
Max Decimal Value: 3
RequiredTransaction amount and currency excluding fees and exchange rate. Transaction Currency (ISO alpha-3 code)

NOTE: For Crypto partners this is the fiat currency for the BUY/Sell or Ramp-on/Ramp-off
consumerTransactionHistory.sendAmount.feesString
Min length: 0
Max length: 14
Max Decimal Value: 3
RequiredFee Amount and Fee Currency applied to transaction (Fee Currency usesISO alpha-3 code)
consumerTransactionHistory.sendAmount.taxesString
Min length: 0
Max length: 14
Max Decimal Value: 3
OptionalTax Amount and Tax Currency applied to the Transaction by the the origin country (Tax Currency uses ISO alpha-3 code)
consumerTransactionHistory.sendAmount.discountsApplied.totalDiscountString
Min length: 0
Max length: 14
Max Decimal Value: 3
OptionalTransaction discount amount applied and currency type excluding fees and exchange rate. Transaction Currency (ISO alpha-3 code)
consumerTransactionHistory.sendAmount.totalString
Min length: 0
Max length: 14
Max Decimal Value: 3
RequiredTransaction Total Amount and Transaction Total Currency including fees, taxes and discount. (Transaction Total Amount uses ISO alpha-3 code)
consumerTransactionHistory.receiveAmount.amountString
Min length: 0
Max length: 14
Max Decimal Value: 3
RequiredTransaction Received Amount and Transaction Receive currency (Transaction Total Amount uses ISO alpha-3 code)
consumerTransactionHistory.receiveAmount.feesString
Min length: 0
Max length: 14
Max Decimal Value: 3
OptionalReceived Fee and Receive Currency applied to the transaction by the destination country (Transaction Total Amount uses ISO alpha-3 code)
consumerTransactionHistory.receiveAmount.taxesString
Min length: 0
Max length: 14
Max Decimal Value: 3
OptionalTax Amount and Tax Currency applied to the Transaction by the the origin country (Tax Currency uses ISO alpha-3 code)
consumerTransactionHistory.receiveAmount.totalString
Min length: 0
Max length: 14
Max Decimal Value: 3
RequiredReceive Amount Total and Receive Transaction Currency to be picked-up/deposited in destination country including fees, taxes and discount (Transaction Total Amount uses ISO alpha-3 code)
consumerTransactionHistory.receiveAmount.fxRateString
Max Decimal Value: 6
RequiredFx Rate applied to transaction
consumerTransactionHistory.sendAmount.fxRateEstimatedBooleanOptionalIndicates whether the Fx is “estimated” and amount, taxes and total cannot be guaranteed. The word “estimated” must appear before receiveAmount.amount, receiveAmount.taxes and receiveAmount.total only when true.
consumerTransactionHistory.tenderTypeStringOptionalFunding method
consumerTransactionHistory.targetAccountProfileIdStringOptionalUnique Identifier for Target Account Resource
consumerTransactionHistory.targetAccountDisplayNumberStringOptionalThe last four digits of the target account number
consumerTransactionHistory.receiver.name.firstNameString
Min length: 1
Max length: 20
RequiredFirst Name
consumerTransactionHistory.receiver.name.middleNameString
Min length: 1
Max length: 20
OptionalMiddle Name (If applicable)
consumerTransactionHistory.receiver.name.lastNameString
Min length: 1
Max length: 30
RequiredLast Name
consumerTransactionHistory.receiver.name.secondLastNameString
Min length: 1
Max length: 30
OptionalSecond Last Name (If applicable)
paginationMetadata.totalItemsNumberOptionalTotal number of items on all pages
paginationMetadata.currentPageNumberOptionalCurrent page number
paginationMetadata.perPageNumberOptionalPage size
paginationMetadata.totalPagesNumberOptionalTotal number of pages
paginationMetadata.links.pageNumberNumberOptionalPage number
paginationMetadata.links.hrefString
Max Length: 255
OptionalHATEOS links to data