Masterpass Entegrasyonu
Masterpass Nedir? #
Masterpass, Mastercard'ın dijital ödeme çözümüdür. Kullanıcılar kartlarını Masterpass sisteminde kayıt ettikten sonra, cep telefonu numaraları ile hızlı ve güvenli ödeme yapabilirler.
Pazaryeri sistemi, standart kart ödemelerinin yanı sıra Masterpass ile de ödeme almayı destekler.
Avantajları #
- ✅ Hızlı Ödeme - Kullanıcı kart bilgisi girmez, sadece SMS onayı
- ✅ Güvenli - Kart bilgileri Masterpass tarafından saklanır
- ✅ Mobil Uyumlu - Mobil cihazlarda kolay kullanım
- ✅ Kayıtlı Kartlar - Kullanıcıların Masterpass'e kayıtlı kartları kullanılır
CreatePayment (Masterpass) #
Masterpass ile ödeme almak için özel bir endpoint kullanılır.
Endpoint #
TEST:
POST https://apitest.paynkolay.com.tr/marketplace/v1/payment/create/MASTERPASSPROD:
POST https://api.paynkolay.com.tr/marketplace/v1/payment/create/MASTERPASS/MASTERPASS eklenmesi gerekir.İstek Parametreleri #
Masterpass ödemesinde bankCard bilgileri gönderilmez. Bunun yerine gsm parametresi zorunludur.
{
"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'e Özel Parametreler #
| Parametre | Tip | Zorunlu | Açıklama |
|---|---|---|---|
| gsm | String | ✅ | Kullanıcının cep telefonu (başında +90 olmadan) |
GSM Format:
✅ Doğru: "5321234567"
❌ Yanlış: "+905321234567"
❌ Yanlış: "05321234567"Ortak Zorunlu Parametreler #
Standart CreatePayment ile aynı zorunlu parametreler:
- apiKey
- apiSecretKey
- trxCurrency
- trxAmount
- trxCode
- trxType
- callbackUrl
- sellerList (sellerExternalId, trxAmount, withholdingTax)
- shippingCost
- otherAmount
- marketplaceCode
GÖNDERİLMEYEN Parametreler #
Masterpass ödemesinde aşağıdaki parametreler gönderilmez:
- ❌ bankCard (kart bilgileri)
- ❌ installment
- ❌ isFetchInstallments
- ❌ encodedValue
- ❌ customerCardInfo
Yanıt #
{
"data": {
"refCode": "REF123456789",
"trxCode": "ORDER_12345",
"form": "PGh0bWw+...Masterpass HTML Form Base64..."
},
"success": true,
"responseCode": "200",
"responseMessage": "SUCCESS"
}Yanıt formatı standart CreatePayment ile aynıdır. form alanı Base64 encoded HTML içerir.
Masterpass İşlem Akışı #
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ıÖrnek Kod #
<?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 İşleme #
Masterpass ödemesinin callback işlemi standart ödeme ile aynıdır:
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');
});Kullanıcı Arayüzü Örneği #
Ödeme Yöntemi Seçimi #
<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 Gönderimi #
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 Özellikleri #
Kart Bilgisi Gerekmiyor #
// ❌ 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
}Taksit Desteği #
Masterpass ödemelerinde taksit seçenekleri Masterpass ekranında gösterilir. API isteğinde taksit parametresi gönderilmez.
Kayıtlı Kartlar #
GSM numarası kullanılarak kullanıcının Masterpass'e kayıtlı kartları otomatik olarak getirilir. Ek bir işlem gerekmez.
Hata Durumları #
Masterpass'e Kayıtlı Değil #
Kullanıcının GSM numarası Masterpass'e kayıtlı değilse, Masterpass ekranında kayıt olma seçeneği sunulur.
// 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.'
);
}Geçersiz 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 Standart Kart #
| Özellik | Masterpass | Standart Kart |
|---|---|---|
| Kart Bilgisi | ❌ Gerekmiyor | ✅ Gerekiyor |
| GSM | ✅ Zorunlu | ❌ Opsiyonel |
| Hız | ⚡ Çok Hızlı | 🐢 Daha Yavaş |
| Güvenlik | 🔒 Masterpass | 🔒 3D Secure |
| Kayıtlı Kart | ✅ Otomatik | ❌ Manuel |
| Mobil | 📱 Optimize | 💻 Standart |
Test Etme #
Masterpass test işlemleri için:
- Test GSM Numarası: Mastercard tarafından sağlanan test numaralarını kullanın
- Test Kartları: Masterpass test hesabına test kartları ekleyin
- Test Ortamı:
apitest.paynkolay.com.trkullanın
Sonraki Adımlar #
Masterpass entegrasyonunu tamamladıktan sonra:
- 1. Raporlama - Masterpass işlemlerini raporlayın
- 2. Ödeme İşlemleri - Standart kart ödemeleri
- 3. Ödeme Değişiklikleri - Masterpass iadesi