Esc
Start typing to search...

Masterpass Integration

What is Masterpass? #

Masterpass is Mastercard's digital payment solution. After users register their cards in the Masterpass system, they can make fast and secure payments with their mobile phone numbers.

The marketplace system supports accepting payments with Masterpass as well as standard card payments.

Advantages #

  • Fast Payment - User does not enter card info, only SMS confirmation
  • Secure - Card info is stored by Masterpass
  • Mobile Friendly - Easy use on mobile devices
  • Stored Cards - Users' cards registered in Masterpass are used

CreatePayment (Masterpass) #

A special endpoint is used to accept payments with Masterpass.

Endpoint #

TEST:

POST https://apitest.paynkolay.com.tr/marketplace/v1/payment/create/MASTERPASS

PROD:

POST https://api.paynkolay.com.tr/marketplace/v1/payment/create/MASTERPASS

Request Parameters #

In Masterpass payment, bankCard information is not sent. Instead, the gsm parameter is mandatory.

{
  "apiKey": "calculated_api_key",
  "apiSecretKey": "sx_value",
  "gsm": "5321234567",
  "trxCurrency": "TRY",
  "trxAmount": 150.00,
  "trxCode": "ORDER_12345",
  "trxType": "SALES",
  "callbackUrl": "https://yoursite.com/payment-callback",
  "sellerList": [
    {
      "sellerExternalId": "SELLER_001",
      "trxAmount": 100.00,
      "withholdingTax": 0.80
    },
    {
      "sellerExternalId": "SELLER_002",
      "trxAmount": 50.00,
      "withholdingTax": 0.40
    }
  ],
  "shippingCost": 0.00,
  "otherAmount": 0.00,
  "marketplaceCode": "MP12345"
}

Masterpass Specific Parameters #

ParameterTypeRequiredDescription
gsmStringUser's mobile phone (without +90 prefix)

GSM Format:

✅ Correct: "5321234567"
❌ Wrong: "+905321234567"
❌ Wrong: "05321234567"

Common Mandatory Parameters #

Common mandatory parameters with standard CreatePayment:

  • apiKey
  • apiSecretKey
  • trxCurrency
  • trxAmount
  • trxCode
  • trxType
  • callbackUrl
  • sellerList (sellerExternalId, trxAmount, withholdingTax)
  • shippingCost
  • otherAmount
  • marketplaceCode

OMITTED Parameters #

The following parameters are not sent in Masterpass payment:

  • ❌ bankCard (card info)
  • ❌ installment
  • ❌ isFetchInstallments
  • ❌ encodedValue
  • ❌ customerCardInfo

Response #

{
  "data": {
    "refCode": "REF123456789",
    "trxCode": "ORDER_12345",
    "form": "PGh0bWw+...Masterpass HTML Form Base64..."
  },
  "success": true,
  "responseCode": "200",
  "responseMessage": "SUCCESS"
}

Response format is the same as standard CreatePayment. form field contains Base64 encoded HTML.


Masterpass Transaction Flow #

sequenceDiagram
    participant User as Kullanıcı
    participant Your as Sizin Sistem
    participant PNK as Paynkolay
    participant MP as Masterpass

    User->>Your: GSM numarası ile ödeme başlat
    Your->>PNK: CreatePayment/MASTERPASS (gsm)
    PNK->>Your: HTML Form (Base64)
    Your->>Your: Base64 Decode
    Your->>User: Masterpass Form Göster
    User->>MP: Masterpass'e Giriş
    MP->>User: Kayıtlı Kartları Göster
    User->>MP: Kart Seç + SMS Onay
    MP->>PNK: Ödeme Sonucu
    PNK->>Your: callbackUrl'e POST
    Your->>User: Sonuç Sayfası

Example Code #

example.php
<?php
class MasterpassPayment {
    private $apiSecretKey;
    private $merchantSecretKey;
    private $mpCode;
    private $baseURL;

    public function __construct($apiSecretKey, $merchantSecretKey, $mpCode, $baseURL) {
        $this->apiSecretKey = $apiSecretKey;
        $this->merchantSecretKey = $merchantSecretKey;
        $this->mpCode = $mpCode;
        $this->baseURL = $baseURL;
    }

    private function calculateApiKey() {
        $hashString = $this->apiSecretKey . '|' . $this->merchantSecretKey;
        $hash = hash('sha512', $hashString, true);
        return base64_encode($hash);
    }

    public function createMasterpassPayment($paymentData) {
        $apiKey = $this->calculateApiKey();

        $data = [
            'apiKey' => $apiKey,
            'apiSecretKey' => $this->apiSecretKey,
            'gsm' => $paymentData['gsm'],
            'trxCurrency' => 'TRY',
            'trxAmount' => $paymentData['amount'],
            'trxCode' => $paymentData['orderId'],
            'trxType' => 'SALES',
            'callbackUrl' => $paymentData['callbackUrl'],
            'sellerList' => $paymentData['sellers'],
            'shippingCost' => $paymentData['shippingCost'] ?? 0,
            'otherAmount' => $paymentData['otherAmount'] ?? 0,
            'marketplaceCode' => $this->mpCode
        ];

        $ch = curl_init($this->baseURL . '/payment/create/MASTERPASS');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }
}

// Usage
$masterpass = new MasterpassPayment(
    getenv('API_SECRET_KEY'),
    getenv('MERCHANT_SECRET_KEY'),
    'MP12345',
    'https://apitest.paynkolay.com.tr/marketplace/v1'
);

$payment = $masterpass->createMasterpassPayment([
    'gsm' => '5321234567',
    'amount' => 250.00,
    'orderId' => 'ORDER_789',
    'callbackUrl' => 'https://yoursite.com/payment-callback',
    'sellers' => [
        [
            'sellerExternalId' => 'SELLER_001',
            'trxAmount' => 250.00,
            'withholdingTax' => 2.00
        ]
    ]
]);

// Display form
if ($payment['success'] && isset($payment['data']['form'])) {
    $htmlForm = base64_decode($payment['data']['form']);
    echo $htmlForm;
}
?>
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Collections.Generic;

public class MasterpassPayment
{
    private readonly string apiSecretKey;
    private readonly string merchantSecretKey;
    private readonly string mpCode;
    private readonly string baseURL;

    public MasterpassPayment(string apiSecretKey, string merchantSecretKey, string mpCode, string baseURL)
    {
        this.apiSecretKey = apiSecretKey;
        this.merchantSecretKey = merchantSecretKey;
        this.mpCode = mpCode;
        this.baseURL = baseURL;
    }

    private string CalculateApiKey()
    {
        string hashString = $"{apiSecretKey}|{merchantSecretKey}";
        using (var sha512 = SHA512.Create())
        {
            byte[] bytes = sha512.ComputeHash(Encoding.UTF8.GetBytes(hashString));
            return Convert.ToBase64String(bytes);
        }
    }

    public async Task<JsonDocument> CreateMasterpassPayment(PaymentData paymentData)
    {
        string apiKey = CalculateApiKey();

        var data = new
        {
            apiKey,
            apiSecretKey,
            gsm = paymentData.Gsm,
            trxCurrency = "TRY",
            trxAmount = paymentData.Amount,
            trxCode = paymentData.OrderId,
            trxType = "SALES",
            callbackUrl = paymentData.CallbackUrl,
            sellerList = paymentData.Sellers,
            shippingCost = paymentData.ShippingCost,
            otherAmount = paymentData.OtherAmount,
            marketplaceCode = mpCode
        };

        using var client = new HttpClient();
        var jsonContent = new StringContent(
            JsonSerializer.Serialize(data),
            Encoding.UTF8,
            "application/json"
        );

        var response = await client.PostAsync($"{baseURL}/payment/create/MASTERPASS", jsonContent);
        var jsonString = await response.Content.ReadAsStringAsync();
        return JsonDocument.Parse(jsonString);
    }
}

public class PaymentData
{
    public string Gsm { get; set; }
    public decimal Amount { get; set; }
    public string OrderId { get; set; }
    public string CallbackUrl { get; set; }
    public List<Seller> Sellers { get; set; }
    public decimal ShippingCost { get; set; }
    public decimal OtherAmount { get; set; }
}

public class Seller
{
    public string sellerExternalId { get; set; }
    public decimal trxAmount { get; set; }
    public decimal withholdingTax { get; set; }
}

// Usage
var masterpass = new MasterpassPayment(
    Environment.GetEnvironmentVariable("API_SECRET_KEY"),
    Environment.GetEnvironmentVariable("MERCHANT_SECRET_KEY"),
    "MP12345",
    "https://apitest.paynkolay.com.tr/marketplace/v1"
);

// Create payment
var payment = await masterpass.CreateMasterpassPayment(new PaymentData
{
    Gsm = "5321234567",
    Amount = 250.00m,
    OrderId = "ORDER_789",
    CallbackUrl = "https://yoursite.com/payment-callback",
    Sellers = new List<Seller>
    {
        new Seller
        {
            sellerExternalId = "SELLER_001",
            trxAmount = 250.00m,
            withholdingTax = 2.00m
        }
    },
    ShippingCost = 0,
    OtherAmount = 0
});

// Decode and display form
if (payment.RootElement.GetProperty("success").GetBoolean() &&
    payment.RootElement.GetProperty("data").TryGetProperty("form", out var formElement))
{
    byte[] formBytes = Convert.FromBase64String(formElement.GetString());
    string htmlForm = Encoding.UTF8.GetString(formBytes);
    // Display HTML to user
}
const axios = require('axios');
const crypto = require('crypto');

class MasterpassPayment {
  constructor(apiSecretKey, merchantSecretKey, mpCode, baseURL) {
    this.apiSecretKey = apiSecretKey;
    this.merchantSecretKey = merchantSecretKey;
    this.mpCode = mpCode;
    this.baseURL = baseURL;
  }

  calculateApiKey() {
    const hashString = this.apiSecretKey + '|' + this.merchantSecretKey;
    const hash = crypto.createHash('sha512').update(hashString, 'utf8').digest();
    return hash.toString('base64');
  }

  async createMasterpassPayment(paymentData) {
    const apiKey = this.calculateApiKey();

    const response = await axios.post(
      `${this.baseURL}/payment/create/MASTERPASS`,
      {
        apiKey,
        apiSecretKey: this.apiSecretKey,
        gsm: paymentData.gsm,
        trxCurrency: 'TRY',
        trxAmount: paymentData.amount,
        trxCode: paymentData.orderId,
        trxType: 'SALES',
        callbackUrl: paymentData.callbackUrl,
        sellerList: paymentData.sellers,
        shippingCost: paymentData.shippingCost || 0,
        otherAmount: paymentData.otherAmount || 0,
        marketplaceCode: this.mpCode
      }
    );

    return response.data;
  }
}

// Usage
const masterpass = new MasterpassPayment(
  process.env.API_SECRET_KEY,
  process.env.MERCHANT_SECRET_KEY,
  'MP12345',
  'https://apitest.paynkolay.com.tr/marketplace/v1'
);

// Create payment
const payment = await masterpass.createMasterpassPayment({
  gsm: '5321234567',
  amount: 250.00,
  orderId: 'ORDER_789',
  callbackUrl: 'https://yoursite.com/payment-callback',
  sellers: [
    {
      sellerExternalId: 'SELLER_001',
      trxAmount: 250.00,
      withholdingTax: 2.00
    }
  ],
  shippingCost: 0,
  otherAmount: 0
});

// Decode and display form
if (payment.success && payment.data.form) {
  const htmlForm = Buffer.from(payment.data.form, 'base64').toString('utf-8');
  // Display HTML to user
}
import requests
import hashlib
import base64
import os
import json

class MasterpassPayment:
    def __init__(self, api_secret_key, merchant_secret_key, mp_code, base_url):
        self.api_secret_key = api_secret_key
        self.merchant_secret_key = merchant_secret_key
        self.mp_code = mp_code
        self.base_url = base_url

    def calculate_api_key(self):
        hash_string = f"{self.api_secret_key}|{self.merchant_secret_key}"
        hash_bytes = hashlib.sha512(hash_string.encode('utf-8')).digest()
        return base64.b64encode(hash_bytes).decode('utf-8')

    def create_masterpass_payment(self, payment_data):
        api_key = self.calculate_api_key()

        data = {
            'apiKey': api_key,
            'apiSecretKey': self.api_secret_key,
            'gsm': payment_data['gsm'],
            'trxCurrency': 'TRY',
            'trxAmount': payment_data['amount'],
            'trxCode': payment_data['orderId'],
            'trxType': 'SALES',
            'callbackUrl': payment_data['callbackUrl'],
            'sellerList': payment_data['sellers'],
            'shippingCost': payment_data.get('shippingCost', 0),
            'otherAmount': payment_data.get('otherAmount', 0),
            'marketplaceCode': self.mp_code
        }

        response = requests.post(
            f"{self.base_url}/payment/create/MASTERPASS",
            json=data
        )

        return response.json()

# Usage
masterpass = MasterpassPayment(
    os.getenv('API_SECRET_KEY'),
    os.getenv('MERCHANT_SECRET_KEY'),
    'MP12345',
    'https://apitest.paynkolay.com.tr/marketplace/v1'
)

# Create payment
payment = masterpass.create_masterpass_payment({
    'gsm': '5321234567',
    'amount': 250.00,
    'orderId': 'ORDER_789',
    'callbackUrl': 'https://yoursite.com/payment-callback',
    'sellers': [
        {
            'sellerExternalId': 'SELLER_001',
            'trxAmount': 250.00,
            'withholdingTax': 2.00
        }
    ],
    'shippingCost': 0,
    'otherAmount': 0
})

# Decode and display form
if payment.get('success') and payment.get('data', {}).get('form'):
    html_form = base64.b64decode(payment['data']['form']).decode('utf-8')
    # Display HTML to user

Callback Processing #

Masterpass payment callback process is the same as standard payment:

app.post('/payment-callback', (req, res) => {
  const {
    trxCode,
    responseCode,
    referenceCode,
    authAmount,
    timestamp,
    hash,
    paymentSystem  // Masterpass için "MASTERPASS" değeri gelir
  } = req.body;

  // Hash doğrula
  const calculatedHash = calculateCallbackHash({
    timestamp,
    referenceCode,
    trxCode,
    authAmount,
    responseCode
  }, apiSecretKey);

  if (calculatedHash !== hash) {
    return res.status(400).send('Invalid hash');
  }

  // Ödeme başarılı mı?
  if (responseCode === '00' || responseCode === '0000') {
    // Masterpass ile ödeme başarılı
    console.log('Masterpass ödeme başarılı:', trxCode);
    updateOrderStatus(trxCode, 'PAID', 'MASTERPASS');
  } else {
    console.log('Masterpass ödeme başarısız:', responseCode);
    updateOrderStatus(trxCode, 'FAILED');
  }

  res.status(200).send('OK');
});

User Interface Example #

Payment Method Selection #

<div class="payment-methods">
  <label>
    <input type="radio" name="paymentMethod" value="card">
    Kredi/Banka Kartı
  </label>

  <label>
    <input type="radio" name="paymentMethod" value="masterpass">
    <img src="/images/masterpass-logo.png" alt="Masterpass">
    Masterpass ile Öde
  </label>
</div>

<div id="card-form" style="display:none;">
  <!-- Standart kart formu -->
  <input type="text" name="cardNumber" placeholder="Kart Numarası">
  <input type="text" name="cardHolder" placeholder="Kart Üzerindeki İsim">
  <!-- ... -->
</div>

<div id="masterpass-form" style="display:none;">
  <label>Cep Telefonu Numaranız:</label>
  <input type="tel" name="gsm" placeholder="5XX XXX XX XX" pattern="5[0-9]{9}">
  <small>Masterpass'e kayıtlı cep telefonu numaranız</small>
</div>

<script>
document.querySelectorAll('input[name="paymentMethod"]').forEach(radio => {
  radio.addEventListener('change', (e) => {
    document.getElementById('card-form').style.display =
      e.target.value === 'card' ? 'block' : 'none';

    document.getElementById('masterpass-form').style.display =
      e.target.value === 'masterpass' ? 'block' : 'none';
  });
});
</script>

Form Submission #

async function processPayment(formData) {
  const paymentMethod = formData.get('paymentMethod');

  if (paymentMethod === 'masterpass') {
    // Masterpass ile ödeme
    const gsm = formData.get('gsm').replace(/\s/g, ''); // Boşlukları temizle

    // GSM validasyonu
    if (!/^5[0-9]{9}$/.test(gsm)) {
      alert('Geçerli bir cep telefonu numarası girin');
      return;
    }

    const response = await fetch('/api/payment/masterpass', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        gsm: gsm,
        amount: orderTotal,
        orderId: orderId
      })
    });

    const result = await response.json();

    if (result.success) {
      // Base64 decode ve göster
      const htmlForm = atob(result.data.form);
      document.body.innerHTML = htmlForm;
    }

  } else {
    // Standart kart ile ödeme
    // ...
  }
}

Masterpass Features #

Card Info Not Required #

// ❌ YANLIŞ - Masterpass için kart bilgisi göndermeyin
// ❌ WRONG - Do not send card info for Masterpass
{
  "bankCard": {
    "cardNumber": "...",
    "cvv": "..."
  },
  "gsm": "5321234567"
}

// ✅ DOĞRU - Sadece GSM yeterli
// ✅ CORRECT - Only GSM is sufficient
{
  "gsm": "5321234567"
  // bankCard GÖNDERİLMEZ / OMITTED
}

Installment Support #

In Masterpass payments, installment options are shown on the Masterpass screen. Installment parameter is not sent in the API request.

Stored Cards #

Using the GSM number, user's cards registered in Masterpass are automatically retrieved. No additional action is required.


Error Situations #

Not Registered to Masterpass #

If user's GSM number is not registered to Masterpass, a registration option is offered on the Masterpass screen.

// Kullanıcıyı bilgilendir
if (paymentMethod === 'masterpass') {
  alert(
    'Masterpass ile ödeme yapmak için Masterpass hesabınızın olması gerekmektedir. ' +
    'Eğer hesabınız yoksa, ödeme ekranında Masterpass\'e kayıt olabilirsiniz.'
  );
}

Invalid GSM #

function validateGSM(gsm) {
  // Başında 5, toplam 10 hane
  if (!/^5[0-9]{9}$/.test(gsm)) {
    throw new Error('Geçersiz GSM formatı. Başında 0 olmadan 10 hane olmalı.');
  }
  return true;
}

Masterpass vs Standard Card #

FeatureMasterpassStandard Card
Card Info❌ Not Required✅ Required
GSM✅ Mandatory❌ Optional
Speed⚡ Very Fast🐢 Slower
Security🔒 Masterpass🔒 3D Secure
Stored Card✅ Automatic❌ Manual
Mobile📱 Optimize💻 Standard

Testing #

For Masterpass test operations:

  • Test GSM Number: Use test numbers provided by Mastercard
  • Test Cards: Add test cards to Masterpass test account
  • Test Environment: apitest.paynkolay.com.tr use

Next Steps #

After completing Masterpass integration: