Configure OAuth 2.0 client credentials for API authentication, including how to provision credentials in the Business Portal, request and cache access tokens, and implement responsible token management patterns.
PayNearMe supports OAuth 2.0 for API version 3.0+ using the industry-standard client credentials grant. OAuth provides token-based authorization for system-to-system API access. You manage client credentials and access tokens in the PayNearMe Business Portal without contacting Customer Support for each token.
PayNearMe continues to support HMAC signature authentication for API requests and for callbacks. You can use both methods on the same site: requests that include a Bearer token in the Authorization header use OAuth while requests without that header use signature authentication.
Authorization vs. AuthenticationOAuth 2.0 is an authorization protocol. It grants your application controlled access to PayNearMe API resources using access tokens. It does not replace consumer-facing login flows in your application.
Client Pre-Requisites
Before you provision OAuth credentials, confirm the following:
- Your integration uses API version 3.0+. OAuth is not available for API versions 1.8 or 2.0.
- OAuth is enabled for your site by your PayNearMe Technical Account Manager (TAM).
- You have Business Portal access with both Developer and Admin permissions so you can provision sites and manage credentials.
- Your token requests and API calls are made from a secure server-side system. Never place the Client Secret or an access token in browser code, mobile apps, or any software distributed to end users.
- Your network allows outbound HTTPS to both the token endpoint and the API base URL for each environment you use. If you restrict outbound traffic by hostname or IP address, allow both.
- Your servers keep accurate time using NTP (Network Time Protocol) synchronization, so token expiration calculations are correct.
- You have a secure place to store the Client Secret, such as a secrets manager, and a cache for access tokens (see Caching Tokens).
PayNearMe SetupYour TAM will enable OAuth for your site before you can provision credentials. Contact them if the API Client Credentials page is not available/visible in your Business Portal.
Quick Start
- In the Business Portal, provision your site for OAuth (one-time action per site).
- Generate the following client credentials: Client ID, Client Secret, and Audience.
- From your application, request an access token from the PayNearMe Token Endpoint URL using the client credentials grant.
- Cache the access token and reuse it for API calls until it is near expiration.
- Call PayNearMe API endpoints using the
Authorization: Bearer {access_token}header. - Request a new access token when the current token is near expiration or has expired.
sequenceDiagram participant Client as ClientApplication participant Portal as BusinessPortal participant Auth as TokenEndpoint participant API as PayNearMeAPI Client->>Portal: Provision site and generate credentials Client->>Auth: POST client_credentials token request Auth-->>Client: access_token and expires_in Client->>Client: Cache token until near expiry Client->>API: API call with Authorization Bearer token
Sandbox and Production Are SeparateSandbox and production use different token endpoints, API base URLs, and Business Portal environments. Provision the site and generate credentials separately in each environment. Credentials, Audience values, and access tokens from one environment do not work in the other. Always copy the Audience exactly as it displays in the portal for that environment.
Generating Credentials in the Business Portal
To generate and configure your OAuth credentials, log into the Business Portal and complete the following steps:
-
Navigate to Developer > API Documentation > API Client Credentials. Confirm that the API version selector shows v3.0.
-
Click Provision Site. This is a one-time action for each site in each environment. The "Site provisioned successfully" message displays. Provisioning creates a scope in the PayNearMe identity provider and ties it to your site's external ID.
-
Click Generate Credentials. A success confirmation message displays.
-
Verify that Client ID, Client Secret, Audience, and Created Date display correctly.
-
Use the clipboard icon to copy the Client Secret. Store the Client ID, Client Secret, and Audience in a secure location (e.g., a secrets manager).
As long as the Client Secret is not exposed, you do not need to routinely change it.
Sandbox and production are separate. Complete these steps in each environment's Business Portal, and store each environment's credentials separately.
Treat the Client Secret Like a PasswordDo not email the Client Secret, paste it into chat or support tickets, commit it to source control, or share it outside the team that operates your integration. If it may have been exposed, generate a new credential set, move your integration to it, and delete the exposed set.
Credential Limits and Rotation RequirementsEach site can only maintain a maximum of two credential sets. Each set can request tokens from PayNearMe. If two sets exist, the Generate Credentials button is disabled until you delete an existing set. PayNearMe allows two sets so you can migrate smoothly from one Client ID/Client Secret pair to another.
Deleting Credentials
Delete a credential set when:
- The set was used only for testing.
- You suspect a security incident and need to rotate to a new Client Secret.
- You are rotating credentials as part of routine maintenance (see Rotating Credentials).
To delete a set, click Delete on the credential row and confirm removal. Verify that the set no longer displays and that the Generate Credentials button is available again.

Deleted Secrets Cannot be RecoveredDeleting a credential set takes effect immediately. Access tokens already issued from that set stop working, and token requests with that Client ID and Client Secret return
401 Unauthorizederrors. The Client Secret cannot be recovered. Before you delete a set that is in use, move your integration to another set so API calls are not interrupted.
Rotating Credentials
Because each site can hold two credential sets, you can replace your Client ID and Client Secret without interrupting API traffic:
- Confirm that only one credential set exists. If two exist, delete the one that is not in use.
- Click Generate Credentials to create a second set.
- Store the new Client ID, Client Secret, and Audience in your secrets manager.
- Deploy the new credentials to your integration and confirm that token requests and API calls succeed with them.
- Restart or reconfigure every application instance so that all of them request tokens with the new set.
- Confirm that no systems still use the old Client ID, then click Delete on the old set. Tokens issued from the old set stop working immediately.
- Record the rotation date and who performed it in your change log.
If You Suspect a Client Secret Was Exposed
- Generate a second credential set. If two sets already exist, delete the one that is not in use first.
- Switch your integration to the new set immediately.
- Delete the exposed set.
- Review your PayNearMe API activity for unexpected requests and contact your TAM.
Security Best Practices
- Store secrets securely. Keep the Client Secret in a secrets manager or encrypted configuration and inject it at runtime. Never hard-code it or commit it to source control.
- Treat the Client Secret like a password. Do not email it, paste it into chat or support tickets, or share it outside the team that operates the integration.
- Use server-side systems only. Never include the Client Secret or an access token in browser JavaScript, mobile apps, or other software distributed to end users.
- Use HTTPS only for both token requests and API calls, and do not disable certificate validation.
- Never log secrets or full tokens. Mask them (for example, show only the last four characters) in logs, error reports, and support tickets.
- Limit access. Only the Admin and Developer users who need credentials should be able to view and manage them. Remove access promptly when people leave the team.
- Separate environments. Use separate credentials for sandbox and production (and per site where practical). Never use sandbox credentials in production.
- Rotate when needed. Rotate credentials according to your organization's policy, and immediately after a suspected exposure or a change in staff with access.
- Delete unused credential sets so that only the credentials you actively use remain.
- Monitor. Alert on spikes in token requests, repeated authentication errors, and
429responses from the token endpoint.
API Keys and Callbacks
Callback verification continues to use API keys and HMAC signatures--even if you use OAuth for outbound API calls. See HMAC Signature Authentication and API Key Rotation Guidelines.
When OAuth is in use for outbound API calls, the API Keys & Signatures page (Developer > API Documentation > API Keys & Signatures) will display the following message:
This site uses API keys for callbacks only. See API Client Credentials for API access setup.
Migrating from HMAC Signatures
You can configure signature authentication and OAuth on the same site at the same time. Requests that include an Authorization: Bearer header use OAuth; requests without it use signature authentication. This lets you migrate one integration, endpoint, or environment at a time:
- Confirm that your site uses API version 3.0+ and that your TAM has enabled OAuth for your site.
- Provision the site and generate credentials in sandbox (see Generating Credentials in the Business Portal).
- Implement token requests, caching, and refresh (see Token Management).
- Add the
Authorization: Bearer {access_token}header to your API calls and test thoroughly in sandbox. - Provision the site and generate credentials in production.
- Move production traffic to OAuth, ideally in stages, and monitor for
401responses on API calls and for401,403, and429responses from the token endpoint. - After a stable period, remove signature generation for outbound API requests from your code. Keep your API keys for callback validation.
Only authentication changes when you move from signatures to OAuth. Request and response formats for API calls stay the same, except that you omit the signature parameter.
Token Endpoints
Request access tokens from the PayNearMe login host for your environment:
| Environment | Token URL |
|---|---|
| Sandbox | https://login.paynearme-sandbox.com/oauth/token |
| Production | https://login.paynearme.com/oauth/token |
Using the Correct API URLAPI requests use the JSON API base URL for your environment (e.g.,
https://api.paynearme-sandbox.com/json-apifor sandbox). Do not send token requests to the/json-apihost.
Requesting an Access Token
Send a POST request with grant_type, client_id, client_secret, and audience. You can send the body as JSON or as application/x-www-form-urlencoded. Send credentials in the request body over HTTPS only; never put them in the URL query string.
| Field | Required | Description |
|---|---|---|
grant_type | Yes | Always client_credentials. |
client_id | Yes | The Client ID from the API Client Credentials page. |
client_secret | Yes | The Client Secret from the API Client Credentials page. Never log this value. |
audience | Yes | The Audience shown next to your credentials in the portal. It identifies the PayNearMe API the token is for. Copy it exactly. |
Example Request (JSON Data)
curl --request POST \
--url https://login.paynearme-sandbox.com/oauth/token \
--header 'content-type: application/json' \
--data '{
"grant_type": "client_credentials",
"client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET",
"audience": "YOUR_TOKEN_AUDIENCE"
}'Example Request (URL-Encoded Form Data)
curl --request POST \
--url https://login.paynearme-sandbox.com/oauth/token \
--header 'content-type: application/x-www-form-urlencoded' \
--data 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_TOKEN_AUDIENCE'Example Response
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"scope": "external_id/YOUR_SITE_ID",
"expires_in": 86400,
"token_type": "Bearer"
}| Field | Description |
|---|---|
access_token | The Bearer token to send on API calls. Treat it as an opaque string: do not parse it or depend on its format, which may change. Expect it to be 1 KB or larger, and size your storage accordingly. |
scope | Ties the token to your PayNearMe site, in the format external_id/{site identifier}. |
expires_in | The token lifetime in seconds. A typical value is 86400 (24 hours). Always use this value rather than hard-coding a lifetime. |
token_type | Always Bearer. |
Store expires_in and the time you received the token so your application can refresh the access_token before expiration.
Use the following code samples to request tokens from your application. Replace placeholders with your Client ID, Client Secret, Audience, and the correct Token URL for your environment.
require 'uri'
require 'net/http'
require 'json'
url = URI('https://login.paynearme-sandbox.com/oauth/token')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request['content-type'] = 'application/json'
request.body = {
grant_type: 'client_credentials',
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET',
audience: 'YOUR_TOKEN_AUDIENCE'
}.to_json
response = http.request(request)
puts response.read_body<?php
$url = 'https://login.paynearme-sandbox.com/oauth/token';
$body = http_build_query([
'grant_type' => 'client_credentials',
'client_id' => 'YOUR_CLIENT_ID',
'client_secret' => 'YOUR_CLIENT_SECRET',
'audience' => 'YOUR_TOKEN_AUDIENCE',
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>const https = require('https');
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'client_credentials',
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET',
audience: 'YOUR_TOKEN_AUDIENCE',
});
const options = {
hostname: 'login.paynearme-sandbox.com',
path: '/oauth/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
},
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => { console.log(data); });
});
req.write(body);
req.end();using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
static async Task Main() {
var client = new HttpClient();
var url = "https://login.paynearme-sandbox.com/oauth/token";
var form = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("grant_type", "client_credentials"),
new KeyValuePair<string,string>("client_id", "YOUR_CLIENT_ID"),
new KeyValuePair<string,string>("client_secret", "YOUR_CLIENT_SECRET"),
new KeyValuePair<string,string>("audience", "YOUR_TOKEN_AUDIENCE"),
});
var response = await client.PostAsync(url, form);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import java.util.Map;
public class OAuthTokenRequest {
public static void main(String[] args) throws Exception {
String body = Map.of(
"grant_type", "client_credentials",
"client_id", "YOUR_CLIENT_ID",
"client_secret", "YOUR_CLIENT_SECRET",
"audience", "YOUR_TOKEN_AUDIENCE"
).entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "=" +
URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://login.paynearme-sandbox.com/oauth/token"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}#!/usr/bin/env python3
import json
import urllib.request
import urllib.parse
url = 'https://login.paynearme-sandbox.com/oauth/token'
data = urllib.parse.urlencode({
'grant_type': 'client_credentials',
'client_id': 'YOUR_CLIENT_ID',
'client_secret': 'YOUR_CLIENT_SECRET',
'audience': 'YOUR_TOKEN_AUDIENCE',
}).encode('utf-8')
req = urllib.request.Request(
url,
data=data,
headers={'Content-Type': 'application/x-www-form-urlencoded'},
method='POST',
)
with urllib.request.urlopen(req) as resp:
print(resp.read().decode('utf-8'))package main
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
func main() {
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", "YOUR_CLIENT_ID")
form.Set("client_secret", "YOUR_CLIENT_SECRET")
form.Set("audience", "YOUR_TOKEN_AUDIENCE")
req, err := http.NewRequest("POST", "https://login.paynearme-sandbox.com/oauth/token",
strings.NewReader(form.Encode()))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}Token Endpoint Errors
The token endpoint returns standard HTTP status codes when a request fails. The response body normally includes error and error_description fields. Log these values to help diagnose the problem, but never log the Client Secret.
| HTTP Status | Likely Cause | What to Do |
|---|---|---|
400 | A missing or malformed field, the wrong grant_type, or the wrong Content-Type. | Fix the request. Do not retry it unchanged. |
401 / 403 | The wrong Client ID or Client Secret, deleted credentials, the wrong Audience, or credentials from a different environment. | Verify the values in the portal for the correct environment. Do not retry in a loop; alert your operators. |
429 | Token requests are being sent too often. | Honor the Retry-After header, back off with jitter, and review your caching (see Error Handling). |
5xx | A temporary service problem. | Retry with capped exponential backoff (see Error Handling). |
Authenticating API Requests
After you receive an access_token, send API requests with the Bearer scheme in the Authorization header. When you use OAuth for a request, you do not need to include an HMAC signature in the request body.
The following example creates an order in sandbox using an access token and the required parameters for the /create_order endpoint:
curl --request POST \
--url https://api.paynearme-sandbox.com/json-api/create_order \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--data '{
"site_identifier": "S2155373459",
"timestamp": "1636142061",
"version": "3.0",
"order_amount": "500",
"order_currency": "USD",
"site_customer_identifier": "11223344",
"order_type": "any",
"order_is_standing": "true"
}'Required body fields such as version, site_identifier, and timestamp still apply for version 3.0+ API calls. Omit the signature parameter when authenticating with OAuth.
Token Management
PayNearMe supports on-demand token requests. However, requesting a new token for every API call can exhaust shared token capacity and trigger rate limits. All clients must cache access tokens and refresh only when needed.
Caching RequirementsDo not request a new access token for every API call. Failure to cache and refresh responsibly can result in rate limiting, increased latency, and enforcement of issuance quotas.
Caching Tokens
After you receive a token, store it in a secure cache until it expires. Acceptable options include:
- In-memory cache (single process)
- Redis or another shared cache (multiple instances)
- Secure server-side storage
If you run several application instances, share one cached token between them (for example, in Redis) rather than having every instance request its own. An access token grants access to anyone who holds it until it expires, so protect the cache like a secret.
Do not call the token endpoint before every API request.
Validating Tokens
Before making an API call, check whether the cached token is still valid using the expiration time you stored (see Proactive Refresh). Do not call the token endpoint to check validity.
As a general recommendation, request a new token when the current token is within 5–10 minutes of expiration or has already expired. This gives your application time to obtain a new token gracefully, without waiting until the last moment.
Refreshing Tokens
Client credentials tokens cannot be renewed with a refresh token. To refresh, request a new token with the same Client ID and Client Secret before the current token expires. Use proactive refresh, and use single-flight refresh so concurrent workers do not all call /oauth/token at once.
Proactive Refresh
When you receive a token:
- Store the
expires_infrom the response. - Record the
issued_attime (i.e., Unix time when you received the token). - Compute the expiration time:
expiration_time=issued_at+expires_in.
Code a clock-skew leeway buffer (leeway_buffer) of 60–120 seconds into your refresh logic to account for differences between your system clock and PayNearMe's. Your application must treat the token as expired when:
current_time ≥ expiration_time - leeway_buffer
Never send a token after this point. The 5–10 minute recommendation in Validating Tokens is when to start requesting a new token; the leeway buffer is the hard cutoff after which the current token is no longer used.
For high-traffic systems, you can refresh at 80–90% of the token lifetime in a background job so that live request paths are not blocked upon token refresh.
Single-Flight Refresh
Ensure only one refresh runs at a time per credential set across threads or processes. Concurrent /oauth/token calls from many workers can cause token storms and rate limiting.
Error Handling
Errors on API calls and on the token endpoint are reported differently and require different responses:
- API calls return HTTP
401 Unauthorizedwhen theAuthorizationheader has no Bearer token or the access token is invalid, expired, or issued for a different site. Refresh and retry once. Other failed API calls return HTTP200with"status": "error"and one or more error descriptions in the response body; do not refresh the token for these. - The token endpoint (
/oauth/token) returns standard HTTP error status codes. Use exponential backoff and capped retries for429and5xxresponses, and do not retry400,401, or403responses.
Authentication Errors on API Calls
If the Authorization header has no Bearer token, or the access token is invalid, expired, or issued for a different site, the API returns HTTP 401 Unauthorized. A site_identifier that does not match any site returns the same error. When the response body is JSON, it contains the following error:
{
"status": "error",
"errors": [
{
"description": "Unauthorized"
}
]
}The response does not say why the token was rejected. An expired token, an invalid token, and a token issued for a different site (see Parent and Child Sites) all return the same error. A site mismatch fails again after a refresh, which is why you retry only once. Depending on where the request is rejected, the body may not be JSON, so detect token errors by the HTTP 401 status rather than by parsing the body.
Two mistakes return HTTP 200 signature errors instead of 401, because the request is handled as an HMAC-signed call:
- The request has no
Authorizationheader at all. - The site is not enabled for OAuth 2.0. A Bearer token sent to such a site is ignored.
If you are sending a token and see errors about signature or timestamp, check for one of these rather than refreshing the token.
When an API call returns 401:
- Request a new access token once, using single-flight refresh. If another thread or process has already replaced the token, use the new one instead of requesting another.
- Retry the original request exactly once with the new token.
- Do not loop indefinitely.
If the retry fails, surface a clear error to operators and log correlation details: request timestamps, the Client ID, and the site_identifier. Never log the Client Secret or the full access token.
429 Responses On the Token Endpoint
429 Responses On the Token EndpointIf /oauth/token returns 429 Too Many Requests:
- Honor the
Retry-Afterheader when present. - Use exponential backoff with jitter. For example, wait 1 second, double the wait after each attempt, add a random delay, and cap the wait at 60 seconds.
- Do not retry aggressively.
- Review your caching. A
429response from the token endpoint usually means tokens are being requested too often.
5xx Responses On the Token Endpoint
5xx Responses On the Token EndpointFor server errors:
- Use exponential backoff with jitter.
- Cap the total number of retries (for example, 5 attempts), then surface an error.
- Log telemetry for operational monitoring.
- Keep using your cached token while it is still valid. A token endpoint outage does not affect API calls made with a valid token.
Incorrect vs Correct Patterns
Incorrect - New token on every API call (high risk):
def call_api():
token = request_new_token() # Do not do this on every call
return requests.post(api_url, headers={'Authorization': f'Bearer {token}'}, json=payload)Correct - Cache the token, refresh only when needed, and allow only one refresh at a time:
import threading
import time
import requests
LEEWAY_BUFFER = 120 # clock-skew leeway buffer, in seconds
_lock = threading.Lock()
_cached_token = None
_expiration_time = 0 # issued_at + expires_in
def get_token():
global _cached_token, _expiration_time
if _cached_token and time.time() < _expiration_time - LEEWAY_BUFFER:
return _cached_token
with _lock: # single-flight refresh
# Another thread may have refreshed the token while this one waited.
if _cached_token and time.time() < _expiration_time - LEEWAY_BUFFER:
return _cached_token
_cached_token, expires_in = request_new_token() # POST /oauth/token
_expiration_time = time.time() + expires_in
return _cached_token
def call_api():
return requests.post(
api_url,
headers={'Authorization': f'Bearer {get_token()}'},
json=payload,
)In this example, request_new_token() is your function that sends the token request and returns the access_token and expires_in values. If you run multiple servers or processes, store the token and expiration time in a shared cache and replace the in-process lock with a distributed lock.
Parent and Child Sites
OAuth client credentials can be configured at different levels:
- Parent site: Credentials at the parent level can be used by the parent and by child sites that are configured to inherit from the parent. Contact your TAM to confirm whether your child sites inherit from their parent.
- Child site: Credentials at the child level apply only to that child, not to siblings or the parent.
A token is tied to the scope of the site its credentials were created on. A child site can use its own token, or its parent's token if the child inherits from the parent. Using a token for any other site returns 401 Unauthorized with the same Unauthorized error as an invalid or expired token (see Authentication Errors on API Calls). This includes:
- A child site's token used for a sibling site or for the parent
- A parent site's token used for a child site that does not inherit from the parent
Client Responsibilities
Your integration must:
- Cache access tokens after the first successful token request
- Refresh only when the token is near expiration or expired
- Implement exponential backoff for token endpoint errors
- Retry an API call once after refreshing when the call returns
401 - Prevent parallel token storms (single-flight refresh)
Failure to follow these patterns may result in rate limiting, service instability, higher latency, and enforcement of issuance quotas.
PayNearMe SafeguardsPayNearMe may apply additional controls, including:
- Fine-grained machine-to-machine token quotas per Client ID
- Traffic monitoring and alerting for abnormal token request volume
Clients that exceed reasonable issuance thresholds may be investigated or rate limited.
Go-Live Checklist
Before you move production traffic to OAuth, confirm the following:
- The site is provisioned and credentials are generated in the correct environment.
- The Client ID, Client Secret, and Audience are stored in a secrets manager, not in code or logs.
- A token request succeeds, and the response includes
access_token,expires_in, andtoken_type. - An API call with the Bearer token succeeds.
- The token is cached and reused: several consecutive API calls produce only one token request.
- Expiration is calculated from
expires_inwith a 60–120 second leeway buffer, and a new token is requested before expiration. - Single-flight refresh is implemented and verified under concurrent load.
- A
401response on an API call triggers one refresh and exactly one retry, with no infinite loops. -
429and5xxresponses from the token endpoint use backoff with jitter and capped retries. - Negative tests pass: an invalid Client Secret and deleted credentials return an error and raise an alert, without retrying in a loop.
- Logs contain no secrets or full tokens.
- Your credential rotation procedure is documented and tested (see Rotating Credentials).
- Monitoring and alerts are set for token request volume and authentication errors.
- Production token endpoint, API base URL, credentials, and Audience are configured separately from sandbox.
- Callback validation with your API keys still works.
Frequently Asked Questions
Can I use signature authentication and OAuth at the same time?
Yes. If the request does not include a Bearer token in the Authorization header, PayNearMe uses HMAC signature authentication. If the request does include Authorization: Bearer {access_token}, PayNearMe uses OAuth for that request.
When would I still use signatures?
If your integration validates callbacks with HMAC signatures, you still need API keys and signature verification for those inbound messages. Outbound API calls can use OAuth while callbacks continue to use API keys.
Where do I find my site identifier?
Use the same Site ID (or Key Identifier) as for signature-based calls. See Authentication for locating your site identifier in the Business Portal.
Is there a refresh token?
No. The client credentials grant does not issue refresh tokens. When a token nears expiration, request a new one with your Client ID and Client Secret (see Refreshing Tokens).
How long does an access token last?
Typically 86400 seconds (24 hours). Always read expires_in from the token response instead of hard-coding the lifetime, since it could change.
Can I decode or inspect the access token?
Treat the token as an opaque string. Its format and contents may change, so do not build logic that depends on them. Use expires_in to track expiration.
Can multiple servers share one token?
Yes, and they should, through a shared cache. Because anyone holding a token can use it until it expires, protect the cache like a secret.
Can I use OAuth from a web browser or mobile app?
No. The Client Secret and access tokens must never be exposed to end users. Call PayNearMe from your backend systems.
Can I get my Client Secret again later?
You can copy the Client Secret from the credentials table for as long as the credential set exists. If you delete the set, the secret cannot be recovered and you must generate a new set.
Does OAuth work with API versions 1.8 or 2.0?
No. OAuth requires API version 3.0+.
Troubleshooting
401 Unauthorized from the Token Endpoint
- Confirm Client ID, Client Secret, and Audience match the values shown when credentials were generated.
- Verify you are calling the correct environment (sandbox vs production token URL).
- If credentials were deleted, generate a new set. Deleted secrets cannot be restored.
Authentication Error from an API Call
API calls return HTTP 401 Unauthorized when the Authorization header has no Bearer token, or when the access token is invalid, expired, or issued for a different site. The response does not say which. See Authentication Errors on API Calls.
- Confirm the
Authorizationheader isBearer {access_token}with no typos or extra whitespace, and that the token was not truncated or altered. - Check whether the access token has expired. If so, refresh and retry once.
- Verify the Audience used to obtain the token matches your site configuration.
- Ensure the sandbox token is not sent to production API hosts (or vice versa).
- If the credential set that issued the token was deleted, the token no longer works. Request a token with an active credential set.
- Confirm the token was issued for the site in the request's
site_identifier, or for its parent if the site inherits from the parent (see Parent and Child Sites).
Rate Limiting or Token Exhaustion
- Audit your code for a new token request on every API call then implement caching and proactive refresh instead.
- Ensure only one refresh runs at a time across workers.
- On
429responses, respectRetry-Afterand back off.
OAuth Option Not Visible in the Business Portal
If the API Client Credentials page, the Provision Site button, or the Generate Credentials button is missing:
- Confirm that the API version selector on the API Client Credentials page shows v3.0.
- Confirm that you have both Developer and Admin permissions.
- OAuth must be enabled for your site by PayNearMe. If the options are still missing, contact your TAM.
Generate Credentials Button Is Disabled
Your site already has two credential sets, which is the maximum. Delete the set you are not using, then generate a new one (see Deleting Credentials).
400 Bad Request from the Token Endpoint
The request is malformed. Send grant_type=client_credentials with all four fields, and set Content-Type to application/json or application/x-www-form-urlencoded to match the body format.
403 Forbidden from the Token Endpoint
- Confirm Client ID, Client Secret, and Audience match the values in the portal for the environment you are calling.
- Confirm the token URL matches the environment your credentials came from. Sandbox credentials do not work in production, and production credentials do not work in sandbox.
API Calls Work for Hours, Then Fail
The token expired and your application did not request a new one. Track expiration from expires_in and refresh proactively (see Proactive Refresh).
Intermittent Failures Under Load
Multiple workers may be refreshing at the same time or using stale tokens. Use single-flight refresh and a shared cache (see Single-Flight Refresh).
Callbacks Stop Validating
Callbacks still use API keys and HMAC signatures, even when your API calls use OAuth. Confirm your API keys were not deleted or changed (see API Keys and Callbacks).
Contacting Support
If you need help from your TAM, include the following information:
- The environment (sandbox or production) and your
site_identifier - Your Client ID (never the Client Secret or a full access token)
- The date and time, with time zone, of the failing request
- Whether the failure is on the token endpoint or on an API call
- For token endpoint failures, the HTTP status and the
erroranderror_descriptionvalues - For API call failures, the error description from the response body
