Dev Save Points Example

Saving Player Points with devBatchSavePoints

Once you’ve registered your game and obtained a gameApiKey, you can save player points to the OGP platform. Like other protected endpoints, this request requires an HMAC signature, which you can generate using your API key and secret key with the getSignature helper.

The devBatchSavePoints endpoint lets you batch save player points in the context of your game and token. At minimum, you must provide:

  • gameApiKey – The key returned when registering your game.

  • points – An array of objects containing a playerId and points value.

JavaScript Example

/**
 * Generates HMAC signature for API authentication
 * @returns {Promise<string>} The signature for API requests
 */
async function getSignature() {
  try {
    const response = await fetch(`https://api.opengameprotocol.com/user/hmac-signature`, {
      method: 'POST',
      body: JSON.stringify({
        secretKey: SECRET_KEY,
        path: '/play/dev/batch-save-points',
        method: 'POST',
        apiKey: API_KEY,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(
        `Failed to get signature: ${response.status} ${response.statusText}`
      );
    }

    const result = await response.json();
    return result.data.signature;
  } catch (error) {
    console.error('Failed to get signature:', error);
    throw new Error('Signature generation failed');
  }
}

/**
 * Saves player points for a game
 * @param {string} gameApiKey - API key returned after registering the game
 * @param {Array<Object>} points - Array of { playerId, points }
 * @returns {Promise<Object>} API response
 */
async function savePlayerPoints(gameApiKey, points) {
  const signature = await getSignature();

  const payload = {
    gameApiKey,
    points,
  };

  console.log('Submitting player points:', payload);

  const response = await fetch(`https://api.opengameprotocol.com/play/dev/batch-save-points`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'x-auth-provider': 'hmac',
      Authorization: signature,
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(
      `Save points failed: ${response.status} ${response.statusText} - ${errorText}`
    );
  }

  const result = await response.json();
  console.log('Save points response:', result);
  return result;
}

// Example usage:
savePlayerPoints(
  'YOUR_GAME_API_KEY',
  [{ playerId: 'player123', points: '100' }],
);

Last updated