Apple Pay Payment Initiation
Payment initiation begins when users tap the Apple Pay button, creating a payment session and displaying the Apple Pay payment sheet.
Integration Overview
Payment initiation involves:
- User taps Apple Pay button → Trigger payment session creation
- Create payment request → Define payment parameters and amounts
- Initialize ApplePaySession → Start the Apple Pay flow
- Display payment sheet → Present Apple Pay interface to user
See the complete payment flow for detailed sequence diagrams.
Payment Request Parameters
Required Parameters
Payment requests must include these essential parameters:
const paymentRequest = {
// Basic configuration (obtained from Onerway payment methods query API)
countryCode: config.countryCode, // From Onerway configuration
currencyCode: 'USD', // Payment currency
supportedNetworks: config.subCardTypes.map(card => card.toLowerCase()), // From Onerway configuration
merchantCapabilities: ['supports3DS'],
// Payment total
total: {
label: 'Your Store Name',
amount: '29.99', // String format, two decimal precision
type: 'final'
}
};
2
3
4
5
6
7
8
9
10
11
12
13
14
Getting Configuration from Onerway
To obtain the required countryCode
and supportedNetworks
configuration, use Onerway's Payment Methods Query API. This API returns the necessary Apple Pay configuration for your merchant account, ensuring correct supported card types and regional settings are displayed.
Optional Parameters
Add these for enhanced features:
// Line items (recommended for clarity)
lineItems: [
{ label: 'Product', amount: '24.99', type: 'final' },
{ label: 'Shipping', amount: '5.00', type: 'final' }
],
// Shipping information collection
requiredShippingContactFields: ['postalAddress', 'name', 'phone', 'email'],
shippingMethods: [
{
label: 'Standard Shipping',
amount: '5.00',
detail: '5-7 business days',
identifier: 'standard'
}
],
shippingType: 'shipping',
// Billing information collection
requiredBillingContactFields: ['postalAddress', 'name'],
// Recurring payments
recurringPaymentRequest: {
paymentDescription: 'Monthly Subscription Service',
regularBilling: {
label: 'Monthly Fee',
amount: '9.99',
type: 'final',
paymentTiming: 'recurring',
recurringPaymentIntervalUnit: 'month',
recurringPaymentIntervalCount: 1,
recurringPaymentStartDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() // Start after 7-day trial
},
trialBilling: {
label: '7-Day Free Trial',
amount: '0.00',
type: 'final',
paymentTiming: 'immediate' // Start immediately
},
managementURL: 'https://your-website.com/manage-subscription' // Subscription management page
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Apple Pay Parameter Documentation
For more parameter configuration details, see Apple's official documentation:
Parameter Category | Official Documentation Link |
---|---|
Basic Parameters | ApplePayPaymentRequest |
Shipping Information | Shipping Contact Fields |
Billing Information | Billing Contact Fields |
Recurring Payments | Recurring Payment Request |
Merchant Capabilities | Merchant Capabilities |
Basic Implementation
1. Get Onerway Configuration and Create Payment Session
Configuration Retrieval
Use the Payment Methods Query API to obtain the Apple Pay configuration required, including countryCode
and supportedNetworks
.
/**
* Get Onerway Apple Pay configuration
* @returns {Promise<Object>} Apple Pay configuration object
*/
async function getOnerwayConfig() {
const response = await fetch('/api/onerway/payment-methods', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
merchantId: 'your-merchant-id',
paymentMethod: 'APPLE_PAY'
})
});
if (!response.ok) {
throw new Error(`Configuration fetch failed: ${response.status}`);
}
return response.json();
}
/**
* Create Apple Pay payment request
* @param {Object} config - Onerway configuration
* @param {string} orderTotal - Order total amount
* @param {Array} orderItems - Order line items
* @returns {Object} Apple Pay payment request object
*/
function createPaymentRequest(config, orderTotal, orderItems) {
return {
countryCode: config.countryCode, // From Onerway
currencyCode: 'USD',
supportedNetworks: config.subCardTypes.map(card => card.toLowerCase()), // From Onerway
merchantCapabilities: ['supports3DS'],
total: {
label: 'Your Store Name', // Your merchant display name
amount: orderTotal.toString(), // String format, two decimal precision
type: 'final'
},
lineItems: orderItems
};
}
/**
* Start Apple Pay payment flow
* @param {string} orderTotal - Order total amount
* @param {Array} orderItems - Order line items
*/
async function startApplePayPayment(orderTotal, orderItems) {
try {
// Step 1: Get Onerway configuration
const config = await getOnerwayConfig();
// Step 2: Create payment request
const paymentRequest = createPaymentRequest(config, orderTotal, orderItems);
// Step 3: Create and start session (first time creating ApplePaySession and begin())
const session = new ApplePaySession(3, paymentRequest);
setupEventHandlers(session, config);
session.begin();
} catch (error) {
console.error('Failed to start Apple Pay:', error);
handlePaymentError(error);
}
}
/**
* Handle payment startup errors
* @param {Error} error - Error object
*/
function handlePaymentError(error) {
// Provide different user prompts based on error type
if (error.message.includes('Configuration fetch failed')) {
alert('Payment configuration loading failed, please try again later');
} else {
alert('Unable to start Apple Pay, please try again or choose another payment method');
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Apple Pay Session Documentation
For detailed session creation and configuration, see:
- ApplePaySession - Apple Pay Session API
- session.begin() - Start payment session
2. Event Handlers Setup
Apple Pay sessions require event handlers for merchant validation and payment processing. Set up the basic event structure:
/**
* Set up Apple Pay session event handlers
* @param {ApplePaySession} session - The Apple Pay session
* @param {Object} config - Merchant/Onerway configuration used during validation
*/
function setupEventHandlers(session, config) {
// Merchant validation - detailed implementation in merchant validation guide
session.onvalidatemerchant = (event) => {
handleMerchantValidation(session, event, config);
};
// Payment authorization - detailed implementation in payment authorization guide
session.onpaymentauthorized = (event) => {
handlePaymentAuthorization(event);
};
// User cancellation
session.oncancel = (event) => {
console.log('User cancelled Apple Pay');
// Clean up any pending processes
};
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Event Handler Implementation
The actual implementation of merchant validation and payment authorization involves complex logic. For detailed guidance:
- Merchant Validation: See Apple Pay Merchant Validation for complete implementation
- Payment Authorization: See Apple Pay Payment Authorization for payment processing logic
Apple Pay Event Documentation
Event handling details:
- onvalidatemerchant - Merchant validation event
- completeMerchantValidation - Complete merchant validation
- onpaymentauthorized - Payment authorization event
- completePayment - Complete payment
Complete Button Click Handler
Full Implementation with Onerway Integration
/**
* Check device support for Apple Pay
* @returns {boolean} Whether Apple Pay is supported
*/
function checkDeviceSupport() {
if (!ApplePaySession.canMakePayments()) {
alert('Apple Pay is not available on this device');
return false;
}
return true;
}
/**
* Get current order information
* @returns {Object} Order information object
*/
function getCurrentOrderInfo() {
// Example order information, should be obtained from the page or state management in real applications
return {
total: '29.99',
currencyCode: 'USD',
items: [
{ label: 'Product', amount: '24.99', type: 'final' },
{ label: 'Shipping', amount: '5.00', type: 'final' }
]
};
}
/**
* Complete Apple Pay button click handler
*/
async function handleApplePayButtonClick() {
// Step 1: Check device support
if (!checkDeviceSupport()) {
return;
}
try {
// Step 2: Get Onerway configuration (reuse previously defined function)
const config = await getOnerwayConfig();
// Step 3: Get current order information
const orderInfo = getCurrentOrderInfo();
// Step 4: Create payment request (reuse previously defined function)
const paymentRequest = createPaymentRequest(config, orderInfo.total, orderInfo.items);
// Update currency code to order currency
paymentRequest.currencyCode = orderInfo.currencyCode;
// Step 5: Start payment session
const session = new ApplePaySession(3, paymentRequest);
setupEventHandlers(session, config); // Contains Onerway integration logic
session.begin();
} catch (error) {
console.error('Failed to start Apple Pay:', error);
handlePaymentError(error);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Onerway API Documentation
Related Onerway API endpoints:
- Payment Methods Query API - Get
countryCode
,supportedNetworks
and other configurations - Merchant Validation API - Handle Apple Pay merchant validation requests
- Payment Processing API - Process Apple Pay payment tokens
Common Issues and Solutions
Device Support Issues
Issue: Apple Pay button doesn't appear
Cause: Device doesn't support Apple Pay
Solution:
// Check device support and provide fallback
if (ApplePaySession && ApplePaySession.canMakePayments()) {
document.getElementById('apple-pay-button').style.display = 'block';
} else {
document.getElementById('fallback-payment').style.display = 'block';
console.log('Apple Pay unavailable, showing alternative payment methods');
}
2
3
4
5
6
7
Configuration Error Issues
Issue: Receiving "Invalid merchant configuration" error
Cause: Onerway configuration information is incomplete or incorrect
Solution: Validate configuration obtained from Payment Methods Query API:
// Validate required configuration items
function validateConfig(config) {
const required = ['countryCode', 'subCardTypes'];
for (const field of required) {
if (!config[field]) {
throw new Error(`Missing required configuration: ${field}`);
}
}
if (!Array.isArray(config.subCardTypes) || config.subCardTypes.length === 0) {
throw new Error('Invalid supportedNetworks configuration');
}
}
2
3
4
5
6
7
8
9
10
11
12
13
Amount Format Issues
Issue: Payment amounts rejected by Apple Pay
Cause: Incorrect amount format
Solution: Ensure amounts are in string format with correct precision:
// Correct amount formatting
function formatAmount(amount) {
return Number(amount).toFixed(2).toString();
}
// Usage example
total: {
amount: formatAmount(orderTotal), // "29.99"
type: 'final'
}
// Incorrect: Don't pass numbers directly
// total: { amount: 29.99 }
2
3
4
5
6
7
8
9
10
11
12
13
Next Steps
After implementing payment initiation, continue to complete your Apple Pay integration:
- Merchant Validation: Learn how to handle
onvalidatemerchant
events and certificate management - Payment Authorization: Learn how to handle
onpaymentauthorized
events and payment processing - Complete Payment Flow: View full end-to-end sequence with Onerway integration
- Onerway Payment API: View detailed payment processing API documentation
Prerequisites Review
If you haven't completed the preliminary configuration, please refer to:
- Session Initialization: SDK loading, device detection, and button rendering
- Account Setup: Certificate configuration and domain validation
Chapter Completion Checklist
After completing this chapter, you should have implemented the following functionality:
- Obtained Apple Pay configuration from Onerway (
countryCode
,supportedNetworks
) - Created
paymentRequest
object with required parameters (total
,currencyCode
, etc.) - Implemented
ApplePaySession
creation andsession.begin()
call - Set up event handler structure (
onvalidatemerchant
,onpaymentauthorized
,oncancel
) - Added device support checking and error handling
- Implemented complete button click handler flow
Key Requirements
Integration Checklist
- ✅ HTTPS enabled on your domain
- ✅ Apple Pay configuration obtained from Onerway
- ✅ Event handlers for
onvalidatemerchant
andonpaymentauthorized
- ✅ Error handling for unsupported devices
- ✅ Backend integration ready for merchant validation and payment processing