Masterpass Integration
What is Masterpass?
Section titled “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 using their mobile phone numbers.
The marketplace system supports payment collection with Masterpass as well as standard card payments.
Advantages
Section titled “Advantages”- ✅ Fast Payment - User doesn’t enter card details, only SMS confirmation
- ✅ Secure - Card information is stored by Masterpass
- ✅ Mobile Compatible - Easy to use on mobile devices
- ✅ Saved Cards - Users’ cards registered with Masterpass are used
CreatePayment (Masterpass)
Section titled “CreatePayment (Masterpass)”A special endpoint is used to accept payments with Masterpass.
Endpoint
Section titled “Endpoint”TEST:
POST https://apitest.paynkolay.com.tr/marketplace/v1/payment/create/MASTERPASSPROD:
POST https://api.paynkolay.com.tr/marketplace/v1/payment/create/MASTERPASSRequest Parameters
Section titled “Request Parameters”In Masterpass payments, bankCard information is not sent. Instead, the gsm parameter is required.
{ "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
Section titled “Masterpass-Specific Parameters”| Parameter | Type | Required | Description |
|---|---|---|---|
gsm | String | ✅ | User’s mobile phone number (without +90 prefix) |
GSM Format:
✅ Correct: "5321234567"❌ Wrong: "+905321234567"❌ Wrong: "05321234567"Common Required Parameters
Section titled “Common Required Parameters”Same required parameters as standard CreatePayment:
apiKeyapiSecretKeytrxCurrencytrxAmounttrxCodetrxTypecallbackUrlsellerListsellerList[].sellerExternalIdsellerList[].trxAmountsellerList[].withholdingTax
shippingCostotherAmountmarketplaceCode
Parameters NOT SENT
Section titled “Parameters NOT SENT”The following parameters are not sent in Masterpass payments:
- ❌
bankCard(card information) - ❌
installment - ❌
isFetchInstallments - ❌
encodedValue - ❌
customerCardInfo
Response
Section titled “Response”{ "data": { "refCode": "REF123456789", "trxCode": "ORDER_12345", "form": "PGh0bWw+...Masterpass HTML Form Base64..." }, "success": true, "responseCode": "200", "responseMessage": "SUCCESS"}The response format is the same as standard CreatePayment. The form field contains Base64 encoded HTML.
Masterpass Transaction Flow
Section titled “Masterpass Transaction Flow”sequenceDiagram participant User as User participant Your as Your System participant PNK as Pay N Kolay participant MP as Masterpass
User->>Your: Start payment with GSM number Your->>PNK: CreatePayment/MASTERPASS (gsm) PNK->>Your: HTML Form (Base64) Your->>Your: Base64 Decode Your->>User: Show Masterpass Form User->>MP: Login to Masterpass MP->>User: Show Saved Cards User->>MP: Select Card + SMS Confirmation MP->>PNK: Payment Result PNK->>Your: POST to callbackUrl Your->>User: Result PageExample Code
Section titled “Example Code”<?phpclass 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 formif ($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; }}
// Usagevar masterpass = new MasterpassPayment( Environment.GetEnvironmentVariable("API_SECRET_KEY"), Environment.GetEnvironmentVariable("MERCHANT_SECRET_KEY"), "MP12345", "https://apitest.paynkolay.com.tr/marketplace/v1");
// Create paymentvar 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 formif (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}import requestsimport hashlibimport base64import osimport 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()
# Usagemasterpass = MasterpassPayment( os.getenv('API_SECRET_KEY'), os.getenv('MERCHANT_SECRET_KEY'), 'MP12345', 'https://apitest.paynkolay.com.tr/marketplace/v1')
# Create paymentpayment = 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 formif payment.get('success') and payment.get('data', {}).get('form'): html_form = base64.b64decode(payment['data']['form']).decode('utf-8') # Display HTML to userconst 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; }}
// Usageconst masterpass = new MasterpassPayment( process.env.API_SECRET_KEY, process.env.MERCHANT_SECRET_KEY, 'MP12345', 'https://apitest.paynkolay.com.tr/marketplace/v1');
// Create paymentconst 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 formif (payment.success && payment.data.form) { const htmlForm = Buffer.from(payment.data.form, 'base64').toString('utf-8'); // Display HTML to user}Callback Processing
Section titled “Callback Processing”Callback processing for Masterpass payments is the same as standard payments:
app.post('/payment-callback', (req, res) => { const { trxCode, responseCode, referenceCode, authAmount, timestamp, hash, paymentSystem // Value "MASTERPASS" comes for Masterpass } = req.body;
// Verify hash const calculatedHash = calculateCallbackHash({ timestamp, referenceCode, trxCode, authAmount, responseCode }, apiSecretKey);
if (calculatedHash !== hash) { return res.status(400).send('Invalid hash'); }
// Is payment successful? if (responseCode === '00' || responseCode === '0000') { // Masterpass payment successful console.log('Masterpass payment successful:', trxCode); updateOrderStatus(trxCode, 'PAID', 'MASTERPASS'); } else { console.log('Masterpass payment failed:', responseCode); updateOrderStatus(trxCode, 'FAILED'); }
res.status(200).send('OK');});User Interface Example
Section titled “User Interface Example”Payment Method Selection
Section titled “Payment Method Selection”<div class="payment-methods"> <label> <input type="radio" name="paymentMethod" value="card"> Credit/Debit Card </label>
<label> <input type="radio" name="paymentMethod" value="masterpass"> <img src="/images/masterpass-logo.png" alt="Masterpass"> Pay with Masterpass </label></div>
<div id="card-form" style="display:none;"> <!-- Standard card form --> <input type="text" name="cardNumber" placeholder="Card Number"> <input type="text" name="cardHolder" placeholder="Cardholder Name"> <!-- ... --></div>
<div id="masterpass-form" style="display:none;"> <label>Your Mobile Phone Number:</label> <input type="tel" name="gsm" placeholder="5XX XXX XX XX" pattern="5[0-9]{9}"> <small>Your mobile phone number registered with Masterpass</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
Section titled “Form Submission”async function processPayment(formData) { const paymentMethod = formData.get('paymentMethod');
if (paymentMethod === 'masterpass') { // Payment with Masterpass const gsm = formData.get('gsm').replace(/\s/g, ''); // Remove spaces
// GSM validation if (!/^5[0-9]{9}$/.test(gsm)) { alert('Enter a valid mobile phone number'); 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 and display const htmlForm = atob(result.data.form); document.body.innerHTML = htmlForm; }
} else { // Standard card payment // ... }}Masterpass Features
Section titled “Masterpass Features”No Card Information Required
Section titled “No Card Information Required”// ❌ WRONG - Don't send card information for Masterpass{ "bankCard": { "cardNumber": "...", "cvv": "..." }, "gsm": "5321234567"}
// ✅ CORRECT - Only GSM is sufficient{ "gsm": "5321234567" // bankCard is NOT SENT}Installment Support
Section titled “Installment Support”Installment options for Masterpass payments are shown on the Masterpass screen. The installment parameter is not sent in the API request.
Saved Cards
Section titled “Saved Cards”Using the GSM number, the user’s cards registered with Masterpass are automatically retrieved. No additional action is required.
Error Conditions
Section titled “Error Conditions”Not Registered with Masterpass
Section titled “Not Registered with Masterpass”If the user’s GSM number is not registered with Masterpass, the Masterpass screen offers a registration option.
// Inform the userif (paymentMethod === 'masterpass') { alert( 'You need to have a Masterpass account to pay with Masterpass. ' + 'If you don\'t have an account, you can register with Masterpass on the payment screen.' );}Invalid GSM
Section titled “Invalid GSM”function validateGSM(gsm) { // Starts with 5, total 10 digits if (!/^5[0-9]{9}$/.test(gsm)) { throw new Error('Invalid GSM format. Should be 10 digits without leading 0.'); } return true;}Masterpass vs Standard Card
Section titled “Masterpass vs Standard Card”| Feature | Masterpass | Standard Card |
|---|---|---|
| Card Information | ❌ Not Required | ✅ Required |
| GSM | ✅ Required | ❌ Optional |
| Speed | ⚡ Very Fast | 🐢 Slower |
| Security | 🔒 Masterpass | 🔒 3D Secure |
| Saved Card | ✅ Automatic | ❌ Manual |
| Mobile | 📱 Optimized | 💻 Standard |
Testing
Section titled “Testing”For Masterpass test transactions:
- Test GSM Number: Use test numbers provided by Mastercard
- Test Cards: Add test cards to Masterpass test account
- Test Environment: Use
apitest.paynkolay.com.tr
Next Steps
Section titled “Next Steps”After completing the Masterpass integration:
- Reporting - Report Masterpass transactions
- Payment Operations - Standard card payments
- Payment Modifications - Masterpass refunds