Get Access Token
GET /oauth/accessToken
Overview
OAuth (Open Authorization) is an open standard framework that enables third-party applications to access protected resources on behalf of a resource owner, without sharing the owner's credentials. It allows users to grant limited access to their resources to other applications without revealing their passwords or sensitive information. OAuth provides a secure and standardized way for applications to access resources on behalf of users, reducing the risk of exposing sensitive information and providing a better user experience.
The OAuth 2.0 Framework is the most widely adopted version of OAuth and provides a flexible and extensible framework for authorization. It has several grant types for different use cases, such as authorization code, implicit client credentials and refresh tokens. Each grant type defines its flow and requirements.
MoneyGram uses the OAuth 2.0 framework. The application must use their OAuth client credentials to generate an accesstoken
and pass it as a header value in API HTTP calls.
General API sequence
Detailed guide
Step 1: Request client credentials
After partnering with MoneyGram, we will send you OAuth 2.0 client credentials for each environment. These credentials consist of a unique client ID and secret. MoneyGram's authorization endpoint will verify these credentials and authenticate your application.
Good to know:
Storing credentials securely: The client ID & secret are sensitive pieces of data and could be used to impersonate your business by a third party. Please handle and store this data with the utmost security for your company's safety.
Step 2: Create an access token
Next, the application must next generate an accesstoken
from the MoneyGram authorization endpoint. The application must make an HTTP POST request to the /oauth/accessToken
endpoint using the following values:
Field | Type | Required/Optional | Description |
---|---|---|---|
grant_type | string | Required | The value of this field should always be "client_credentials" . |
client_id | string | Required | The client ID value securely sent to you by moneyGram. |
client_secret | string | Required | The client secret value securely sent to you by MoneyGram. |
Code Examples
const axios = require('axios');
const accessToken = async () => {
// Step 1: Create the HTTP Headers and GET request
const client_id = 'your_client_id';
const client_secret = 'your_client_secret';
// For production - api.moneygram.com & For test - sandboxapi.moneygram.com
const host = "sandboxapi.moneygram.com";
const url = 'https://' + host + '/oauth/accesstoken?grant_type=client_credentials';
const encodedCredentials = Buffer.from(client_id + ':' + client_secret).toString('base64');
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + encodedCredentials,
};
try {
// Step 2: Send the request and obtain the response
axios.get(url, { headers })
.then(function (response) {
// Step 3: Parse the response and extract the access token
const accessToken = response.data.access_token;
console.log('Access Token:', accessToken);
const expiresIn = response.data.expires_in;
console.log('Token Expires In:', expiresIn);
})
.catch(function (error) {
// Handle any errors that occurred during the request
console.error('Error:', error.message);
});
} catch (error) {
console.error('Error:', error.message);
}
};
accessToken();
import requests
import base64
import json
def access_token():
# Step 1: Create the HTTP Headers and GET request
client_id = 'your_client_id';
client_secret = 'your_client_secret';
# For production - api.moneygram.com & For test - sandboxapi.moneygram.com
host = "sandboxapi.moneygram.com";
url = 'https://' + host + '/oauth/accesstoken?grant_type=client_credentials';
credentials = f"{client_id}:{client_secret}"
encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + encoded_credentials
}
try:
# Step 2: Send the request and obtain the response
response = requests.get(url, headers=headers)
# Step 3: Parse the response and extract the access token
if response.status_code == 200:
parsed_response = json.loads(response.text)
accessToken = parsed_response['access_token'];
print("Access Token:"+ accessToken)
expiresIn = parsed_response['expires_in'];
print("Token Expires In:"+ expiresIn)
else:
# Print the error message if request fails
print("Request failed with status code:", response.status_code)
except requests.exceptions.RequestException as e:
# Print any error that occurred during the request
print("An error occurred:", e)
access_token()
package access_token;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.StringReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Base64;
public class AccessToken {
public static void main(String[] args) {
// Replace these values with your actual client credentials and token endpoint host
String clientId = "your_client_id";
String clientSecret = "your_client_secret";
// For production - api.moneygram.com & For test - sandboxapi.moneygram.com
String host = "sandboxapi.moneygram.com";
String tokenEndpoint = "https://" + host + "/oauth/accesstoken?grant_type=client_credentials";
// Step 1: Create the HTTP client and GET request
HttpClient httpClient = HttpClient.newHttpClient();
String credentials = clientId + ":" + clientSecret;
String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(tokenEndpoint))
.GET()
.setHeader("Authorization", "Basic " + encodedCredentials)
.build();
try {
// Step 2: Send the request and obtain the response
HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());
// Retrieve the status code and body from the response
int statusCode = response.statusCode();
System.out.println("Status Code: " + statusCode);
// Step 3: Parse the response and extract the access token
if (statusCode == 200) {
String responseBody = response.body();
JsonReader reader = Json.createReader(new StringReader(responseBody));
JsonObject jsonObject = reader.readObject();
String accessToken = jsonObject.getString("access_token");
System.out.println("Access Token: " + accessToken);
String expiresIn = jsonObject.getString("expires_in");
System.out.println("Token Expires In: " + expiresIn);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
API Request & Response Examples
curl --request GET \
--url 'https://sandboxapi.moneygram.com/oauth/accesstoken?grant_type=client_credentials' \
--header 'accept: application/json' \
--header 'authorization: Basic ******************************************************************'
{
"refresh_token_expires_in": "0",
"api_product_list": "[Adaptor-Ext]",
"api_product_list_json": [
"Adaptor-Ext"
],
"organization_name": "moneygram",
"developer.email": "[email protected]",
"token_type": "BearerToken",
"issued_at": "1681306750858",
"client_id": "********************************",
"access_token": "****************************",
"application_name": "**********-**-****-****-************",
"scope": "",
"expires_in": "3599",
"refresh_count": "0",
"status": "approved"
Good to know:
Token expiration: Access tokens are issued with 1-hour lifespan. The
expires_in
defines the number of seconds remaining until the token expires. You can request a new token once your current token expires.
Step 3: Make subsequent API requests
Once you've been granted an access token, you can make subsequent HTTP calls to MoneyGram endpoints by including the access_token in the authorization header of each request.
Good to know:
Handling invalid tokens: The authorization endpoint will respond with a
HTTP 401 - Unauthorized
status if an *invalid token** is used on the request. In this case, the token may need to be regenerated because it expired, revoked or for another reason. Make sure your applications are coded to properly handle aHTTP 401
status.
Response fields
Field | Type | Required/Optional |
---|---|---|
refresh_token_expires_in | String | Optional |
api_product_list | Array | Optional |
api_product_list_json | Array | Optional |
organization_name | String | Optional |
developer.email | String | Optional |
token_type | String | Optional |
issued_at | String | Optional |
client_id | String | Optional |
access_token | String | Required |
application_name | String | Optional |
scope | String | Optional |
expires_in | Integer | Required |
refresh_count | Integer | Optional |
status | String | Optional |
Updated 10 months ago