React Native Masterpass SDK for retter.io
npm install @retter/rn-masterpassReact Native Masterpass Turkey SDK. A wrapper library to use the Masterpass Turkey JS library (designed for web) in React Native.
``bash`
npm install @retter/rn-masterpass
`bash`
yarn add @retter/rn-masterpass
This package requires the following peer dependencies:
`bash`
npm install react react-native react-native-webviewor
yarn add react react-native react-native-webview
Requirements:
- react >= 16.8.0react-native >= 0.60.0
- react-native-webview >= 13.15.0
-
`typescript
import MasterPass, { MasterPassView } from '@retter/rn-masterpass';
const masterPass = MasterPass.getInstance({
token: 'your-token',
referenceNo: 'your-reference-no',
userId: 'user-phone-number',
sendSms: 'Y', // 'Y' or 'N'
sendSmsLanguage: 'tr', // 'tr' or 'en'
macroMerchantId: 'your-merchant-id',
clientIp: 'client-ip-address',
sdkUrl: 'https://masterpass.com/sdk.js',
clientId: 'your-client-id',
serviceUrl: 'https://masterpass.com/service',
});
`
`tsx
import React from 'react';
import { View } from 'react-native';
import MasterPass, { MasterPassView } from '@retter/rn-masterpass';
const PaymentScreen = () => {
const masterPass = MasterPass.getInstance({
// ... config
});
return (
onEvent={(data) => {
console.log('Event:', data);
}}
onRequest={async (message, body) => {
// Handle requests from web
return null;
}}
/>
);
};
`
#### getInstance(config: MasterPassTurkeyArgs): MasterPass
Creates a new SDK instance. Each call creates a new instance, allowing you to initialize with different tokens as needed.
Parameters:
`typescript`
interface MasterPassTurkeyArgs {
token: string; // Masterpass token
referenceNo: string; // Reference number
userId: string; // User phone number
sendSmsLanguage: string; // SMS language ('tr' or 'en')
sendSms: 'N' | 'Y'; // Send SMS
macroMerchantId: string; // Merchant ID
clientIp: string; // Client IP address
sdkUrl: string; // Masterpass SDK URL
clientId: string; // Client ID
serviceUrl: string; // Service URL
}
#### updateConfig(config: Partial
Dynamically updates the config. Changed values are automatically applied to forms in WebView.
`typescript`
masterPass.updateConfig({
token: 'new-token',
referenceNo: 'new-reference-no',
});
#### registrationCheck(): Promise
Checks the user's Masterpass registration status.
Return Value:
`typescript
interface RegistrationCheckResult {
result: boolean;
action: RegistrationCheckAction;
}
enum RegistrationCheckAction {
linkCards = 'link-cards', // Card linking required
listCards = 'list-cards', // Registered cards can be listed
showMpOption = 'show-mp-option' // Show Masterpass option
}
`
Usage Example:
`typescript`
try {
const result = await masterPass.registrationCheck();
switch (result.action) {
case 'link-cards':
// Redirect to card linking flow
await masterPass.linkCards();
break;
case 'list-cards':
// List registered cards
const cards = await masterPass.listCards();
break;
case 'show-mp-option':
// Show Masterpass option
break;
}
} catch (error) {
console.error('Registration check failed:', error);
}
#### linkCards(): Promise
Links user's cards to Masterpass account.
Return Value:
`typescript
interface OtpResult {
result: boolean;
action: OtpAction;
type: OtpType;
}
enum OtpAction {
verifyOtp = 'verify-otp', // OTP verification required
listCards = 'list-cards', // Cards successfully listed
redirect3D = 'redirect-3D' // 3D Secure redirect
}
enum OtpType {
bank = 'bank', // Bank OTP
masterPass = 'mp', // Masterpass OTP
mPin = 'mpin' // MPIN
}
`
Usage Example:
`typescript`
try {
const result = await masterPass.linkCards();
if (result.action === 'verify-otp') {
// Show OTP screen
// Get OTP code from user
const otpCode = '123456';
await masterPass.verifyOtp(otpCode, result.type);
}
} catch (error) {
console.error('Link cards failed:', error);
}
#### listCards(): Promise
Lists user's registered cards.
Return Value:
`typescript
interface CardResult {
result: boolean;
action: CardAction;
cards: CardModel[];
}
enum CardAction {
hideMpOption = 'hide-mp-option', // Hide Masterpass option
purchase = 'purchase' // Purchase can be made
}
interface CardModel {
BankIca: string; // Bank ICA code
CardStatus: string; // Card status
IsMasterPassMember: 'Y' | 'N'; // Is Masterpass member?
Name: string; // Card name
ProductName: string; // Product name
UniqueId: string; // Unique ID
Value1: string; // Masked card number
}
`
Usage Example:
`typescript${card.Name}: ${card.Value1}
try {
const result = await masterPass.listCards();
if (result.result && result.cards.length > 0) {
result.cards.forEach(card => {
console.log();`
});
}
} catch (error) {
console.error('List cards failed:', error);
}
#### deleteCard(cardName: string): Promise
Deletes a registered card.
Parameters:
- cardName: string - Name of the card to delete
Return Value:
`typescript`
interface DeleteCardResult {
result: boolean;
}
Usage Example:
`typescript`
try {
const result = await masterPass.deleteCard('My Card');
if (result.result) {
console.log('Card deleted successfully');
}
} catch (error) {
console.error('Delete card failed:', error);
}
#### resendOtp(): Promise
Resends the OTP code.
Usage Example:
`typescript`
try {
const result = await masterPass.resendOtp();
// OTP sent, notify user
} catch (error) {
console.error('Resend OTP failed:', error);
}
#### verifyOtp(code: string, type: OtpType): Promise
Verifies the OTP code.
Parameters:
- code: string - OTP codetype: OtpType
- - OTP type ('bank', 'mp', 'mpin')
Usage Example:
`typescript
import { OtpType } from '@retter/rn-masterpass';
try {
const result = await masterPass.verifyOtp('123456', OtpType.bank);
if (result.action === 'list-cards') {
// OTP verified, cards can be listed
const cards = await masterPass.listCards();
} else if (result.action === 'redirect-3D') {
// 3D Secure redirect
}
} catch (error) {
console.error('Verify OTP failed:', error);
}
`
#### purchase(args: PurchaseArgs): Promise
Performs a purchase transaction. Can purchase with a new card or registered card.
Purchase with New Card:
`typescript
import { PurchaseNewArgs } from '@retter/rn-masterpass';
const purchaseArgs: PurchaseNewArgs = {
orderNo: 'ORDER123',
referenceNo: 'REF123',
amount: 100.50,
installmentCount: 1,
card: {
cardHolderName: 'John Doe',
number: '5555555555555555',
cvc: '123',
expMonth: 12,
expYear: 2025,
accountAliasName: 'My Card', // Optional: to save the card
},
additionalParameters: { // Optional
// Additional parameters
},
};
try {
const result = await masterPass.purchase(purchaseArgs);
if (result.action === 'verify-otp') {
// OTP verification required
await masterPass.verifyOtp('123456', result.type);
} else if (result.action === 'redirect-3D') {
// 3D Secure redirect
// Redirect to 3D Secure page with result.url
}
} catch (error) {
console.error('Purchase failed:', error);
}
`
Purchase with Registered Card:
`typescript
import { PurchaseExistingArgs } from '@retter/rn-masterpass';
const purchaseArgs: PurchaseExistingArgs = {
orderNo: 'ORDER123',
referenceNo: 'REF123',
amount: 100.50,
installmentCount: 1,
cardName: 'My Card', // Registered card name
token: 'optional-token', // Optional
additionalParameters: { // Optional
// Additional parameters
},
};
try {
const result = await masterPass.purchase(purchaseArgs);
// ...
} catch (error) {
console.error('Purchase failed:', error);
}
`
Return Value:
`typescript
interface PurchaseResult {
result: boolean;
action: PurchaseAction;
token: string;
purchaseType: PurchaseType;
type: OtpType;
url: string; // 3D Secure URL
}
enum PurchaseAction {
verifyOtp = 'verify-otp', // OTP verification required
redirect3D = 'redirect-3D' // 3D Secure redirect
}
enum PurchaseType {
NewCardRegistration = 0, // Payment with new card registration
WithRegisteredCard = 1, // Payment with registered card
DirectPayment = 2 // Direct payment
}
`
#### setOnEvent(callback: (data: any) => void): void
Sets the event callback. Listens to events from WebView.
`typescript`
masterPass.setOnEvent((data) => {
console.log('Event received:', data);
if (data.status === 'ready') {
console.log('MasterPass is ready');
}
});
#### setOnRequest(callback: (message: string, body: any) => Promise
Handles requests from web.
`typescript`
masterPass.setOnRequest(async (message, body) => {
console.log('Request received:', message, body);
// Handle request and return result
return { success: true };
});
React component that manages the WebView.
Props:
`typescript`
interface MasterPassViewProps {
masterPass: MasterPass; // MasterPass instance
onEvent?: (data: any) => void; // Event callback
onRequest?: (message: string, body: any) => Promise
style?: any; // Additional style (optional)
}
Usage:
`tsx`
onEvent={(data) => {
console.log('Event:', data);
}}
onRequest={async (message, body) => {
// Request handling
return null;
}}
style={{ opacity: 0 }} // WebView should be hidden
/>
`tsx
import React, { useState, useEffect } from 'react';
import { View, Text, Button, TextInput, Alert } from 'react-native';
import MasterPass, { MasterPassView, OtpType } from '@retter/rn-masterpass';
const PaymentScreen = () => {
const [masterPass] = useState(() =>
MasterPass.getInstance({
token: 'your-token',
referenceNo: 'REF123',
userId: '5551234567',
sendSms: 'Y',
sendSmsLanguage: 'tr',
macroMerchantId: 'MERCHANT123',
clientIp: '192.168.1.1',
sdkUrl: 'https://masterpass.com/sdk.js',
clientId: 'CLIENT123',
serviceUrl: 'https://masterpass.com/service',
})
);
const [cards, setCards] = useState([]);
const [otpCode, setOtpCode] = useState('');
const [showOtpInput, setShowOtpInput] = useState(false);
const [otpType, setOtpType] = useState
useEffect(() => {
checkRegistration();
}, []);
const checkRegistration = async () => {
try {
const result = await masterPass.registrationCheck();
if (result.action === 'list-cards') {
await loadCards();
}
} catch (error) {
Alert.alert('Error', error.message);
}
};
const loadCards = async () => {
try {
const result = await masterPass.listCards();
if (result.result) {
setCards(result.cards);
}
} catch (error) {
Alert.alert('Error', error.message);
}
};
const handlePurchase = async (cardName?: string) => {
try {
const purchaseArgs = cardName
? {
orderNo: 'ORDER123',
referenceNo: 'REF123',
amount: 100.50,
installmentCount: 1,
cardName,
}
: {
orderNo: 'ORDER123',
referenceNo: 'REF123',
amount: 100.50,
installmentCount: 1,
card: {
cardHolderName: 'John Doe',
number: '5555555555555555',
cvc: '123',
expMonth: 12,
expYear: 2025,
},
};
const result = await masterPass.purchase(purchaseArgs);
if (result.action === 'verify-otp') {
setOtpType(result.type);
setShowOtpInput(true);
} else if (result.action === 'redirect-3D') {
// 3D Secure redirect
Alert.alert('3D Secure', URL: ${result.url});
}
} catch (error) {
Alert.alert('Error', error.message);
}
};
const handleVerifyOtp = async () => {
try {
const result = await masterPass.verifyOtp(otpCode, otpType);
setShowOtpInput(false);
setOtpCode('');
if (result.action === 'list-cards') {
await loadCards();
}
} catch (error) {
Alert.alert('Error', error.message);
}
};
return (
{cards.map((card) => (
title="Pay with This Card"
onPress={() => handlePurchase(card.Name)}
/>
))}
title="Pay with New Card"
onPress={() => handlePurchase()}
/>
{showOtpInput && (
value={otpCode}
onChangeText={setOtpCode}
keyboardType="numeric"
/>
)}
);
};
export default PaymentScreen;
`
All type definitions are exported from the package:
`typescript`
import {
MasterPassTurkeyArgs,
RegistrationCheckResult,
RegistrationCheckAction,
OtpResult,
OtpAction,
OtpType,
CardResult,
CardAction,
CardModel,
DeleteCardResult,
PurchaseArgs,
PurchaseNewArgs,
PurchaseExistingArgs,
PurchaseResult,
PurchaseAction,
PurchaseType,
PurchaseCardModel,
} from '@retter/rn-masterpass';
- WebView should be hidden (opacity: 0). The MasterPassView component does this automatically.getInstance
- The method creates a new instance each time. This allows you to initialize with different tokens as needed (e.g., after fetching a token from your backend)..then()`.
- All methods return Promises, you can use async/await or
- Methods throw Errors in error cases, catch them with try-catch.
ISC
For questions: GitHub Issues