UNPKG

expo-mercadopago-integration

Version:

Expo library for integrating Mercado Pago native SDK without ejecting

317 lines (310 loc) 12.2 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = App; const react_1 = __importStar(require("react")); const react_native_1 = require("react-native"); const ExpoMercadoPagoModule_1 = require("../src/ExpoMercadoPagoModule"); const config = { publicKey: 'TEST-12345678-1234-1234-1234-123456789012', // Reemplaza con tu public key real siteId: 'MLA', // Argentina language: 'es', }; const mercadopago = (0, ExpoMercadoPagoModule_1.createMercadoPagoSDK)(config); function App() { const [isInitialized, setIsInitialized] = (0, react_1.useState)(false); const [isMercadoPagoInstalled, setIsMercadoPagoInstalled] = (0, react_1.useState)(false); const [sdkVersion, setSdkVersion] = (0, react_1.useState)(''); const [lastPaymentResult, setLastPaymentResult] = (0, react_1.useState)(null); const [isLoading, setIsLoading] = (0, react_1.useState)(false); (0, react_1.useEffect)(() => { initializeSDK(); checkMercadoPagoInstallation(); getSDKVersion(); }, []); const initializeSDK = async () => { try { setIsLoading(true); await mercadopago.initialize(); setIsInitialized(true); console.log('MercadoPago SDK initialized successfully'); } catch (error) { console.error('Failed to initialize MercadoPago SDK:', error); react_native_1.Alert.alert('Error', 'Failed to initialize MercadoPago SDK'); } finally { setIsLoading(false); } }; const checkMercadoPagoInstallation = async () => { try { const installed = await mercadopago.isMercadoPagoInstalled(); setIsMercadoPagoInstalled(installed); } catch (error) { console.error('Error checking MercadoPago installation:', error); } }; const getSDKVersion = async () => { try { const version = await mercadopago.getSDKVersion(); setSdkVersion(version); } catch (error) { console.error('Error getting SDK version:', error); } }; const startPayment = async () => { if (!isInitialized) { react_native_1.Alert.alert('Error', 'SDK not initialized'); return; } // Este preference ID debe ser generado en tu backend const preferenceId = '123456789-12345678-12345678-12345678'; try { setIsLoading(true); // Agregar listener para eventos de pago const subscription = mercadopago.addPaymentResultListener((result) => { console.log('Payment result received:', result); setLastPaymentResult(result); switch (result.status) { case 'approved': react_native_1.Alert.alert('¡Éxito!', `Pago aprobado. ID: ${result.paymentId}`); break; case 'rejected': react_native_1.Alert.alert('Error', `Pago rechazado: ${result.statusDetail}`); break; case 'pending': react_native_1.Alert.alert('Pendiente', 'El pago está pendiente de confirmación'); break; case 'in_process': react_native_1.Alert.alert('En proceso', 'El pago está siendo procesado'); break; } }); const result = await mercadopago.startPayment(preferenceId); console.log('Payment completed:', result); // Remover listener después del pago mercadopago.removePaymentResultListener(subscription); } catch (error) { console.error('Payment failed:', error); react_native_1.Alert.alert('Error', 'El pago falló. Inténtalo de nuevo.'); } finally { setIsLoading(false); } }; const startPaymentWithCustomPreference = async () => { if (!isInitialized) { react_native_1.Alert.alert('Error', 'SDK not initialized'); return; } // Ejemplo con preference ID personalizado const customPreferenceId = '987654321-87654321-87654321-87654321'; try { setIsLoading(true); const result = await mercadopago.startPayment(customPreferenceId); console.log('Custom payment completed:', result); setLastPaymentResult(result); if (result.status === 'approved') { react_native_1.Alert.alert('¡Éxito!', `Pago aprobado. ID: ${result.paymentId}`); } else { react_native_1.Alert.alert('Error', `Pago ${result.status}: ${result.statusDetail}`); } } catch (error) { console.error('Custom payment failed:', error); react_native_1.Alert.alert('Error', 'El pago falló. Inténtalo de nuevo.'); } finally { setIsLoading(false); } }; return (<react_native_1.SafeAreaView style={styles.container}> <react_native_1.ScrollView contentContainerStyle={styles.scrollContainer}> <react_native_1.Text style={styles.title}>Expo MercadoPago SDK</react_native_1.Text> <react_native_1.View style={styles.statusContainer}> <react_native_1.Text style={styles.statusText}> SDK Status: {isInitialized ? '✅ Initialized' : '❌ Not Initialized'} </react_native_1.Text> <react_native_1.Text style={styles.statusText}> MercadoPago App: {isMercadoPagoInstalled ? '✅ Installed' : '❌ Not Installed'} </react_native_1.Text> {sdkVersion && (<react_native_1.Text style={styles.statusText}>SDK Version: {sdkVersion}</react_native_1.Text>)} </react_native_1.View> <react_native_1.View style={styles.buttonContainer}> <react_native_1.TouchableOpacity style={[styles.button, styles.primaryButton]} onPress={startPayment} disabled={!isInitialized || isLoading}> <react_native_1.Text style={styles.buttonText}> {isLoading ? 'Procesando...' : 'Iniciar Pago'} </react_native_1.Text> </react_native_1.TouchableOpacity> <react_native_1.TouchableOpacity style={[styles.button, styles.secondaryButton]} onPress={startPaymentWithCustomPreference} disabled={!isInitialized || isLoading}> <react_native_1.Text style={styles.buttonText}> Pago con Preference ID Personalizado </react_native_1.Text> </react_native_1.TouchableOpacity> <react_native_1.TouchableOpacity style={[styles.button, styles.infoButton]} onPress={checkMercadoPagoInstallation} disabled={isLoading}> <react_native_1.Text style={styles.buttonText}>Verificar Instalación</react_native_1.Text> </react_native_1.TouchableOpacity> </react_native_1.View> {lastPaymentResult && (<react_native_1.View style={styles.resultContainer}> <react_native_1.Text style={styles.resultTitle}>Último Resultado:</react_native_1.Text> <react_native_1.Text style={styles.resultText}>Status: {lastPaymentResult.status}</react_native_1.Text> <react_native_1.Text style={styles.resultText}>ID: {lastPaymentResult.paymentId}</react_native_1.Text> <react_native_1.Text style={styles.resultText}>Detail: {lastPaymentResult.statusDetail}</react_native_1.Text> {lastPaymentResult.error && (<react_native_1.Text style={styles.errorText}> Error: {lastPaymentResult.error.message} </react_native_1.Text>)} </react_native_1.View>)} <react_native_1.View style={styles.infoContainer}> <react_native_1.Text style={styles.infoTitle}>Información Importante:</react_native_1.Text> <react_native_1.Text style={styles.infoText}> • Reemplaza la public key con tu clave real de MercadoPago </react_native_1.Text> <react_native_1.Text style={styles.infoText}> • Los preference IDs deben ser generados en tu backend </react_native_1.Text> <react_native_1.Text style={styles.infoText}> • Para testing, usa las credenciales de prueba de MercadoPago </react_native_1.Text> </react_native_1.View> </react_native_1.ScrollView> </react_native_1.SafeAreaView>); } const styles = react_native_1.StyleSheet.create({ container: { flex: 1, backgroundColor: '#f5f5f5', }, scrollContainer: { flexGrow: 1, padding: 20, }, title: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', marginBottom: 30, color: '#333', }, statusContainer: { backgroundColor: 'white', padding: 15, borderRadius: 10, marginBottom: 20, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, }, statusText: { fontSize: 16, marginBottom: 5, color: '#666', }, buttonContainer: { marginBottom: 20, }, button: { padding: 15, borderRadius: 10, marginBottom: 10, alignItems: 'center', }, primaryButton: { backgroundColor: '#007AFF', }, secondaryButton: { backgroundColor: '#34C759', }, infoButton: { backgroundColor: '#FF9500', }, buttonText: { color: 'white', fontSize: 16, fontWeight: '600', }, resultContainer: { backgroundColor: 'white', padding: 15, borderRadius: 10, marginBottom: 20, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, }, resultTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 10, color: '#333', }, resultText: { fontSize: 14, marginBottom: 5, color: '#666', }, errorText: { fontSize: 14, marginTop: 5, color: '#FF3B30', fontWeight: '500', }, infoContainer: { backgroundColor: '#E3F2FD', padding: 15, borderRadius: 10, borderLeftWidth: 4, borderLeftColor: '#2196F3', }, infoTitle: { fontSize: 16, fontWeight: 'bold', marginBottom: 10, color: '#1976D2', }, infoText: { fontSize: 14, marginBottom: 5, color: '#424242', }, });