ArgusDocs
English Türkçe

Code samples

On this page

A small, complete API client in curl, PHP, Node.js, C#, Go and Python.

You need no SDK: the API is plain HTTPS and JSON. Each sample makes the three calls most integrations need:

  1. Create and confirm a payment with a pm_… id. The id comes from a card tokenized in the browser or saved earlier. A card saved to a customer works only when the payment names that customer. When the response asks for 3D Secure, send the customer to the bank.
  2. Read the payment on your return page, after you verify the signature of the redirect.
  3. Refund the payment.

To pay with a card that your server received, send payment_method_data.card instead of payment_method. Server-to-server card payments has complete checkout and return handlers in PHP and Node.js.

A payment can be refunded only after its status is succeeded. A payment that needs 3D Secure is requires_action until the customer comes back, so the samples refund only a payment that has succeeded. In your own code, steps 2 and 3 run in later requests. The samples put all three in one file to stay short.

All samples read the secret key from ARGUS_SECRET_KEY and the base URL from ARGUS_API_BASE, for example https://api.pf.organizer.tr/v1. They send an Idempotency-Key with every POST and turn an error response into an exception.

The Webhooks guide shows how to verify a webhook signature in each language.

The API reference shows the request of every operation in curl, Node.js, PHP, Python and Go. Pick a language once and every operation shows it. The Node.js, PHP, Python and Go samples there read the same two variables.

curl

curl -X POST https://api.pf.organizer.tr/v1/payment_intents \
  -H "Authorization: Bearer sk_sandbox_YOUR_KEY" \
  -H "Idempotency-Key: order-SIP-2026-10423" \
  -H "Content-Type: application/json" \
  -d '{"amount": 12500, "currency": "try", "confirm": true, "payment_method": "pm_01J9ZQA2B4C6D8E1F3G5H7J9K2", "payment_method_data": {"billing_details": {"name": "Ayşe Yılmaz", "address": {"line1": "Caferağa Mah. Moda Cad. No:12", "city": "Kadıköy", "country": "TR"}}}, "return_url": "https://modakitabevi.com.tr/odeme/sonuc", "metadata": {"order_id": "SIP-2026-10423"}}'

curl https://api.pf.organizer.tr/v1/payment_intents/pi_01J9ZQ4V8K2M3N5P7R9T1W3Y5A \
  -H "Authorization: Bearer sk_sandbox_YOUR_KEY"

curl -X POST https://api.pf.organizer.tr/v1/refunds \
  -H "Authorization: Bearer sk_sandbox_YOUR_KEY" \
  -H "Idempotency-Key: refund-order-SIP-2026-10423" \
  -H "Content-Type: application/json" \
  -d '{"payment_intent": "pi_01J9ZQ4V8K2M3N5P7R9T1W3Y5A"}'

PHP

PHP 8.1 or later, with the bundled cURL extension.

<?php
final class ArgusClient
{
    public function __construct(
        private string $secretKey,
        private string $baseUrl = 'https://api.pf.organizer.tr/v1',
    ) {
    }

    public function request(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
    {
        $headers = ['Authorization: Bearer ' . $this->secretKey, 'Content-Type: application/json'];
        if ($idempotencyKey !== null) {
            $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
        }
        $ch = curl_init($this->baseUrl . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
        ]);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }
        $raw = curl_exec($ch);
        if ($raw === false) {
            throw new RuntimeException('Network error: ' . curl_error($ch));
        }
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $data = json_decode($raw, true);
        if ($status >= 400) {
            $error = $data['error'] ?? [];
            throw new RuntimeException(($error['code'] ?? 'error') . ': ' . ($error['message'] ?? '') . ' (' . ($error['request_id'] ?? '') . ')', $status);
        }
        return $data;
    }
}

$argus = new ArgusClient(getenv('ARGUS_SECRET_KEY'), getenv('ARGUS_API_BASE') ?: 'https://api.pf.organizer.tr/v1');

// The return page is the same script: it skips step 1 when the customer comes back.
if (!isset($_GET['payment_intent'])) {
    // 1. Create and confirm.
    $payment = $argus->request('POST', '/payment_intents', [
        'amount' => 12500,
        'currency' => 'try',
        'confirm' => true,
        'payment_method' => $_POST['payment_method'],
        'payment_method_data' => ['billing_details' => [
            'name' => 'Ayşe Yılmaz',
            'address' => ['line1' => 'Caferağa Mah. Moda Cad. No:12', 'city' => 'Kadıköy', 'country' => 'TR'],
        ]],
        'return_url' => 'https://modakitabevi.com.tr/odeme/sonuc',
        'metadata' => ['order_id' => 'SIP-2026-10423'],
    ], 'order-SIP-2026-10423');

    if ($payment['status'] === 'requires_action' && $payment['next_action']['type'] === 'redirect_to_url') {
        header('Location: ' . $payment['next_action']['redirect_to_url']['url']);
        exit;
    }
}

// 2. On the return page: verify argus_signature first (see the server-to-server guide), then read the payment.
$payment = $argus->request('GET', '/payment_intents/' . rawurlencode($_GET['payment_intent'] ?? $payment['id']));
$paid = $payment['status'] === 'succeeded';

// 3. Refund, once the payment has succeeded.
if ($paid) {
    $refund = $argus->request('POST', '/refunds', ['payment_intent' => $payment['id']], 'refund-order-SIP-2026-10423');
}

Node.js

Node.js 18 or later (built-in fetch). The sample is an ES module: save it as .mjs, or set "type": "module" in package.json.

const BASE = process.env.ARGUS_API_BASE ?? 'https://api.pf.organizer.tr/v1';
const KEY = process.env.ARGUS_SECRET_KEY;

export async function argus(method, path, body, idempotencyKey) {
  const headers = { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' };
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
  const res = await fetch(BASE + path, { method, headers, body: body ? JSON.stringify(body) : undefined });
  const data = await res.json();
  if (!res.ok) {
    const err = new Error(`${data.error?.code ?? 'error'}: ${data.error?.message ?? ''}`);
    err.status = res.status;
    err.error = data.error;
    throw err;
  }
  return data;
}

// 1. Create and confirm (paymentMethodId comes from the browser).
export async function createPayment(paymentMethodId) {
  const payment = await argus('POST', '/payment_intents', {
    amount: 12500,
    currency: 'try',
    confirm: true,
    payment_method: paymentMethodId,
    payment_method_data: {
      billing_details: {
        name: 'Ayşe Yılmaz',
        address: { line1: 'Caferağa Mah. Moda Cad. No:12', city: 'Kadıköy', country: 'TR' },
      },
    },
    return_url: 'https://modakitabevi.com.tr/odeme/sonuc',
    metadata: { order_id: 'SIP-2026-10423' },
  }, 'order-SIP-2026-10423');
  if (payment.status === 'requires_action' && payment.next_action.type === 'redirect_to_url') {
    return { redirectTo: payment.next_action.redirect_to_url.url };
  }
  return { payment };
}

// 2. On the return page: verify argus_signature first, then read the payment.
export async function getPayment(id) {
  return argus('GET', `/payment_intents/${encodeURIComponent(id)}`);
}

// 3. Refund.
export async function refund(paymentIntentId, amount) {
  return argus('POST', '/refunds', { payment_intent: paymentIntentId, amount }, `refund-${paymentIntentId}-${amount ?? 'full'}`);
}

C# / .NET

.NET 6 or later, HttpClient and System.Text.Json.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

public sealed class ArgusClient
{
    private readonly HttpClient _http;

    public ArgusClient(string secretKey, string baseUrl = "https://api.pf.organizer.tr/v1/")
    {
        _http = new HttpClient { BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/"), Timeout = TimeSpan.FromSeconds(60) };
        _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", secretKey);
    }

    public async Task<JsonElement> SendAsync(HttpMethod method, string path, object? body = null, string? idempotencyKey = null)
    {
        using var request = new HttpRequestMessage(method, path);
        if (body != null) request.Content = JsonContent.Create(body);
        if (idempotencyKey != null) request.Headers.Add("Idempotency-Key", idempotencyKey);
        using var response = await _http.SendAsync(request);
        var json = await response.Content.ReadFromJsonAsync<JsonElement>();
        if (!response.IsSuccessStatusCode)
        {
            var error = json.GetProperty("error");
            throw new HttpRequestException($"{error.GetProperty("code")}: {error.GetProperty("message")} ({error.GetProperty("request_id")})");
        }
        return json;
    }
}

public static class Example
{
    public static async Task Main()
    {
        var argus = new ArgusClient(Environment.GetEnvironmentVariable("ARGUS_SECRET_KEY")!,
            Environment.GetEnvironmentVariable("ARGUS_API_BASE") ?? "https://api.pf.organizer.tr/v1/");

        // 1. Create and confirm.
        var payment = await argus.SendAsync(HttpMethod.Post, "payment_intents", new
        {
            amount = 12500,
            currency = "try",
            confirm = true,
            payment_method = "pm_01J9ZQA2B4C6D8E1F3G5H7J9K2",
            payment_method_data = new
            {
                billing_details = new
                {
                    name = "Ayşe Yılmaz",
                    address = new { line1 = "Caferağa Mah. Moda Cad. No:12", city = "Kadıköy", country = "TR" },
                },
            },
            return_url = "https://modakitabevi.com.tr/odeme/sonuc",
            metadata = new { order_id = "SIP-2026-10423" },
        }, "order-SIP-2026-10423");

        if (payment.GetProperty("status").GetString() == "requires_action")
        {
            var url = payment.GetProperty("next_action").GetProperty("redirect_to_url").GetProperty("url").GetString();
            Console.WriteLine($"Redirect the customer to {url}");
        }

        // 2. On the return page: verify argus_signature first, then read the payment.
        var id = payment.GetProperty("id").GetString();
        payment = await argus.SendAsync(HttpMethod.Get, $"payment_intents/{Uri.EscapeDataString(id!)}");

        // 3. Refund, once the payment has succeeded.
        if (payment.GetProperty("status").GetString() == "succeeded")
        {
            var refund = await argus.SendAsync(HttpMethod.Post, "refunds", new { payment_intent = id }, "refund-order-SIP-2026-10423");
            Console.WriteLine(refund.GetProperty("status").GetString());
        }
    }
}

Go

Standard library only.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"
)

type Client struct {
	Key  string
	Base string
	HTTP *http.Client
}

type APIError struct {
	Status int
	Body   struct {
		Error struct {
			Type        string `json:"type"`
			Code        string `json:"code"`
			DeclineCode string `json:"decline_code"`
			Message     string `json:"message"`
			RequestID   string `json:"request_id"`
		} `json:"error"`
	}
}

func (e *APIError) Error() string {
	return fmt.Sprintf("%d %s: %s (%s)", e.Status, e.Body.Error.Code, e.Body.Error.Message, e.Body.Error.RequestID)
}

func (c *Client) Do(method, path string, body any, idempotencyKey string, out any) error {
	var payload *bytes.Reader
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			return err
		}
		payload = bytes.NewReader(b)
	} else {
		payload = bytes.NewReader(nil)
	}
	req, err := http.NewRequest(method, c.Base+path, payload)
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+c.Key)
	req.Header.Set("Content-Type", "application/json")
	if idempotencyKey != "" {
		req.Header.Set("Idempotency-Key", idempotencyKey)
	}
	res, err := c.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		apiErr := &APIError{Status: res.StatusCode}
		_ = json.NewDecoder(res.Body).Decode(&apiErr.Body)
		return apiErr
	}
	return json.NewDecoder(res.Body).Decode(out)
}

type PaymentIntent struct {
	ID         string `json:"id"`
	Status     string `json:"status"`
	Amount     int64  `json:"amount"`
	NextAction *struct {
		Type          string `json:"type"`
		RedirectToURL struct {
			URL string `json:"url"`
		} `json:"redirect_to_url"`
	} `json:"next_action"`
}

func main() {
	base := os.Getenv("ARGUS_API_BASE")
	if base == "" {
		base = "https://api.pf.organizer.tr/v1"
	}
	argus := &Client{Key: os.Getenv("ARGUS_SECRET_KEY"), Base: base, HTTP: &http.Client{Timeout: 60 * time.Second}}

	// 1. Create and confirm.
	var pi PaymentIntent
	err := argus.Do("POST", "/payment_intents", map[string]any{
		"amount":         12500,
		"currency":       "try",
		"confirm":        true,
		"payment_method": "pm_01J9ZQA2B4C6D8E1F3G5H7J9K2",
		"payment_method_data": map[string]any{
			"billing_details": map[string]any{
				"name":    "Ayşe Yılmaz",
				"address": map[string]string{"line1": "Caferağa Mah. Moda Cad. No:12", "city": "Kadıköy", "country": "TR"},
			},
		},
		"return_url": "https://modakitabevi.com.tr/odeme/sonuc",
		"metadata":   map[string]string{"order_id": "SIP-2026-10423"},
	}, "order-SIP-2026-10423", &pi)
	if err != nil {
		fmt.Println(err)
		return
	}
	if pi.Status == "requires_action" && pi.NextAction != nil {
		fmt.Println("Redirect the customer to", pi.NextAction.RedirectToURL.URL)
	}

	// 2. On the return page: verify argus_signature first, then read the payment.
	if err := argus.Do("GET", "/payment_intents/"+url.PathEscape(pi.ID), nil, "", &pi); err != nil {
		fmt.Println(err)
		return
	}

	// 3. Refund, once the payment has succeeded.
	if pi.Status != "succeeded" {
		fmt.Println(pi.Status)
		return
	}
	var refund map[string]any
	if err := argus.Do("POST", "/refunds", map[string]any{"payment_intent": pi.ID}, "refund-order-SIP-2026-10423", &refund); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(pi.Status, refund["status"])
}

Python

Python 3.8 or later with the requests package.

import os

import requests

BASE = os.environ.get("ARGUS_API_BASE", "https://api.pf.organizer.tr/v1")
KEY = os.environ["ARGUS_SECRET_KEY"]


class ArgusError(Exception):
    def __init__(self, status, error):
        super().__init__(f"{status} {error.get('code')}: {error.get('message')} ({error.get('request_id')})")
        self.status = status
        self.error = error


def argus(method, path, body=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {KEY}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    res = requests.request(method, BASE + path, json=body, headers=headers, timeout=60)
    data = res.json()
    if res.status_code >= 400:
        raise ArgusError(res.status_code, data.get("error", {}))
    return data


# 1. Create and confirm.
payment = argus("POST", "/payment_intents", {
    "amount": 12500,
    "currency": "try",
    "confirm": True,
    "payment_method": "pm_01J9ZQA2B4C6D8E1F3G5H7J9K2",
    "payment_method_data": {
        "billing_details": {
            "name": "Ayşe Yılmaz",
            "address": {"line1": "Caferağa Mah. Moda Cad. No:12", "city": "Kadıköy", "country": "TR"},
        },
    },
    "return_url": "https://modakitabevi.com.tr/odeme/sonuc",
    "metadata": {"order_id": "SIP-2026-10423"},
}, idempotency_key="order-SIP-2026-10423")

if payment["status"] == "requires_action":
    print("Redirect the customer to", payment["next_action"]["redirect_to_url"]["url"])

# 2. On the return page: verify argus_signature first, then read the payment.
payment = argus("GET", f"/payment_intents/{payment['id']}")

# 3. Refund, once the payment has succeeded.
if payment["status"] == "succeeded":
    refund = argus("POST", "/refunds", {"payment_intent": payment["id"]}, idempotency_key="refund-order-SIP-2026-10423")
    print(payment["status"], refund["status"])

Handling html_form

Some banks need a form post instead of a redirect. When next_action.type is html_form, do not redirect. Return next_action.html_form.html as the body of your response to the customer's browser, with the content type text/html.

Next: Read how the payment flow works in Card payments and 3D Secure, then receive results with Webhooks.