POST Create a Consumer Profile

POST /consumer/v2/profiles

Development Guide:

The 'Create Consumer Profile API' generates a new profileId for the consumer.


1. Prepare headers & authentication:

The application must call the Create a Consumer Profile endpoint with a POST 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 request body:

The application must provide all the required consumer details and all other REQUIRED fields in the request.


🚀

Launch Example Code:




3. Make the request and handle the response:

The application will call the 'Create a Consumer Profile' endpoint with a POST HTTP method. The 'Create a Consumer Profile' will generate a profileId for the new consumer's profile. The application must build to handle the following response scenarios:


  • Success | Parse the Response | 200 OK HTTP Status
    When the create a consumer profile endpoint responds with a 200 HTTP Status, the consumer profile has been created and the unique profileId will be returned in the response.

  • Failed | Handle the Error | 400 Bad Request HTTP Status
    When the 'Create a Profile' 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:

.




Code Examples


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

const createProfile = 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 POST request headers & body
    const headers = {
        'Content-Type': 'application/json',
        'X-MG-ClientRequestId': uuidv4(), // New UUID for each request tracing
        'Authorization': 'Bearer ' + token,
    };
    const request = {
        "targetAudience": "AGENT_FACING",
        "agentPartnerId": "your_partner_id",
        "userLanguage": "en-US",
        "consumer": {
            "firstName": "firstName",
            "middleName": "",
            "lastName": "lastName",
            "secondLastName": "",
            "address": {
                    "line1": "line1 of address",
                    "line2": "",
                    "line3": "",
                    "city": "minneapolis",
                    "countrySubdivisionCode": "US-MN",
                    "countryCode": "USA",
                    "postalCode": "55335"
                },
            "notificationPreferences": {
                    "type": "Transactional",
                    "channel": "SMS",
                    "optIn": true
                },
            "mobilePhone": {
                    "number": "6123456789",
                    "countryDialCode": "1"
                },
            "dateOfBirth": "1980-08-15"
        }
    }

    try {
        // Step 3: Send the request and obtain the response
        axios.post(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);
    }
};

createProfile();
import requests
import uuid
import json

def create_profile():

    # 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 POST request headers & body
    headers = {
        'Content-Type': 'application/json',
        'X-MG-ClientRequestId': str(uuid.uuid4()), # New UUID for each request tracing
        'Authorization': 'Bearer ' + token,
    }
    request = {
        'targetAudience': 'AGENT_FACING',
        'agentPartnerId': 'your_partner_id',
        'userLanguage': 'en-US',
        'consumer': {
            'firstName': 'firstName',
            'middleName': '',
            'lastName': 'lastName',
            'secondLastName': '',
            'address': {
                    'line1': 'line1 of address',
                    'line2': '',
                    'line3': '',
                    'city': 'minneapolis',
                    'countrySubdivisionCode': 'US-MN',
                    'countryCode': 'USA',
                    'postalCode': '55335'
                },
            'notificationPreferences': {
                    'type': 'Transactional',
                    'channel': 'SMS',
                    'optIn': True
                },
            'mobilePhone': {
                    'number': '6123456789',
                    'countryDialCode': '1'
                },
            'dateOfBirth': '1980-08-15'
        }
    }

    try:
        # Step 3: Send the request and obtain the response
        response = requests.post(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)

create_profile()

package consumer;

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

    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 uri = "https://" + host + "/consumer/v2/profiles";

        // Step 2: Create the POST request headers & body
        // Create a JSON object
        JsonObjectBuilder requestBuilder = Json.createObjectBuilder()
                .add("targetAudience", "AGENT_FACING")
                .add("agentPartnerId", "your_partner_id")
                .add("userLanguage", "en-US")
                .add("consumer", Json.createObjectBuilder().add("firstName", "firstName")
                        .add("middleName", "")
                        .add("lastName", "lastName")
                        .add("secondLastName", "")
                        .add("address", Json.createObjectBuilder().add("line1", "line1 of address")
                                .add("line2", "")
                                .add("line3", "")
                                .add("city", "minneapolis")
                                .add("countrySubdivisionCode", "US-MN")
                                .add("countryCode", "USA")
                                .add("postalCode", "55335"))
                        .add("notificationPreferences", Json.createObjectBuilder().add("type", "Transactional")
                                .add("channel", "SMS")
                                .add("optIn", true))
                        .add("mobilePhone",
                                Json.createObjectBuilder().add("number", "6123456789")
                                        .add("countryDialCode", "1"))
                        .add("dateOfBirth", "1980-08-15")
                );

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

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



Request Body

FieldTypeRequired
/Optional
Description
targetAudienceString RequiredTailors 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
agentPartnerIdString
Max length: 8
RequiredUnique identifier for the agent or partner
userLanguageString
Max length: 6
RequiredLanguage used by the user/operator
consumer.firstNameString
Min length: 1
Max length: 20
RequiredFirst Name
consumer.middleNameString
Min length: 1
Max length: 20
OptionalMiddle Name (if applicable)
consumer.lastNameString
Min length: 1
Max length: 30
RequiredLast Name
consumer.secondLastNameString
Min length: 1
Max length: 30
OptionalSecond Last Name
consumer.address.line1String
Min length: 5
Max length: 30
RequiredResidence address line 1
consumer.address.line2String
Min length: 1
Max length: 80
OptionalResidence address line 2 (if applicable)
consumer.address.line3String
Min length: 1
Max length: 80
OptionalResidence address line 3 (if applicable)
consumer.address.cityString
Min length: 1
Max length: 20
RequiredCity of residence
consumer.address.countrySubdivisionCodeString
Length: 6
OptionalState/province of residence

NOTE: For a full list of accepted countries and supported destination country subdivision codes see Reference Data API Module: Retrieve Countries ISO3 endpoint
consumer.address.countryCodeString
Length: 3
RequiredCountry of residence (ISO Alpha-3 Code)

NOTE: For a full list of accepted countries and supported destination country subdivision codes see Reference Data API Module: Retrieve Countries ISO3 endpoint
consumer.address.postalCodeString
Min length: 2
Max length: 6
OptionalPostal/Zip code of residence
consumer.notificationPreferences.typeStringOptionalConsumer notification preference types (Enumerated Values)
consumer.notificationPreferences.channelStringOptionalDelivery method of notification

NOTE: For notification preference channels see: Reference Data API Module CNSMR_OPTIN
consumer.notificationPreferences.optInBooleanOptionalFlag to declare customer opts-in to notification type and method
consumer.mobilePhone.numberString
Min length: 5
Max length: 14
RequiredPhone number
consumer.mobilePhone.countryDialCodeString
Min length: 1
Max length: 3
RequiredCountry dial code

NOTE: For country calling code see Reference Data API Module /countries endpoint phoneDialCodes
consumer.personalDetails.dateOfBirthString
Length: 10
RequiredDate of birth (YYYY-MM-DD)
additionalDetailsDynamicOptionalDynamic field key/values



Response Fields

FieldTypeRequired/OptionalDescription
profileIdStringRequiredConsumer's unique identifier