UNPKG

react-native-passkit-apple-pay

Version:

A React Native library for integrating Apple Pay with Conekta payment processor using PassKit framework

321 lines (245 loc) 8.06 kB
# React Native Conekta Apple Pay A React Native library for integrating Apple Pay with Conekta payment processor using PassKit framework. ## Features - Native Apple Pay integration using PassKit - iOS support with TypeScript definitions - Customizable payment button UI - Secure token-based payment processing ## Installation ```bash npm install conekta/conekta-react-native-apple-pay ``` ### iOS Setup 1. Install iOS dependencies: ```bash cd ios && pod install ``` 2. Add Apple Pay capability to your iOS project: - Open your project in Xcode - Select your target - Go to "Signing & Capabilities" - Click "+" and add "Apple Pay" - Configure your merchant identifier (must be registered and supported by Conekta) 3. Add your merchant identifier to your entitlements file: ```xml <key>com.apple.developer.in-app-payments</key> <array> <string>merchant.your.identifier</string> </array> ``` That's it! The library will be automatically linked thanks to React Native's auto-linking feature. ## Usage ### Basic Setup with Conekta ```tsx import React from 'react'; import { View, Text } from 'react-native'; import { ApplePayProvider, ApplePayButton, completeApplePayPayment, ApplePayToken, } from 'react-native-conekta-apple-pay'; function App() { const handlePaymentToken = async (token: ApplePayToken) => { try { const result = await processPayment(token); if (result.success) { await completeApplePayPayment(true); // Handle successful payment } else { await completeApplePayPayment(false, result.errorMessage); // Handle payment failure } } catch (error) { await completeApplePayPayment(false, 'Payment processing failed'); // Handle error } }; const processPayment = async (token: ApplePayToken) => { //Calls to your backend here return { success: true, //your success logic //errorMessage: response.message || 'Payment failed', }; }; const handlePaymentError = (error: Error) => { console.log('Payment error:', error.message); }; return ( <ApplePayProvider merchantIdentifier="merchant.your.identifier" countryCode="MX" currencyCode="MXN" supportedNetworks={['visa', 'masterCard', 'amex']}> <ApplePayButton payment={{ label: 'Producto de Ejemplo', amount: '100.00', }} onPaymentToken={handlePaymentToken} onError={handlePaymentError}> <View style={styles.payButton}> <Text style={styles.payButtonText}>Pagar con Apple Pay</Text> </View> </ApplePayButton> </ApplePayProvider> ); } ``` ### Conekta Integration This library is specifically designed to work seamlessly with Conekta's Apple Pay implementation. The Apple Pay token format is compatible with Conekta's API expectations. #### Required Conekta Configuration 1. **Merchant ID**: Register your merchant identifier with Conekta 2. **API Keys**: Use your Conekta API keys for backend processing 3. **Webhook Setup**: Configure Conekta webhooks for payment confirmations #### Example processPayment methods with Conekta backend ```tsx const processConektaPayment = async (token: ApplePayToken, orderId: string) => { try { const response = await fetch(`https://api.conekta.io/orders/${orderId}/charges`, { method: 'POST', headers: { 'Accept': 'application/vnd.conekta-v2.0.0+json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${CONEKTA_PRIVATE_KEY}`, }, body: JSON.stringify({ payment_method: { type: 'apple_pay', token_id: token, }, }), }); const result = await response.json(); if (response.ok && result.status === 'paid') { return { success: true }; } else { return { success: false, errorMessage: result.errorMessage || 'Payment failed' }; } } catch (error) { return { success: false, errorMessage: 'Network error' }; } }; ``` ## API Reference ### ApplePayProvider The provider component that configures global Apple Pay settings for Conekta integration. #### Props | Prop | Type | Required | Description | |------|------|----------|-------------| | `merchantIdentifier` | `string` | ✅ | Your Conekta-registered merchant identifier | | `countryCode` | `string` | ✅ | Two-letter country code (e.g., "MX" for Mexico) | | `currencyCode` | `string` | ✅ | Three-letter currency code (e.g., "MXN" for Mexican Peso) | | `supportedNetworks` | `string[]` | ✅ | Supported payment networks | #### Supported Networks for Conekta - `visa` - `masterCard` - `amex` ### ApplePayButton A wrapper component that converts its children into an Apple Pay button optimized for Conekta. #### Props | Prop | Type | Required | Description | |------|------|----------|-------------| | `payment` | `PaymentSummary` | ✅ | Payment details | | `onPaymentToken` | `(token: ApplePayToken) => void` | ✅ | Callback when payment is authorized | | `onError` | `(error: Error) => void` | ❌ | Callback when payment fails or is cancelled | | `children` | `React.ReactNode` | ✅ | Custom button UI | #### PaymentSummary ```tsx interface PaymentSummary { label: string; // Product/service name amount: string; // Payment amount as string (e.g., "100.00") } ``` ### ApplePayToken The payment token returned when payment is authorized, formatted for Conekta API consumption. ```tsx interface ApplePayToken { paymentData: ApplePayPaymentData; paymentMethod: ApplePayPaymentMethod; transactionIdentifier: string; } ``` ### completeApplePayPayment Function to complete the Apple Pay transaction after Conekta processing. ```tsx completeApplePayPayment( success: boolean, errorMessage?: string | null ): Promise<void> ``` #### Parameters - `success`: `true` if Conekta payment succeeded, `false` otherwise - `errorMessage`: Optional error message to display on failure ## Error Handling The library handles several types of errors common in Conekta integration: - **Device Compatibility**: Apple Pay not available on device - **User Cancellation**: User cancels the payment flow - **Conekta API Errors**: Backend payment processing failures - **Network Issues**: Connection problems with Conekta API ```tsx const handlePaymentError = (error: Error) => { switch (error.message) { case 'USER_CANCELLED': // User cancelled payment break; case 'APPLE_PAY_NOT_AVAILABLE': // Apple Pay not available on device break; default: // Other errors (likely Conekta API related) break; } }; ``` ## Troubleshooting ### Auto-linking Issues If you experience issues with auto-linking, you can disable it by adding this to your `react-native.config.js`: ```js module.exports = { dependencies: { 'react-native-conekta-apple-pay': { platforms: { ios: null, // disable iOS platform auto-linking }, }, }, }; ``` Then manually add to your `ios/Podfile`: ```ruby pod 'react-native-conekta-apple-pay', :path => '../node_modules/react-native-conekta-apple-pay' ``` ### Clean Build If you encounter build issues, try cleaning your project: ```bash # Clean React Native npx react-native clean # Clean iOS cd ios rm -rf Pods Podfile.lock pod install cd .. # Clean and rebuild npx react-native run-ios ``` ## Requirements - iOS 11.0+ - React Native 0.60+ - Valid Apple Developer account with Apple Pay capability - Conekta merchant account with Apple Pay enabled - Configured merchant identifier registered with Conekta ## Conekta Resources - [Conekta API Reference](https://developers.conekta.com/api) ## License MIT ## Contributing Contributions are welcome! Please read the contributing guidelines before submitting PRs. ## Support For issues and questions: - Library issues: Use the GitHub issue tracker - Conekta-specific questions: Contact Conekta support - Apple Pay setup: Refer to Apple Developer documentation