diff --git a/README.md b/README.md
index c87b9a0..7f9e86d 100644
--- a/README.md
+++ b/README.md
@@ -1,168 +1,161 @@
# 🚀 React Native PlugPag Nitro
-**High-performance PagSeguro PlugPag integration with TypeScript-first enum-based API**
+High-performance PagSeguro PlugPag integration for React Native with TypeScript support and real-time events.
-[](https://www.npmjs.com/package/react-native-plugpag-nitro)
-[](https://www.npmjs.com/package/react-native-plugpag-nitro)
-[](https://github.com/mCodex/react-native-plugpag-nitro/blob/main/LICENSE)
-[](https://nitro.margelo.com/)
+[](https://www.npmjs.com/package/react-native-plugpag-nitro)
+[](LICENSE)
+[](https://nitro.margelo.com/)
----
-
-## ✨ Features
-
-> **Built with [Nitro Modules](https://nitro.margelo.com/) for **~10x faster** performance than traditional bridges**
-
-- 🔥 **High Performance** - Direct JSI bindings, zero-copy data transfer
-- 🎯 **TypeScript Enums** - Type-safe payment types, installment types, and error codes
-- 💰 **All Payment Types** - Credit, Debit, PIX, and Voucher support
-- 📱 **Real-time Events** - Payment progress monitoring with event hooks
-- 🎣 **React Hooks** - Modern hook-based API for seamless integration
-- 📱 **Android Focused** - Optimized for PlugPag terminals
-- 🛡️ **TypeScript Native** - Full type safety and IntelliSense support
-- ⚡ **Simple API** - Clean function-based approach with payment presets
+**Features**: TypeScript-first • Real-time Events • High Performance JSI • Credit/Debit/PIX Support
----
-
-## 🚀 Quick Start
+## Installation
```bash
npm install react-native-plugpag-nitro react-native-nitro-modules
```
-> **Requirements**: React Native ≥ 0.72, Android API ≥ 21
+> Requires React Native ≥ 0.72, Android API ≥ 21
-### Simple Enum-Based Approach
+## Quick Start
```typescript
import {
- PaymentType,
- InstallmentType,
- ErrorCode,
- doPayment,
initializeAndActivatePinPad,
- PaymentPresets,
- isTransactionSuccessful
-} from 'react-native-plugpag-nitro';
-
-// Initialize terminal once
-await initializeAndActivatePinPad('your-activation-code');
-
-// Simple credit payment using presets
-const result = await doPayment(PaymentPresets.creditCard(2500, 1));
-
-// Or use enum types directly for custom payments
-const customPayment = await doPayment({
- amount: 5000, // R$ 50.00
- type: PaymentType.CREDIT,
- installmentType: InstallmentType.BUYER_INSTALLMENT,
- installments: 3,
- printReceipt: true,
- userReference: 'order-123'
-});
-
-if (isTransactionSuccessful(result)) {
- console.log('Payment approved!', result);
-}
-```
-
-### Modern Hook-Based Approach
-
-```typescript
-import {
+ doPayment,
+ useTransactionEvent,
PaymentType,
- usePaymentFlow,
- useTransactionPaymentEvent,
- PaymentPresets
+ ErrorCode
} from 'react-native-plugpag-nitro';
-function PaymentComponent() {
- const paymentFlow = usePaymentFlow();
- const paymentEvent = useTransactionPaymentEvent();
+function PaymentScreen() {
+ const paymentEvent = useTransactionEvent();
const handlePayment = async () => {
- try {
- const result = await paymentFlow.executePayment(
- PaymentPresets.creditCard(2500, 1)
- );
-
- if (paymentFlow.isTransactionSuccessful) {
- console.log('Payment successful!', result);
- }
- } catch (error) {
- console.error('Payment failed:', error);
+ // Initialize terminal
+ await initializeAndActivatePinPad('YOUR_ACTIVATION_CODE');
+
+ // Process payment
+ const result = await doPayment({
+ amount: 2500, // R$ 25.00 in cents
+ type: PaymentType.CREDIT
+ });
+
+ if (result.result === ErrorCode.OK) {
+ console.log('Payment approved!', result);
}
};
return (
-
-
+ {/* Real-time payment events */}
{paymentEvent.code > 0 && (
- Status: {paymentEvent.eventName}
+ Status: {paymentEvent.message}
)}
- {paymentFlow.isProcessing && }
+
);
}
```
----
+## API Reference
-## 📚 API Reference
+### Core Functions
-### 🔧 Enums
+#### `doPayment(options)`
+Process payments with type-safe enums.
-#### PaymentType
```typescript
-enum PaymentType {
- CREDIT = 1, // Credit card
- DEBIT = 2, // Debit card
- VOUCHER = 3, // Voucher/meal card
- PIX = 5 // PIX instant payment
-}
+const result = await doPayment({
+ amount: 2500, // Amount in cents
+ type: PaymentType.CREDIT, // CREDIT | DEBIT | VOUCHER | PIX
+ installmentType?: InstallmentType.BUYER_INSTALLMENT, // Optional
+ installments?: 3, // Optional
+ printReceipt?: true // Optional
+});
```
-#### InstallmentType
+#### `useTransactionEvent()`
+Real-time payment event monitoring hook.
+
```typescript
-enum InstallmentType {
- NO_INSTALLMENT = 1, // À vista (no installments)
- SELLER_INSTALLMENT = 2, // Parcelado pelo vendedor
- BUYER_INSTALLMENT = 3 // Parcelado pelo comprador
-}
+const paymentEvent = useTransactionEvent();
+// Returns: { code: number, message: string, customMessage?: string }
```
-#### ErrorCode
+### Enums
+
```typescript
+enum PaymentType {
+ CREDIT = 1, // Credit card
+ DEBIT = 2, // Debit card
+ VOUCHER = 3, // Voucher/meal card
+ PIX = 5 // PIX instant payment
+}
+
enum ErrorCode {
OK = 0, // Success
OPERATION_ABORTED = -1, // Operation aborted
- AUTHENTICATION_FAILED = -2, // Authentication failed
- COMMUNICATION_ERROR = -3, // Communication error
- NO_PRINTER_DEVICE = -4, // No printer device
- NO_TRANSACTION_DATA = -5 // No transaction data
+ COMMUNICATION_ERROR = -3, // Connection error
+ // ... more error codes
}
```
-#### PaymentEventCode
+### Other Functions
+
+- `initializeAndActivatePinPad(code)` - Initialize terminal
+- `refundPayment({ transactionCode, transactionId })` - Refund transaction
+- `getTerminalSerialNumber()` - Get terminal serial
+- `doAbort()` - Abort current transaction
+- `print(filePath)` - Print receipt from file
+```
+
+## Error Handling
+
```typescript
-enum PaymentEventCode {
- CARD_INSERTED = 1, // Card inserted
- CARD_REMOVED = 2, // Card removed
- WAITING_CARD = 3, // Waiting for card
- CARD_READ = 4, // Card read successfully
- PAYMENT_PROCESSING = 5, // Payment processing
- PAYMENT_COMPLETED = 6, // Payment completed
- PAYMENT_CANCELLED = 7, // Payment cancelled
- // ... and more event codes
+try {
+ const result = await doPayment({ amount: 2500, type: PaymentType.CREDIT });
+
+ if (result.result !== ErrorCode.OK) {
+ // Handle specific errors
+ switch (result.result) {
+ case ErrorCode.OPERATION_ABORTED:
+ console.log('Payment cancelled by user');
+ break;
+ case ErrorCode.COMMUNICATION_ERROR:
+ console.log('Connection error - check terminal');
+ break;
+ default:
+ console.log('Payment failed:', result.message);
+ }
+ return;
+ }
+
+ console.log('Payment successful!', result);
+} catch (error) {
+ console.error('Payment error:', error.message);
}
```
+## Contributing
+
+```bash
+git clone https://github.com/mCodex/react-native-plugpag-nitro.git
+cd react-native-plugpag-nitro
+yarn install
+yarn example android
+```
+
+## License
+
+MIT - see [LICENSE](LICENSE) for details.
+
+## Links
+
+- [📚 Nitro Modules](https://nitro.margelo.com/)
+- [🏢 PagSeguro PlugPag](https://dev.pagseguro.uol.com.br/)
+- [🐛 Issues](https://github.com/mCodex/react-native-plugpag-nitro/issues)
+
### 💳 Core Functions
#### `initializeAndActivatePinPad(activationCode: string)`
@@ -196,18 +189,6 @@ const result = await doPayment({
});
```
-#### `doPaymentWithEvents(options: PaymentOptions)`
-Processes a payment with real-time event monitoring.
-
-```typescript
-const result = await doPaymentWithEvents({
- amount: 2500,
- type: PaymentType.CREDIT,
- installmentType: InstallmentType.NO_INSTALLMENT
-});
-// Events are automatically tracked via useTransactionPaymentEvent hook
-```
-
#### `refundPayment(options)`
Refunds a previous payment transaction.
@@ -220,89 +201,43 @@ const result = await refundPayment({
```
### 🎣 React Hooks
-
-#### `usePaymentFlow()`
-Comprehensive payment hook with built-in state management and event tracking.
+#### `useTransactionEvent()`
+Real-time payment event monitoring hook to track status updates during transactions.
```typescript
-const {
- isProcessing, // boolean - payment in progress
- currentTransaction, // PlugpagTransactionResult | null
- paymentEvent, // Current payment event
- executePayment, // Function to execute payment
- resetFlow, // Reset flow state
- isTransactionSuccessful, // boolean - transaction success status
- transactionError // string | null - error message
-} = usePaymentFlow();
-
-// Usage
-const handlePayment = async () => {
- try {
- const result = await executePayment({
- amount: 2500,
- type: PaymentType.CREDIT
- });
-
- if (isTransactionSuccessful) {
- console.log('Payment successful!');
- }
- } catch (error) {
- console.error('Payment failed:', transactionError);
+const paymentEvent = useTransactionEvent();
+
+useEffect(() => {
+ if (paymentEvent.code > 0) {
+ console.log('Payment event:', paymentEvent.eventName);
}
-};
+}, [paymentEvent]);
```
-#### `useTransactionPaymentEvent()`
-Real-time payment event monitoring hook.
+### 🎣 React Hooks
+#### `useTransactionEvent()`
+Real-time payment event monitoring hook to track status updates during transactions.
```typescript
-const paymentEvent = useTransactionPaymentEvent();
+const paymentEvent = useTransactionEvent();
// paymentEvent contains:
// {
-// code: number, // PaymentEventCode
-// eventName?: string, // Human-readable event name
-// userReference?: string, // User reference
-// amount?: string, // Amount
-// resetEvent?: () => void // Function to reset event
+// code: PaymentEventCode, // Event code
+// message: string, // Event message
+// customMessage?: string // Custom message if any
// }
-// Usage in component
useEffect(() => {
if (paymentEvent.code > 0) {
- console.log('Payment event:', paymentEvent.eventName);
+ console.log('Payment event:', paymentEvent.message);
}
}, [paymentEvent]);
```
-### 🎯 Payment Presets
-
-Quick payment setup with predefined configurations:
-
-```typescript
-// Credit card payments
-PaymentPresets.creditCard(amount, installments?)
-PaymentPresets.creditCard(10000, 3) // R$ 100.00 in 3x
-
-// Debit card
-PaymentPresets.debitCard(2500) // R$ 25.00
-
-// PIX payments
-PaymentPresets.pix(5000) // R$ 50.00
-
-// Voucher
-PaymentPresets.voucher(1500) // R$ 15.00
-```
-
### 🔧 Utility Functions
```typescript
-// Check if transaction was successful
-isTransactionSuccessful(result: PlugpagTransactionResult): boolean
-
-// Get error message from result
-getTransactionError(result: PlugpagTransactionResult): string | null
-
// Get terminal serial number
getTerminalSerialNumber(): string
@@ -314,40 +249,35 @@ doAbort(): Promise
// Print custom receipt from file
print(filePath: string): Promise
-
-// Reprint last customer receipt
-reprintCustomerReceipt(): Promise
```
---
## 💡 Usage Examples
-### Hook-Based Payment Flow (Recommended)
+### Real-time Event Monitoring with Payment
```typescript
import React, { useState, useEffect } from 'react';
import {
PaymentType,
- InstallmentType,
- PaymentEventCode,
- usePaymentFlow,
- useTransactionPaymentEvent,
- PaymentPresets,
+ ErrorCode,
+ doPayment,
+ useTransactionEvent,
initializeAndActivatePinPad
} from 'react-native-plugpag-nitro';
-function ModernPaymentScreen() {
+function PaymentScreen() {
const [isInitialized, setIsInitialized] = useState(false);
- const paymentFlow = usePaymentFlow();
- const paymentEvent = useTransactionPaymentEvent();
+ const [isProcessing, setIsProcessing] = useState(false);
+ const paymentEvent = useTransactionEvent();
// Initialize terminal on mount
useEffect(() => {
const initialize = async () => {
try {
const result = await initializeAndActivatePinPad('403938');
- if (result.result === 0) {
+ if (result.result === ErrorCode.OK) {
setIsInitialized(true);
}
} catch (error) {
@@ -358,26 +288,6 @@ function ModernPaymentScreen() {
initialize();
}, []);
- // Monitor payment events
- useEffect(() => {
- if (paymentEvent.code > 0) {
- console.log('Payment event:', paymentEvent.eventName);
-
- // Handle specific events
- switch (paymentEvent.code) {
- case PaymentEventCode.CARD_INSERTED:
- console.log('Card inserted, please wait...');
- break;
- case PaymentEventCode.PAYMENT_PROCESSING:
- console.log('Processing payment...');
- break;
- case PaymentEventCode.PAYMENT_COMPLETED:
- console.log('Payment completed!');
- break;
- }
- }
- }, [paymentEvent]);
-
const handleCreditPayment = async () => {
if (!isInitialized) {
Alert.alert('Error', 'Terminal not initialized');
@@ -385,272 +295,61 @@ function ModernPaymentScreen() {
}
try {
- const result = await paymentFlow.executePayment({
- amount: 2500, // R$ 25.00
- type: PaymentType.CREDIT,
- installmentType: InstallmentType.NO_INSTALLMENT,
- userReference: `payment-${Date.now()}`
+ setIsProcessing(true);
+ const result = await doPayment({
+ amount: 2500,
+ type: PaymentType.CREDIT
});
- if (paymentFlow.isTransactionSuccessful) {
- Alert.alert('Success', 'Payment approved!', [
- { text: 'OK', onPress: () => paymentFlow.resetFlow() }
- ]);
+ if (result.result === ErrorCode.OK) {
+ Alert.alert('Success', 'Payment approved!');
} else {
- Alert.alert('Failed', paymentFlow.transactionError || 'Payment failed');
+ Alert.alert('Failed', result.message || 'Payment failed');
}
} catch (error) {
Alert.alert('Error', error.message);
- }
- };
-
- const handlePixPayment = async () => {
- try {
- const result = await paymentFlow.executePayment(
- PaymentPresets.pix(5000) // R$ 50.00
- );
-
- if (paymentFlow.isTransactionSuccessful) {
- Alert.alert('PIX Success', 'PIX payment completed!');
- }
- } catch (error) {
- Alert.alert('PIX Error', error.message);
+ } finally {
+ setIsProcessing(false);
}
};
return (
-
- Terminal: {isInitialized ? '✅ Ready' : '❌ Not Ready'}
-
+ Terminal: {isInitialized ? '✅ Ready' : '❌ Not Ready'}
- {/* Payment Event Display */}
+ {/* Real-time Event Display */}
{paymentEvent.code > 0 && (
-
- Status: {paymentEvent.eventName}
-
- )}
-
- {/* Processing Indicator */}
- {paymentFlow.isProcessing && (
-
-
- Processing payment...
+
+ Status: {paymentEvent.message}
+ Code: {paymentEvent.code}
)}
-
- {/* Transaction Result Display */}
- {paymentFlow.currentTransaction && (
-
- Last Transaction:
- Code: {paymentFlow.currentTransaction.transactionCode}
- Amount: R$ {(parseInt(paymentFlow.currentTransaction.amount) / 100).toFixed(2)}
- Status: {paymentFlow.isTransactionSuccessful ? '✅ Approved' : '❌ Declined'}
- Date: {paymentFlow.currentTransaction.date} {paymentFlow.currentTransaction.time}
-
- )}
-
- );
-}
-```
-
-### Basic Payment Flow (Function-Based)
-
-```typescript
-import React, { useState } from 'react';
-import {
- PaymentType,
- InstallmentType,
- ErrorCode,
- doPayment,
- doPaymentWithEvents,
- initializeAndActivatePinPad,
- isTransactionSuccessful,
- getTransactionError,
- PaymentPresets
-} from 'react-native-plugpag-nitro';
-
-function BasicPaymentScreen() {
- const [isProcessing, setIsProcessing] = useState(false);
- const [lastPayment, setLastPayment] = useState(null);
-
- const handleInitialize = async () => {
- try {
- const result = await initializeAndActivatePinPad('403938');
- if (result.result === ErrorCode.OK) {
- Alert.alert('Success', 'Terminal activated successfully!');
- } else {
- Alert.alert('Error', result.errorMessage || 'Failed to activate terminal');
- }
- } catch (error) {
- Alert.alert('Error', error.message);
- }
- };
-
- const handleCreditPayment = async () => {
- try {
- setIsProcessing(true);
-
- // Using preset for simplicity
- const result = await doPayment(PaymentPresets.creditCard(2500, 1));
- setLastPayment(result);
-
- if (isTransactionSuccessful(result)) {
- Alert.alert('Success', 'Payment approved!');
- } else {
- const errorMessage = getTransactionError(result);
- Alert.alert('Payment Failed', errorMessage || 'Unknown error');
- }
- } catch (error) {
- Alert.alert('Error', error.message);
- } finally {
- setIsProcessing(false);
- }
- };
-
- const handlePaymentWithEvents = async () => {
- try {
- setIsProcessing(true);
-
- // Payment with automatic event tracking
- const result = await doPaymentWithEvents({
- amount: 5000, // R$ 50.00
- type: PaymentType.CREDIT,
- installmentType: InstallmentType.BUYER_INSTALLMENT,
- installments: 3
- });
-
- if (isTransactionSuccessful(result)) {
- Alert.alert('Success', 'Payment with events completed!');
- }
- } catch (error) {
- Alert.alert('Error', error.message);
- } finally {
- setIsProcessing(false);
- }
- };
-
- return (
-
-
-
-
-
-
-
- {lastPayment && (
-
- Last Transaction:
- Code: {lastPayment.transactionCode}
- Amount: {lastPayment.amount}
- Status: {isTransactionSuccessful(lastPayment) ? 'Approved' : 'Declined'}
-
- )}
);
}
```
-### Real-time Event Monitoring
+### Error Handling
```typescript
-import { useTransactionPaymentEvent, PaymentEventCode } from 'react-native-plugpag-nitro';
-
-function PaymentEventMonitor() {
- const paymentEvent = useTransactionPaymentEvent();
-
- const getEventColor = (code: number) => {
- if (code >= PaymentEventCode.CARD_INSERTED && code <= PaymentEventCode.WAITING_CARD) {
- return '#007AFF'; // Blue for card events
- } else if (code === PaymentEventCode.PAYMENT_PROCESSING) {
- return '#FF9500'; // Orange for processing
- } else if (code === PaymentEventCode.PAYMENT_COMPLETED) {
- return '#34C759'; // Green for success
- }
- return '#8E8E93'; // Gray for others
- };
-
- return (
-
- {paymentEvent.code > 0 && (
-
-
- {paymentEvent.eventName || `Event Code: ${paymentEvent.code}`}
-
- {paymentEvent.amount && (
- Amount: {paymentEvent.amount}
- )}
-
- )}
-
- );
-}
-```
-
-### PIX Payment Example
-
-```typescript
-const handlePixPayment = async () => {
- try {
- const result = await doPayment({
- amount: 2500,
- type: PaymentType.PIX,
- installmentType: InstallmentType.NO_INSTALLMENT,
- printReceipt: true,
- userReference: 'pix-payment-001'
- });
-
- if (isTransactionSuccessful(result)) {
- Alert.alert('PIX Success', 'PIX payment completed!');
- }
- } catch (error) {
- Alert.alert('PIX Error', error.message);
- }
-};
-```
-
----
-
-## 🚨 Error Handling
-
-```typescript
-import {
- isTransactionSuccessful,
- getTransactionError,
- ErrorCode
-} from 'react-native-plugpag-nitro';
+import { ErrorCode, doPayment, PaymentType } from 'react-native-plugpag-nitro';
try {
- const result = await doPayment(PaymentPresets.creditCard(2500));
+ const result = await doPayment({ amount: 2500, type: PaymentType.CREDIT });
- if (!isTransactionSuccessful(result)) {
- const errorMessage = getTransactionError(result);
-
+ if (result.result !== ErrorCode.OK) {
switch (result.result) {
case ErrorCode.OPERATION_ABORTED:
Alert.alert('Cancelled', 'Payment was cancelled by user');
@@ -659,7 +358,7 @@ try {
Alert.alert('Connection Error', 'Check terminal connection');
break;
default:
- Alert.alert('Payment Failed', errorMessage || 'Unknown error');
+ Alert.alert('Payment Failed', result.message || 'Unknown error');
}
return;
}
diff --git a/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagEventEmitter.kt b/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagEventEmitter.kt
index f4d40d6..d7cb6bc 100644
--- a/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagEventEmitter.kt
+++ b/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagEventEmitter.kt
@@ -5,6 +5,11 @@ import com.facebook.react.modules.core.DeviceEventManagerModule
class PlugpagEventEmitter(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
+ init {
+ // Save instance for emitting events
+ setInstance(this)
+ }
+
override fun getName(): String {
return "PlugpagEventEmitter"
}
@@ -18,17 +23,18 @@ class PlugpagEventEmitter(private val reactContext: ReactApplicationContext) : R
}
@JvmStatic
- fun emitPaymentEvent(code: Double, message: String) {
+ fun emitPaymentEvent(code: Double, message: String, customMessage: String? = null) {
+ android.util.Log.d("PlugpagEventEmitter", "Emitting event - code: $code, message: $message")
instance?.let { emitter ->
val params = Arguments.createMap().apply {
putDouble("code", code)
putString("message", message)
+ putString("customMessage", customMessage ?: "")
}
-
emitter.reactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("paymentEvent", params)
- }
+ } ?: android.util.Log.e("PlugpagEventEmitter", "Instance is null - cannot emit event")
}
}
}
diff --git a/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagNitro.kt b/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagNitro.kt
index 290f92e..ac54334 100644
--- a/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagNitro.kt
+++ b/android/src/main/java/com/margelo/nitro/plugpagnitro/PlugpagNitro.kt
@@ -105,84 +105,8 @@ class PlugpagNitro : HybridPlugpagNitroSpec() {
}
}
- override fun doPayment(
- amount: Double,
- type: PaymentType,
- installmentType: InstallmentType,
- installments: Double,
- printReceipt: Boolean,
- userReference: String
- ): Promise {
- return Promise.async {
- withContext(Dispatchers.IO) {
- try {
- initializePlugPag()
-
- // Convert enum to PlugPag SDK constants
- val paymentType = when (type) {
- PaymentType.CREDIT -> PlugPag.TYPE_CREDITO
- PaymentType.DEBIT -> PlugPag.TYPE_DEBITO
- PaymentType.VOUCHER -> PlugPag.TYPE_VOUCHER
- PaymentType.PIX -> PlugPag.TYPE_PIX
- }
-
- val installmentTypeInt = when (installmentType) {
- InstallmentType.NO_INSTALLMENT -> PlugPag.INSTALLMENT_TYPE_A_VISTA
- InstallmentType.SELLER_INSTALLMENT -> PlugPag.INSTALLMENT_TYPE_PARC_VENDEDOR
- InstallmentType.BUYER_INSTALLMENT -> PlugPag.INSTALLMENT_TYPE_PARC_COMPRADOR
- }
-
- val plugPagPaymentData = PlugPagPaymentData(
- paymentType,
- amount.toInt(),
- installmentTypeInt,
- installments.toInt(),
- userReference,
- printReceipt
- )
-
- val result = plugPag.doPayment(plugPagPaymentData)
-
- val errorCode = when (result.result) {
- PlugPag.RET_OK -> ErrorCode.OK
- PlugPag.OPERATION_ABORTED -> ErrorCode.OPERATION_ABORTED
- PlugPag.AUTHENTICATION_FAILED -> ErrorCode.AUTHENTICATION_FAILED
- PlugPag.COMMUNICATION_ERROR -> ErrorCode.COMMUNICATION_ERROR
- PlugPag.NO_PRINTER_DEVICE -> ErrorCode.NO_PRINTER_DEVICE
- PlugPag.NO_TRANSACTION_DATA -> ErrorCode.NO_TRANSACTION_DATA
- else -> ErrorCode.COMMUNICATION_ERROR
- }
-
- PlugpagTransactionResult(
- result = errorCode,
- errorCode = result.errorCode ?: "",
- message = result.message ?: "",
- transactionCode = result.transactionCode ?: "",
- transactionId = result.transactionId ?: "",
- hostNsu = result.hostNsu ?: "",
- date = result.date ?: "",
- time = result.time ?: "",
- cardBrand = result.cardBrand ?: "",
- bin = result.bin ?: "",
- holder = result.holder ?: "",
- userReference = result.userReference ?: "",
- terminalSerialNumber = result.terminalSerialNumber ?: "",
- amount = result.amount ?: "",
- availableBalance = result.availableBalance ?: "",
- cardApplication = result.cardApplication ?: "",
- label = result.label ?: "",
- holderName = result.holderName ?: "",
- extendedHolderName = result.extendedHolderName ?: ""
- )
- } catch (e: Exception) {
- Log.e(TAG, "Error processing payment", e)
- throw Exception("PAYMENT_ERROR: ${e.message ?: "Unknown error"}")
- }
- }
- }
- }
- override fun doPaymentWithEvents(
+ override fun doPayment(
amount: Double,
type: PaymentType,
installmentType: InstallmentType,
diff --git a/example/src/App.tsx b/example/src/App.tsx
index 389ad94..6723782 100644
--- a/example/src/App.tsx
+++ b/example/src/App.tsx
@@ -2,785 +2,417 @@ import React, { useEffect, useState } from 'react';
import {
ActivityIndicator,
Alert,
- Modal,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
-import PlugpagNitro, {
+import {
type PlugpagTransactionResult,
- InstallmentType,
+ initializeAndActivatePinPad,
+ doPayment,
+ refundPayment,
+ useTransactionEvent,
+ getTerminalSerialNumber,
PaymentType,
- PaymentEventCode,
- useTransactionPaymentEvent,
- usePaymentFlow,
+ ErrorCode,
+ InstallmentType,
} from 'react-native-plugpag-nitro';
export default function App() {
const [isProcessing, setIsProcessing] = useState(false);
+
const [terminalSerial, setTerminalSerial] = useState('N/A');
+
const [lastPayment, setLastPayment] =
useState(null);
- const [showEventModal, setShowEventModal] = useState(false);
-
- // Enhanced payment hooks
- const paymentEvent = useTransactionPaymentEvent();
- const paymentFlow = usePaymentFlow();
- const formatCurrency = (amountInCents: number): string => {
- return new Intl.NumberFormat('pt-BR', {
- style: 'currency',
- currency: 'BRL',
- }).format(amountInCents / 100);
- };
+ const [isInitialized, setIsInitialized] = useState(false);
- const isTransactionSuccessful = (
- transaction: PlugpagTransactionResult
- ): boolean => {
- return PlugpagNitro.isTransactionSuccessful(transaction);
- };
+ // Real-time payment events
+ const paymentEvent = useTransactionEvent();
- const getEventStatusColor = (eventCode: number): string => {
- if (
- eventCode >= PaymentEventCode.CARD_INSERTED &&
- eventCode <= PaymentEventCode.WAITING_CARD
- ) {
- return '#007AFF'; // Blue for card reading
- }
- if (
- eventCode >= PaymentEventCode.DIGIT_PASSWORD &&
- eventCode <= PaymentEventCode.LAST_PASSWORD_TRY
- ) {
- return '#FF9500'; // Orange for password
- }
- if (
- eventCode >= PaymentEventCode.PROCESSING_TRANSACTION &&
- eventCode <= PaymentEventCode.WAITING_HOST_RESPONSE
- ) {
- return '#FFCC02'; // Yellow for processing
- }
- if (
- eventCode >= PaymentEventCode.REMOVE_CARD &&
- eventCode <= PaymentEventCode.TRANSACTION_DENIED
- ) {
- return '#32D74B'; // Green for terminal responses
- }
- if (
- eventCode >= PaymentEventCode.COMMUNICATION_ERROR &&
- eventCode <= PaymentEventCode.INSUFFICIENT_FUNDS
- ) {
- return '#FF3B30'; // Red for errors
- }
- return '#8E8E93'; // Gray for unknown
- };
-
- // Fetch terminal serial on mount
+ // Get terminal serial on mount
useEffect(() => {
- const getSerial = async () => {
- try {
- const serial = PlugpagNitro.getTerminalSerialNumber();
- setTerminalSerial(serial);
- } catch (error) {
- console.log('Error fetching serial:', error);
- }
- };
- getSerial();
+ try {
+ setTerminalSerial(getTerminalSerialNumber());
+ } catch (e) {
+ console.warn(e);
+ }
}, []);
- const handleInitializeAndActivatePinPad = async () => {
+ // Initialize terminal
+ const handleInitialize = async () => {
setIsProcessing(true);
try {
- await PlugpagNitro.initializeAndActivatePinPad('403938');
- Alert.alert('✅ Sucesso', 'PinPad inicializado e ativado com sucesso!');
- } catch (error: any) {
- Alert.alert('❌ Erro', `Falha na inicialização: ${error.message}`);
+ const result = await initializeAndActivatePinPad('403938');
+ if (result.result === ErrorCode.OK) {
+ setIsInitialized(true);
+ Alert.alert('✅ Sucesso', 'Terminal inicializado com sucesso');
+ } else {
+ Alert.alert('❌ Erro', result.errorMessage || 'Falha ao inicializar');
+ }
+ } catch (e: any) {
+ Alert.alert('❌ Error', e.message);
}
setIsProcessing(false);
};
+ // Credit payment
const handleCreditPayment = async () => {
+ if (!isInitialized) {
+ Alert.alert('⚠️ Aviso', 'Por favor, inicialize o terminal primeiro');
+ return;
+ }
+
setIsProcessing(true);
try {
- const result = await PlugpagNitro.doPayment(
- PlugpagNitro.PaymentPresets.creditCard(2500)
- );
+ const result = await doPayment({
+ amount: 2500, // R$ 25.00
+ type: PaymentType.CREDIT,
+ });
setLastPayment(result);
- if (isTransactionSuccessful(result)) {
+ if (result.result === ErrorCode.OK) {
Alert.alert(
'✅ Pagamento Aprovado',
- `Transação realizada com sucesso!\n\nValor: ${formatCurrency(2500)}\nCódigo: ${result.transactionCode}\nNSU: ${result.hostNsu}`
+ `Transação realizada com sucesso!\nCódigo: ${result.transactionCode}\nValor: R$ 25,00`
);
} else {
Alert.alert(
'❌ Pagamento Negado',
- `Transação negada.\n\nCódigo: ${result.transactionCode}\nMensagem: ${result.message}`
+ result.message || 'Transação falhou'
);
}
- } catch (error: any) {
- Alert.alert('❌ Erro', `Falha no pagamento: ${error.message}`);
+ } catch (e: any) {
+ Alert.alert('❌ Erro', e.message);
}
setIsProcessing(false);
};
+ // Debit payment
const handleDebitPayment = async () => {
+ if (!isInitialized) {
+ Alert.alert('⚠️ Aviso', 'Por favor, inicialize o terminal primeiro');
+ return;
+ }
+
setIsProcessing(true);
try {
- const result = await PlugpagNitro.doPayment(
- PlugpagNitro.PaymentPresets.debitCard(2500)
- );
+ const result = await doPayment({
+ amount: 1500, // R$ 15.00
+ type: PaymentType.DEBIT,
+ });
setLastPayment(result);
- if (isTransactionSuccessful(result)) {
+ if (result.result === ErrorCode.OK) {
Alert.alert(
'✅ Pagamento Aprovado',
- `Transação realizada com sucesso!\n\nValor: ${formatCurrency(2500)}\nCódigo: ${result.transactionCode}\nNSU: ${result.hostNsu}`
+ `Transação de débito realizada com sucesso!\nCódigo: ${result.transactionCode}\nValor: R$ 15,00`
);
} else {
Alert.alert(
'❌ Pagamento Negado',
- `Transação negada.\n\nCódigo: ${result.transactionCode}\nMensagem: ${result.message}`
+ result.message || 'Transação falhou'
);
}
- } catch (error: any) {
- Alert.alert('❌ Erro', `Falha no pagamento: ${error.message}`);
+ } catch (e: any) {
+ Alert.alert('❌ Erro', e.message);
}
setIsProcessing(false);
};
- const handlePixPayment = async () => {
+ // Credit payment
+ const handlePIXPayment = async () => {
+ if (!isInitialized) {
+ Alert.alert('⚠️ Aviso', 'Por favor, inicialize o terminal primeiro');
+ return;
+ }
+
setIsProcessing(true);
try {
- const result = await PlugpagNitro.doPayment(
- PlugpagNitro.PaymentPresets.pix(2500)
- );
+ const result = await doPayment({
+ amount: 1500, // R$ 15.00
+ type: PaymentType.PIX,
+ });
setLastPayment(result);
- if (isTransactionSuccessful(result)) {
+ if (result.result === ErrorCode.OK) {
Alert.alert(
'✅ Pagamento Aprovado',
- `Transação PIX realizada com sucesso!\n\nValor: ${formatCurrency(2500)}\nCódigo: ${result.transactionCode}\nNSU: ${result.hostNsu}`
+ `Transação realizada com sucesso!\nCódigo: ${result.transactionCode}\nValor: R$ 25,00`
);
} else {
Alert.alert(
'❌ Pagamento Negado',
- `Transação PIX negada.\n\nCódigo: ${result.transactionCode}\nMensagem: ${result.message}`
+ result.message || 'Transação falhou'
);
}
- } catch (error: any) {
- Alert.alert('❌ Erro', `Falha no pagamento PIX: ${error.message}`);
+ } catch (e: any) {
+ Alert.alert('❌ Erro', e.message);
}
setIsProcessing(false);
};
- const handleCustomPayment = async () => {
+ // Installment payment
+ const handleInstallmentPayment = async () => {
+ if (!isInitialized) {
+ Alert.alert('⚠️ Aviso', 'Por favor, inicialize o terminal primeiro');
+ return;
+ }
+
setIsProcessing(true);
try {
- const result = await PlugpagNitro.doPayment({
- amount: 5000,
+ const result = await doPayment({
+ amount: 10000, // R$ 100.00
type: PaymentType.CREDIT,
installmentType: InstallmentType.BUYER_INSTALLMENT,
installments: 3,
});
setLastPayment(result);
- if (isTransactionSuccessful(result)) {
+ if (result.result === ErrorCode.OK) {
Alert.alert(
'✅ Pagamento Aprovado',
- `Transação parcelada realizada com sucesso!\n\nValor: ${formatCurrency(5000)}\nParcelas: 3x\nCódigo: ${result.transactionCode}\nNSU: ${result.hostNsu}`
+ `Pagamento parcelado realizado com sucesso!\nCódigo: ${result.transactionCode}\nValor: R$ 100,00 (3x)`
);
} else {
Alert.alert(
'❌ Pagamento Negado',
- `Transação parcelada negada.\n\nCódigo: ${result.transactionCode}\nMensagem: ${result.message}`
+ result.message || 'Transação falhou'
);
}
- } catch (error: any) {
- Alert.alert('❌ Erro', `Falha no pagamento: ${error.message}`);
+ } catch (e: any) {
+ Alert.alert('❌ Erro', e.message);
}
setIsProcessing(false);
};
- const handleCreditPaymentWithEvents = async () => {
- try {
- setShowEventModal(true);
- const result = await paymentFlow.executePayment({
- amount: 2500,
- type: PaymentType.CREDIT,
- });
-
- setShowEventModal(false);
-
- if (result && isTransactionSuccessful(result)) {
- Alert.alert(
- '✅ Pagamento Aprovado',
- `Transação com eventos realizada com sucesso!\n\nValor: ${formatCurrency(2500)}\nCódigo: ${result.transactionCode}\nNSU: ${result.hostNsu}`
- );
- } else {
- Alert.alert(
- '❌ Pagamento Negado',
- `Transação com eventos negada.\n\nCódigo: ${result?.transactionCode}\nMensagem: ${result?.message}`
- );
- }
- } catch (error: any) {
- setShowEventModal(false);
- Alert.alert(
- '❌ Erro',
- `Falha no pagamento com eventos: ${error.message}`
- );
+ // Refund last payment
+ const handleRefund = async () => {
+ if (!lastPayment?.transactionCode || !lastPayment.transactionId) {
+ Alert.alert('⚠️ Aviso', 'Nenhuma transação para estornar');
+ return;
}
- };
- const handleHighValuePayment = async () => {
+ setIsProcessing(true);
try {
- setShowEventModal(true);
- const result = await paymentFlow.executePayment({
- amount: 50000, // R$ 500
- type: PaymentType.CREDIT,
+ const result = await refundPayment({
+ transactionCode: lastPayment.transactionCode,
+ transactionId: lastPayment.transactionId,
});
- setShowEventModal(false);
-
- if (result && isTransactionSuccessful(result)) {
+ if (result.result === ErrorCode.OK) {
Alert.alert(
- '💎 Alto Valor Aprovado',
- `Transação de alto valor realizada com sucesso!\n\nValor: ${formatCurrency(50000)}\nCódigo: ${result.transactionCode}\nNSU: ${result.hostNsu}`
+ '✅ Estorno Realizado',
+ `Código: ${result.transactionCode}`
);
+ setLastPayment(null);
} else {
- Alert.alert(
- '❌ Alto Valor Negado',
- `Transação de alto valor negada.\n\nCódigo: ${result?.transactionCode}\nMensagem: ${result?.message}`
- );
+ Alert.alert('❌ Estorno Falhou', result.message || 'Estorno falhou');
}
- } catch (error: any) {
- setShowEventModal(false);
- Alert.alert(
- '❌ Erro',
- `Falha no pagamento de alto valor: ${error.message}`
- );
+ } catch (e: any) {
+ Alert.alert('❌ Erro', e.message);
}
+ setIsProcessing(false);
};
- const handleRefundLastTransaction = async () => {
- if (!lastPayment?.transactionId || !lastPayment?.transactionCode) {
- Alert.alert('⚠️ Aviso', 'Nenhuma transação encontrada para estorno.');
- return;
- }
-
- Alert.alert(
- '🔄 Confirmar Estorno',
- `Deseja estornar a transação?\n\nValor: ${lastPayment.amount}\nID: ${lastPayment.transactionId}`,
- [
- { text: 'Cancelar', style: 'cancel' },
- {
- text: 'Estornar',
- style: 'destructive',
- onPress: async () => {
- setIsProcessing(true);
- try {
- const result = await PlugpagNitro.refundPayment({
- transactionCode: lastPayment.transactionCode!,
- transactionId: lastPayment.transactionId!,
- });
- if (isTransactionSuccessful(result)) {
- Alert.alert(
- '✅ Estorno Aprovado',
- `Estorno realizado com sucesso!\n\nValor: ${lastPayment.amount}\nCódigo: ${result.transactionCode}`
- );
- setLastPayment(null); // Clear last payment after successful refund
- } else {
- Alert.alert(
- '❌ Estorno Negado',
- `Estorno negado.\n\nCódigo: ${result.transactionCode}\nMensagem: ${result.message}`
- );
- }
- } catch (error: any) {
- Alert.alert('❌ Erro', `Falha no estorno: ${error.message}`);
- }
- setIsProcessing(false);
- },
- },
- ]
- );
+ const getEventColor = (code: number) => {
+ if (code >= 1001 && code <= 1004) return '#007AFF'; // Card events - Blue
+ if (code >= 1010 && code <= 1012) return '#FF9500'; // Password events - Orange
+ if (code >= 1020 && code <= 1023) return '#FFCC02'; // Processing - Yellow
+ if (code >= 1030 && code <= 1032) return '#34C759'; // Terminal response - Green
+ if (code >= 1040 && code <= 1043) return '#FF3B30'; // Errors - Red
+ return '#8E8E93'; // Default - Gray
};
return (
-
+
-
- React Native PlugPag Nitro
-
-
- Enhanced Payment Events Demo
-
-
- Terminal Serial: {terminalSerial}
+ Demo PlugPag Nitro
+ Terminal: {terminalSerial}
+
+ Status: {isInitialized ? '✅ Pronto' : '❌ Não Inicializado'}
-
-
- {isProcessing ? 'Inicializando...' : 'Inicializar e ativar o Pin Pad'}
-
-
-
-
- 💳 Pagamentos Básicos
-
- 0 && (
+
-
- {isProcessing
- ? 'Processando...'
- : `💳 Crédito à vista - ${formatCurrency(2500)}`}
-
-
+ {paymentEvent.message}
+ Code: {paymentEvent.code}
+ {paymentEvent.customMessage && (
+ {paymentEvent.customMessage}
+ )}
+
+ )}
-
-
- 💰 Débito - {formatCurrency(2500)}
-
-
+ {/* Processing Indicator */}
+ {isProcessing && (
+
+
+ Processando...
+
+ )}
-
-
- 📱 PIX - {formatCurrency(2500)}
-
-
-
+
+ Inicializar Terminal
+
-
-
- ⚡ Pagamentos com Eventos em Tempo Real
-
+
+ Pagamento Crédito - R$ 25,00
+
-
-
- {paymentFlow.isProcessing
- ? 'Processando com eventos...'
- : `⚡ Crédito com eventos - ${formatCurrency(2500)}`}
-
-
+
+ Pagamento Débito - R$ 15,00
+
-
-
- {paymentFlow.isProcessing
- ? 'Processando...'
- : `💎 Alto Valor com eventos - ${formatCurrency(50000)}`}
-
-
-
- {/* Real-time event display */}
- {paymentFlow.isProcessing && (
-
-
- {paymentEvent.message}
-
- )}
-
+
+ PIX - R$ 15,00
+
-
-
- 🔧 Pagamento Customizado com Enums
+
+
+ Pagamento Parcelado - R$ 100,00 (3x)
+
-
-
- ⚡ Crédito 3x - {formatCurrency(5000)}
-
-
-
-
- 🔧 Configuração:
- • PaymentType.CREDIT
-
- • InstallmentType.BUYER_INSTALLMENT
-
- • 3 parcelas
-
-
-
-
- 🔄 Ações
+
+ Estornar Última Transação
+
-
-
- 🔄 Estornar última transação
+ {lastPayment && (
+
+ Última Transação
+ Código: {lastPayment.transactionCode}
+ ID: {lastPayment.transactionId}
+
+ Status:{' '}
+ {lastPayment.result === ErrorCode.OK ? '✅ Aprovado' : '❌ Negado'}
-
-
-
- {(lastPayment || paymentFlow.currentTransaction) && (
-
- 📋 Última Transação
-
- {(() => {
- const transaction = paymentFlow.currentTransaction || lastPayment;
- return (
- <>
-
- 💰 Valor: {transaction?.amount}
-
-
- 🔢 Código: {transaction?.transactionCode}
-
-
- 🆔 ID: {transaction?.transactionId}
-
-
- 🏦 Bandeira: {transaction?.cardBrand}
-
-
- 📄 NSU: {transaction?.hostNsu}
-
-
- ✅ Status:{' '}
- {isTransactionSuccessful(transaction!)
- ? 'Aprovado'
- : 'Negado'}
-
-
- 📅 Data/Hora: {transaction?.date} {transaction?.time}
-
- {paymentFlow.isTransactionSuccessful && (
-
- 🎉 Transação processada com eventos em tempo real!
-
- )}
- >
- );
- })()}
-
+ {lastPayment.hostNsu && NSU: {lastPayment.hostNsu}}
+ {lastPayment.cardBrand && (
+ Bandeira: {lastPayment.cardBrand}
+ )}
)}
-
- {/* Event Modal */}
-
-
-
-
- Processando Pagamento
-
-
-
-
-
-
-
- {paymentEvent.message}
-
-
-
- Código do evento: {paymentEvent.code}
-
-
-
- setShowEventModal(false)}
- >
- Fechar
-
-
-
-
);
}
const styles = StyleSheet.create({
container: {
- padding: 24,
- backgroundColor: 'white',
+ padding: 20,
+ backgroundColor: '#f5f5f5',
},
header: {
- width: '100%',
alignItems: 'center',
- justifyContent: 'center',
marginBottom: 20,
},
- titleHeader: {
- fontSize: 20,
+ title: {
+ fontSize: 24,
fontWeight: 'bold',
- textAlign: 'center',
- color: '#1a1a1a',
+ color: '#333',
+ marginBottom: 5,
},
subtitle: {
fontSize: 16,
- fontWeight: '600',
- textAlign: 'center',
- color: '#007AFF',
- },
- serialText: {
- fontSize: 14,
color: '#666',
- textAlign: 'center',
+ marginBottom: 5,
},
- paymentSection: {
- marginBottom: 20,
- },
- eventsSection: {
- marginBottom: 20,
- padding: 16,
- backgroundColor: '#e8f5e8',
- borderRadius: 12,
- borderWidth: 1,
- borderColor: '#28a745',
- },
- customSection: {
- marginBottom: 20,
- },
- actionSection: {
- marginBottom: 20,
- },
- lastPaymentSection: {
- marginBottom: 20,
- padding: 16,
- backgroundColor: '#f8f9fa',
- borderRadius: 12,
- borderWidth: 1,
- borderColor: '#e1e5e9',
- },
- sectionTitle: {
- fontSize: 18,
- fontWeight: 'bold',
- marginBottom: 12,
- color: '#333',
- },
- button: {
- width: '100%',
- alignItems: 'center',
- justifyContent: 'center',
- padding: 16,
- borderRadius: 12,
- borderWidth: 2,
- borderColor: '#007AFF',
- backgroundColor: 'white',
- },
- debitButton: {
- borderColor: '#FF9500',
- },
- pixButton: {
- borderColor: '#32D74B',
- },
- customButton: {
- borderColor: '#AF52DE',
- },
- refundButton: {
- borderColor: '#FF3B30',
- },
- eventsButton: {
- borderColor: '#28a745',
- },
- highValueButton: {
- borderColor: '#dc3545',
- backgroundColor: '#fff5f5',
- },
- textButton: {
- fontSize: 16,
- fontWeight: '600',
- textAlign: 'center',
- color: '#007AFF',
- },
- debitText: {
- color: '#FF9500',
- },
- pixText: {
- color: '#32D74B',
- },
- customText: {
- color: '#AF52DE',
- },
- refundText: {
- color: '#FF3B30',
- },
- eventsText: {
- color: '#28a745',
- },
- highValueText: {
- color: '#dc3545',
- fontWeight: 'bold',
- },
- successText: {
- color: '#28a745',
- fontWeight: 'bold',
- },
- space: {
- marginBottom: 12,
- },
- paymentInfo: {
- padding: 12,
- backgroundColor: 'white',
- borderRadius: 8,
- borderWidth: 1,
- borderColor: '#e1e5e9',
- },
- paymentInfoText: {
+ status: {
fontSize: 14,
- marginBottom: 6,
- color: '#444',
- lineHeight: 20,
- },
- disabledButton: {
- opacity: 0.3,
+ fontWeight: '600',
},
- enumInfo: {
- backgroundColor: '#f0f0f5',
- padding: 12,
+ eventContainer: {
+ padding: 15,
borderRadius: 8,
- marginTop: 8,
+ marginBottom: 15,
},
- enumTitle: {
- fontSize: 14,
+ eventText: {
+ color: 'white',
fontWeight: 'bold',
- color: '#333',
- marginBottom: 8,
- },
- enumText: {
- fontSize: 13,
- color: '#666',
- fontFamily: 'Courier New, monospace',
- marginBottom: 4,
- },
- eventStatusContainer: {
- flexDirection: 'row',
- alignItems: 'center',
- padding: 12,
- backgroundColor: 'white',
- borderRadius: 8,
- marginTop: 8,
+ fontSize: 16,
},
- eventStatusIndicator: {
- width: 12,
- height: 12,
- borderRadius: 6,
- marginRight: 8,
+ eventCode: {
+ color: 'white',
+ fontSize: 12,
+ marginTop: 5,
},
- eventStatusText: {
- flex: 1,
+ eventCustom: {
+ color: 'white',
fontSize: 14,
- fontWeight: '500',
- color: '#333',
+ marginTop: 5,
+ fontStyle: 'italic',
},
- // Modal styles
- modalOverlay: {
- flex: 1,
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
- justifyContent: 'center',
+ processingContainer: {
alignItems: 'center',
- },
- modalContainer: {
- backgroundColor: 'white',
- borderRadius: 12,
padding: 20,
- margin: 20,
- minWidth: 300,
- maxWidth: 400,
- },
- modalHeader: {
- marginBottom: 16,
- },
- modalTitle: {
- fontSize: 18,
- fontWeight: 'bold',
- textAlign: 'center',
- color: '#333',
- },
- modalContent: {
- alignItems: 'center',
- marginBottom: 20,
- },
- eventDisplay: {
- flexDirection: 'row',
- alignItems: 'center',
- marginTop: 16,
- padding: 12,
- backgroundColor: '#f8f9fa',
- borderRadius: 8,
- width: '100%',
- },
- eventIndicator: {
- width: 16,
- height: 16,
+ backgroundColor: 'white',
borderRadius: 8,
- marginRight: 12,
- },
- eventMessage: {
- flex: 1,
- fontSize: 14,
- fontWeight: '500',
- color: '#333',
+ marginBottom: 15,
},
- eventCode: {
- fontSize: 12,
+ processingText: {
+ marginTop: 10,
+ fontSize: 16,
color: '#666',
- marginTop: 8,
- textAlign: 'center',
},
- modalCloseButton: {
+ button: {
backgroundColor: '#007AFF',
- padding: 12,
+ padding: 15,
borderRadius: 8,
+ marginBottom: 10,
alignItems: 'center',
},
- modalCloseText: {
+ primaryButton: {
+ backgroundColor: '#34C759',
+ },
+ refundButton: {
+ backgroundColor: '#FF9500',
+ },
+ buttonText: {
color: 'white',
fontSize: 16,
fontWeight: '600',
},
+ transactionInfo: {
+ backgroundColor: 'white',
+ padding: 15,
+ borderRadius: 8,
+ marginTop: 10,
+ },
+ transactionTitle: {
+ fontSize: 16,
+ fontWeight: 'bold',
+ marginBottom: 5,
+ },
});
diff --git a/react-native.config.js b/react-native.config.js
deleted file mode 100644
index e5db07a..0000000
--- a/react-native.config.js
+++ /dev/null
@@ -1,13 +0,0 @@
-module.exports = {
- dependencies: {
- 'react-native-plugpag-nitro': {
- platforms: {
- android: {
- packageImportPath:
- 'com.margelo.nitro.plugpagnitro.PlugpagNitroPackage',
- packageInstance: 'new PlugpagNitroPackage()',
- },
- },
- },
- },
-};
diff --git a/src/PlugpagNitro.nitro.ts b/src/PlugpagNitro.nitro.ts
index 21fea46..f8810cb 100644
--- a/src/PlugpagNitro.nitro.ts
+++ b/src/PlugpagNitro.nitro.ts
@@ -183,25 +183,6 @@ export interface PlugpagNitro extends HybridObject<{ android: 'kotlin' }> {
userReference: string
): Promise;
- /**
- * Process a payment transaction with real-time events
- * This method emits payment events during the transaction flow
- * @param amount Payment amount in cents
- * @param type Payment type (PaymentType.CREDIT, PaymentType.DEBIT, etc.)
- * @param installmentType Installment type (InstallmentType.NO_INSTALLMENT, etc.)
- * @param installments Number of installments
- * @param printReceipt Whether to print receipt
- * @param userReference Optional user reference
- */
- doPaymentWithEvents(
- amount: number,
- type: PaymentType,
- installmentType: InstallmentType,
- installments: number,
- printReceipt: boolean,
- userReference: string
- ): Promise;
-
/**
* Refund a previous payment transaction
* @param transactionCode Transaction code to refund
diff --git a/src/index.tsx b/src/index.tsx
index d217173..4633fcb 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -113,6 +113,7 @@ export async function doPayment(options: {
};
return safeModuleCall('doPayment', () =>
+ // Use native doPayment (with built-in events)
PlugpagNitroModule.doPayment(
paymentOptions.amount,
paymentOptions.type,
@@ -124,39 +125,6 @@ export async function doPayment(options: {
);
}
-/**
- * Process a payment transaction with real-time event updates
- * This method emits payment events during the transaction flow to provide
- * real-time feedback about card insertion, password entry, processing status, etc.
- */
-export async function doPaymentWithEvents(options: {
- amount: number;
- type: PaymentType;
- installmentType?: InstallmentType;
- installments?: number;
- printReceipt?: boolean;
- userReference?: string;
-}): Promise {
- const paymentOptions = {
- installmentType: options.installmentType ?? InstallmentType.NO_INSTALLMENT,
- installments: options.installments ?? 1,
- printReceipt: options.printReceipt ?? true,
- userReference: options.userReference ?? `payment-events-${Date.now()}`,
- ...options,
- };
-
- return safeModuleCall('doPaymentWithEvents', () =>
- PlugpagNitroModule.doPaymentWithEvents(
- paymentOptions.amount,
- paymentOptions.type,
- paymentOptions.installmentType,
- paymentOptions.installments,
- paymentOptions.printReceipt,
- paymentOptions.userReference
- )
- );
-}
-
/**
* Hook for listening to transaction payment events
* Provides real-time updates during payment flow including:
@@ -166,7 +134,9 @@ export async function doPaymentWithEvents(options: {
* - Error notifications
* - Transaction completion status
*/
-export function useTransactionPaymentEvent(): PaymentEvent {
+export function useTransactionEvent(): PaymentEvent & {
+ resetEvent: () => void;
+} {
const [paymentEvent, setPaymentEvent] = useState({
code: PaymentEventCode.WAITING_CARD,
message: 'Aguardando cartão...',
@@ -194,68 +164,13 @@ export function useTransactionPaymentEvent(): PaymentEvent {
return {
...paymentEvent,
resetEvent,
- } as PaymentEvent & { resetEvent: () => void };
+ };
}
/**
* Enhanced payment flow manager
* Combines payment execution with event monitoring
*/
-export function usePaymentFlow() {
- const [isProcessing, setIsProcessing] = useState(false);
- const [currentTransaction, setCurrentTransaction] =
- useState(null);
- const paymentEvent = useTransactionPaymentEvent();
-
- const executePayment = useCallback(
- async (options: {
- amount: number;
- type: PaymentType;
- installmentType?: InstallmentType;
- installments?: number;
- printReceipt?: boolean;
- userReference?: string;
- }) => {
- try {
- setIsProcessing(true);
- setCurrentTransaction(null);
-
- const result = await doPaymentWithEvents(options);
- setCurrentTransaction(result);
-
- return result;
- } catch (error) {
- console.error('[PaymentFlow] Error:', error);
- throw error;
- } finally {
- setIsProcessing(false);
- }
- },
- []
- );
-
- const resetFlow = useCallback(() => {
- setIsProcessing(false);
- setCurrentTransaction(null);
- if ('resetEvent' in paymentEvent) {
- (paymentEvent as any).resetEvent();
- }
- }, [paymentEvent]);
-
- return {
- isProcessing,
- currentTransaction,
- paymentEvent,
- executePayment,
- resetFlow,
- isTransactionSuccessful: currentTransaction
- ? isTransactionSuccessful(currentTransaction)
- : false,
- transactionError: currentTransaction
- ? getTransactionError(currentTransaction)
- : null,
- };
-}
/**
* Refund a previous payment transaction
@@ -301,59 +216,10 @@ export async function reprintCustomerReceipt(): Promise {
* Simple transaction status checker
* Helper function to check if a transaction result indicates success
*/
-export function isTransactionSuccessful(
- result: PlugpagTransactionResult
-): boolean {
- return result.result === ErrorCode.OK;
-}
-
/**
* Simple transaction error checker
* Helper function to get a human-readable error message
*/
-export function getTransactionError(
- result: PlugpagTransactionResult
-): string | null {
- if (isTransactionSuccessful(result)) {
- return null;
- }
-
- return result.message || result.errorCode || 'Unknown transaction error';
-}
-
-// Export presets for common payment scenarios
-export const PaymentPresets = {
- creditCard: (amount: number, installments: number = 1) => ({
- amount,
- type: PaymentType.CREDIT,
- installmentType:
- installments > 1
- ? InstallmentType.BUYER_INSTALLMENT
- : InstallmentType.NO_INSTALLMENT,
- installments,
- }),
-
- debitCard: (amount: number) => ({
- amount,
- type: PaymentType.DEBIT,
- installmentType: InstallmentType.NO_INSTALLMENT,
- installments: 1,
- }),
-
- pix: (amount: number) => ({
- amount,
- type: PaymentType.PIX,
- installmentType: InstallmentType.NO_INSTALLMENT,
- installments: 1,
- }),
-
- voucher: (amount: number) => ({
- amount,
- type: PaymentType.VOUCHER,
- installmentType: InstallmentType.NO_INSTALLMENT,
- installments: 1,
- }),
-} as const;
// Default export
export default {
@@ -362,26 +228,17 @@ export default {
getTerminalSerialNumber,
initializeAndActivatePinPad,
doPayment,
- doPaymentWithEvents,
refundPayment,
doAbort,
print,
reprintCustomerReceipt,
- // Enhanced payment flow
- useTransactionPaymentEvent,
- usePaymentFlow,
-
- // Helper functions
- isTransactionSuccessful,
- getTransactionError,
+ // Enhanced payment event listener
+ useTransactionEvent,
- // Enums (recommended)
+ // Enums
PaymentType,
InstallmentType,
ErrorCode,
PaymentEventCode,
-
- // Presets
- PaymentPresets,
};