โ๏ธRequests
Making Subsequent API Requests
When making API requests, it is essential to include specific headers to ensure both the identification of your tenant account and the security of your requests. Each request must include the following headers:
1. API Key: 'x-api-key'
API Keys are provided by TygaPay support. This key must be included in every API request to identify your tenant account.
2. API Hash: 'x-api-hash'
To maintain the security and integrity of your API requests, you must sign your requests using HMAC SHA256. This signature must be included in every API request. Below, we provide instructions on how to create an
x-api-hash
:
import axios, { AxiosInstance } from "axios";
import { URL } from "url";
import qs from "qs";
import crypto from "crypto";
class TygaPaySandbox {
async runExamples() {
// Store this in a secure place.
const apiKey = "your-api-key";
const apiSecret = "your-api-secret-key";
const service = new TygaPayService(apiKey, apiSecret);
// 1. GET EXAMPLE
const user = await service.getUserByUserId("test");
console.log(user);
// 2. POST EXAMPLE
const order = await service.createOrder({
orderNumber: "order-example-1",
type: "payment",
email: "example@gmail.com",
amount: 100,
notifyUrl: "https://example.com/payment-webhook",
returnUrl: "https://example.com/payment-completed",
});
console.log(order);
}
}
/**
* Refer to the API documentation here: https://tygapay.github.io/docs/
*/
export class TygaPayService {
private readonly client: AxiosInstance;
/**
* Initializes a new instance of the TygaPayService.
* @param apiKey The API key used for authenticating API requests.
* @param apiSecret The secret key used for signing API requests.
*/
constructor(apiKey: string, private apiSecret: string) {
this.client = axios.create({
headers: {
"Content-Type": "application/json",
"x-api-key": apiKey,
},
});
}
/**
* POST EXAMPLE
* Creates a new order in the TygaPay system.
* @param request The order details.
* @returns The API response.
*/
public async createOrder(request: {
orderNumber: string;
type: "payment" | "deposit";
email: string;
amount: number;
notifyUrl: string;
returnUrl: string;
}) {
const url = "https://orders-v1-api-rdqehkur6a-ey.a.run.app/orders";
return this.processApiRequest("POST", url, request);
}
/**
* GET EXAMPLE
* Retrieves a user by their user ID from TygaPay.
* @param userId The user's unique identifier.
* @returns The user's details.
*/
public async getUserByUserId(userId: string) {
const url = `https://users-v1-api-rdqehkur6a-ey.a.run.app/user?userId=${userId}`;
return this.processApiRequest("GET", url);
}
/**
* Processes an API request to TygaPay.
* @param method The HTTP method (POST, GET, PUT, DELETE).
* @param url The endpoint URL.
* @param body The request payload, if any.
* @returns The API response as a generic type T.
*/
public async processApiRequest<T>(
method: "POST" | "GET" | "PUT" | "DELETE",
url: string,
body?: any
): Promise<T> {
try {
const apiPath = this.extractApiPath(url);
const signature = this.signApiRequest(body, apiPath);
const response = await this.client.request({
method,
url,
data: body,
headers: {
"x-api-hash": signature,
},
});
return response.data as T;
} catch (error) {
console.error("TygaPay API request failed", error);
throw error;
}
}
/**
* Extracts the API path from a URL.
* @param url The full URL.
* @returns The extracted path and query string.
*/
private extractApiPath(url: string) {
const parsedUrl = new URL(url);
const apiPath = `${parsedUrl.pathname}${parsedUrl.search}`;
console.log(`Parsed URL: ${apiPath}`);
return apiPath;
}
/**
* Signs an API request by generating a hash signature.
* @param body The request payload.
* @param apiPath The API path.
* @returns The signature string.
*/
private signApiRequest(body: any, apiPath: string) {
const bodyQueryString = qs.stringify(body, {
encode: false,
delimiter: "&",
allowDots: true,
});
console.log(bodyQueryString);
const stringToSign = apiPath + bodyQueryString;
const signature = crypto
.createHmac("sha256", this.apiSecret)
.update(stringToSign)
.digest("hex");
return signature;
}
}
new TygaPaySandbox().runExamples();
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http.Headers;
/// <summary>
/// Refer to the API documentation here: https://tygapay.github.io/docs/
/// Demonstrates usage of the TygaPayService with example methods for both GET and POST requests.
/// </summary>
public class TygaPaySandbox
{
/// <summary>
/// Runs example GET and POST requests using the TygaPayService.
/// </summary>
public static async Task RunExamples()
{
string apiKey = "your-api-key";
string apiSecret = "your-api-secret-key";
var service = new TygaPayService(apiKey, apiSecret);
// Example of a GET request to retrieve user information by userId.
var user = await service.GetUserByUserId("test");
Console.WriteLine(JsonConvert.SerializeObject(user));
// Example of a POST request to create a new order.
var order = await service.CreateOrder(new OrderRequest
{
OrderNumber = "order-example-1",
Type = "payment",
Email = "example@gmail.com",
Amount = 100,
NotifyUrl = "https://example.com/payment-webhook",
ReturnUrl = "https://example.com/payment-completed"
});
Console.WriteLine(JsonConvert.SerializeObject(order));
}
}
/// <summary>
/// Provides methods to interact with the TygaPay API.
/// </summary>
public class TygaPayService
{
private readonly HttpClient client;
private readonly string apiSecret;
/// <summary>
/// Constructor to initialize the TygaPayService with necessary API credentials.
/// </summary>
/// <param name="apiKey">API key for TygaPay authorization header.</param>
/// <param name="apiSecret">Secret key used to sign the API requests.</param>
public TygaPayService(string apiKey, string apiSecret)
{
this.apiSecret = apiSecret;
client = new HttpClient();
client.DefaultRequestHeaders.Add("x-api-key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
/// <summary>
/// Creates an order with the TygaPay API.
/// </summary>
/// <param name="request">Details of the order to create.</param>
/// <returns>The response from the API as a dynamic object.</returns>
public async Task<object> CreateOrder(OrderRequest request)
{
string url = "https://orders-v1-api-rdqehkur6a-ey.a.run.app/orders";
return await ProcessApiRequest("POST", url, request);
}
/// <summary>
/// Retrieves user details from the TygaPay API using a user ID.
/// </summary>
/// <param name="userId">The ID of the user to retrieve.</param>
/// <returns>The user details as a dynamic object.</returns>
public async Task<object> GetUserByUserId(string userId)
{
string url = $"https://users-v1-api-rdqehkur6a-ey.a.run.app/user?userId={userId}";
return await ProcessApiRequest("GET", url);
}
/// <summary>
/// General method to process any API request to the TygaPay API.
/// </summary>
/// <param name="method">HTTP method (GET, POST, etc.)</param>
/// <param name="url">Endpoint URL.</param>
/// <param name="body">Body of the request, if applicable.</param>
/// <returns>The API response as a dynamic object.</returns>
private async Task<object> ProcessApiRequest(string method, string url, object body = null)
{
string jsonBody = body == null ? string.Empty : JsonConvert.SerializeObject(body);
string apiPath = ExtractApiPath(url);
string signature = SignApiRequest(jsonBody, apiPath);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), url)
{
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"),
};
request.Headers.Add("x-api-hash", signature);
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(responseContent);
}
/// <summary>
/// Extracts the API path from a URL to be used in signing the request.
/// </summary>
/// <param name="url">The full URL from which to extract the path and query.</param>
/// <returns>The extracted path and query string.</returns>
private string ExtractApiPath(string url)
{
Uri parsedUrl = new Uri(url);
return $"{parsedUrl.AbsolutePath}{parsedUrl.Query}";
}
/// <summary>
/// Signs the API request using HMAC SHA256 to generate a hash signature.
/// </summary>
/// <param name="body">The body of the request as a JSON string.</param>
/// <param name="apiPath">The API path extracted from the URL.</param>
/// <returns>A hexadecimal string of the hash signature.</returns>
private string SignApiRequest(string body, string apiPath)
{
string stringToSign = apiPath + body;
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(apiSecret));
byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
/// <summary>
/// Represents the request body for creating an order.
/// </summary>
public class OrderRequest
{
public string OrderNumber { get; set; }
public string Type { get; set; }
public string Email { get; set; }
public double Amount { get; set; }
public string NotifyUrl { get; set; }
public string ReturnUrl { get; set; }
}
class Program
{
static async Task Main(string[] args)
{
await TygaPaySandbox.RunExamples();
}
}
<?php
/**
* Refer to the API documentation here: https://tygapay.github.io/docs/
* Service class to handle interactions with TygaPay API.
*/
class TygaPayService
{
private $apiKey;
private $apiSecret;
/**
* Constructor for initializing the TygaPayService with API credentials.
*
* @param string $apiKey API key used for TygaPay API authentication.
* @param string $apiSecret Secret key used for signing API requests.
*/
public function __construct($apiKey, $apiSecret)
{
$this->apiKey = $apiKey;
$this->apiSecret = $apiSecret;
}
/**
* Creates an order with the TygaPay API.
*
* @param array $request Details of the order including type, email, amount, notifyUrl, and returnUrl.
* @return array|false The response from the TygaPay API or false on failure.
*/
public function createOrder($request)
{
$url = 'https://orders-v1-api-rdqehkur6a-ey.a.run.app/orders';
return $this->processApiRequest('POST', $url, $request);
}
/**
* Retrieves a user by their user ID from the TygaPay API.
*
* @param string $userId The user's unique identifier.
* @return array|false The user details from the API or false on failure.
*/
public function getUserByUserId($userId)
{
$url = "https://users-v1-api-rdqehkur6a-ey.a.run.app/user?userId={$userId}";
return $this->processApiRequest('GET', $url);
}
/**
* Processes an API request to the TygaPay API.
*
* @param string $method HTTP method (GET, POST, etc.).
* @param string $url Full URL to the API endpoint.
* @param array|null $body Body of the request if applicable.
* @return array|false The decoded JSON response from the API or false on failure.
*/
private function processApiRequest($method, $url, $body = null)
{
$apiPath = $this->extractApiPath($url);
echo "API PATH:\n";
print_r($apiPath);
$signature = $this->signApiRequest($body, $apiPath);
$options = [
'http' => [
'header' => "x-api-key: {$this->apiKey}\r\n" .
"Content-Type: application/json\r\n" .
"x-api-hash: {$signature}\r\n",
'method' => $method,
'ignore_errors' => true,
]
];
if ($body !== null) {
$options['http']['content'] = json_encode($body);
}
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === FALSE) {
throw new Exception("Error Processing Request");
}
return json_decode($response, true);
}
/**
* Extracts the API path from a full URL, used for signing requests.
*
* @param string $url The full URL.
* @return string Extracted path and query part of the URL.
*/
private function extractApiPath($url)
{
$parsedUrl = parse_url($url);
return $parsedUrl['path'] . (isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '');
}
/**
* Signs an API request using HMAC SHA256.
*
* @param array|null $body The body of the request, if applicable.
* @param string $apiPath The API path to be included in the signature.
* @return string The generated hash signature.
*/
private function signApiRequest($body, $apiPath)
{
$bodyQueryString = $body ? $this->buildQueryString($body) : '';
echo "\nBodyQueryString:\n";
print_r($bodyQueryString);
// Concatenate the API path and query string
$stringToSign = $apiPath . $bodyQueryString;
echo "\nStringToSign:\n";
print_r($stringToSign);
// Generate HMAC signature
$hash = hash_hmac('sha256', $stringToSign, $this->apiSecret);
echo "\nHash:\n";
print_r($hash);
return $hash;
}
private function buildQueryString($params, $prefix = '')
{
$query = [];
foreach ($params as $key => $value) {
if (is_array($value)) {
$newPrefix = $prefix === '' ? $key : $prefix . '.' . $key;
$query[] = $this->buildQueryString($value, $newPrefix);
} else {
$newKey = $prefix === '' ? $key : $prefix . '.' . $key;
$query[] = $newKey . '=' . $value;
}
}
return $query ? implode('&', $query) : '';
}
}
/**
* A sandbox class to demonstrate the use of the TygaPayService.
*/
class TygaPaySandbox
{
/**
* Runs examples of creating an order and retrieving a user by ID.
*/
public static function runExamples()
{
$apiKey = 'your-api-key';
$apiSecret = 'your-api-secret-key';
$service = new TygaPayService($apiKey, $apiSecret);
// $user = $service->getUserByUserId('test');
// echo "User Info:\n";
// print_r($user);
$order = $service->createOrder([
'orderNumber' => 'order-example-1-2',
'type' => 'payment',
'email' => 'example@gmail.com',
'amount' => 100,
'notifyUrl' => 'https://example.com/payment-webhook',
'returnUrl' => 'https://example.com/payment-completed'
]);
echo "Order Info:\n";
print_r($order);
}
}
// Running the examples
TygaPaySandbox::runExamples();
?>
Last updated