Learn how to enable Apple Pay in Stripe with this step-by-step guide for iOS and web, including setup, configuration, and testing for seamless payments.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
How to Enable Apple Pay in Stripe: A Comprehensive Guide
Step 1: Create a Stripe Account
Before setting up Apple Pay, ensure you have a Stripe account. If not, go to the Stripe website (https://stripe.com) and sign up for an account. Complete the verification process to activate your account.
Step 2: Install and Set Up Stripe SDK
For iOS applications, you'll need to install the Stripe SDK. You can use CocoaPods, Swift Package Manager, or Carthage.
Using CocoaPods:
Add to your Podfile
pod 'Stripe'
pod 'StripeApplePay'
Then run
pod install
Using Swift Package Manager:
// In Xcode, go to File > Swift Packages > Add Package Dependency
// Enter the Stripe SDK URL: https://github.com/stripe/stripe-ios
Step 3: Configure Your iOS Project for Apple Pay
Step 4: Create a Merchant ID in Apple Developer Account
Step 5: Create a Payment Processing Certificate
Step 6: Configure Your Domain for Web-based Apple Pay
If you're implementing Apple Pay on a website:
Step 7: Register Your Domain with Stripe
For web implementations, register your domain with Stripe:
// Server-side code (Node.js example)
const stripe = require('stripe')('sk_test_your\_key');
// Register domain with Stripe
stripe.applePayDomains.create({
domain\_name: 'yourdomain.com',
});
Step 8: Initialize Apple Pay in Your iOS App
First, import the necessary frameworks:
import Stripe
import StripeApplePay
import PassKit
Next, set up the Apple Pay button and check if the device can make payments:
// Check if the device supports Apple Pay
func canMakeApplePayPayments() -> Bool {
return StripeAPI.deviceSupportsApplePay() && PKPaymentAuthorizationController.canMakePayments()
}
// Set up Apple Pay button
func setupApplePayButton() {
let applePayButton = PKPaymentButton(paymentButtonType: .buy, paymentButtonStyle: .black)
applePayButton.addTarget(self, action: #selector(handleApplePayButtonTapped), for: .touchUpInside)
// Add to your view
view.addSubview(applePayButton)
// Set constraints
applePayButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
applePayButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
applePayButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
applePayButton.widthAnchor.constraint(equalToConstant: 200),
applePayButton.heightAnchor.constraint(equalToConstant: 44)
])
}
Step 9: Handle Apple Pay Button Tap
Implement the handler for the Apple Pay button:
@objc func handleApplePayButtonTapped() {
// Create a payment request
let paymentRequest = StripeAPI.paymentRequest(withMerchantIdentifier: "merchant.com.yourcompany.yourapp", country: "US", currency: "USD")
// Configure the payment request
paymentRequest.requiredBillingContactFields = [.postalAddress]
// Add items to the payment request
paymentRequest.paymentSummaryItems = [
PKPaymentSummaryItem(label: "Your Product", amount: NSDecimalNumber(string: "10.00")),
PKPaymentSummaryItem(label: "Your Company Name", amount: NSDecimalNumber(string: "10.00"))
]
// Present the Apple Pay payment sheet
if let paymentController = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest) {
paymentController.delegate = self
present(paymentController, animated: true, completion: nil)
} else {
// Apple Pay not available
print("Apple Pay is not available")
}
}
Step 10: Implement PKPaymentAuthorizationViewControllerDelegate
Implement the delegate methods to handle the payment authorization:
extension YourViewController: PKPaymentAuthorizationViewControllerDelegate {
func paymentAuthorizationViewController(\_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
// Convert the PKPayment to a Stripe token
STPAPIClient.shared.createToken(with: payment) { (token, error) in
if let error = error {
// Handle error
print("Error creating token: (error.localizedDescription)")
completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
return
}
guard let token = token else {
// Handle missing token
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
return
}
// Send the token to your server for processing
self.processPayment(with: token.tokenId) { (success, error) in
if success {
completion(PKPaymentAuthorizationResult(status: .success, errors: nil))
} else {
completion(PKPaymentAuthorizationResult(status: .failure, errors: [error].compactMap { $0 }))
}
}
}
}
func paymentAuthorizationViewControllerDidFinish(\_ controller: PKPaymentAuthorizationViewController) {
// Dismiss the Apple Pay UI
controller.dismiss(animated: true, completion: nil)
}
// Function to process payment with your server
func processPayment(with token: String, completion: @escaping (Bool, Error?) -> Void) {
// Send the token to your server
// Implement your API call here
// Example:
let url = URL(string: "https://yourserver.com/process-payment")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters: [String: Any] = [
"token": token,
"amount": 1000, // Amount in cents
"currency": "USD"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
completion(false, error)
return
}
// Process the response
// This is just an example, implement your own logic
completion(true, nil)
}.resume()
}
}
Step 11: Set Up Server-Side Processing
Create a server endpoint to process the payment. Here's an example using Node.js and Express:
const express = require('express');
const bodyParser = require('body-parser');
const stripe = require('stripe')('sk_test_your_secret_key');
const app = express();
app.use(bodyParser.json());
app.post('/process-payment', async (req, res) => {
try {
const { token, amount, currency } = req.body;
// Create a charge using the token
const charge = await stripe.charges.create({
amount: amount,
currency: currency,
source: token,
description: 'Apple Pay charge',
});
// Handle successful charge
res.json({ success: true, charge: charge });
} catch (error) {
// Handle error
console.error('Error processing payment:', error);
res.status(500).json({ success: false, error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Step 12: Implement Apple Pay for Web (Optional)
If you're also implementing Apple Pay on a website, add the following JavaScript:
// Initialize Stripe.js
const stripe = Stripe('pk_test_your_publishable_key');
// Check if Apple Pay is available
const paymentRequest = stripe.paymentRequest({
country: 'US',
currency: 'usd',
total: {
label: 'Your Company Name',
amount: 1000,
},
requestPayerName: true,
requestPayerEmail: true,
});
paymentRequest.canMakePayment().then(function(result) {
if (result && result.applePay) {
// Apple Pay is available, show the button
const elements = stripe.elements();
const prButton = elements.create('paymentRequestButton', {
paymentRequest: paymentRequest,
style: {
paymentRequestButton: {
type: 'buy',
theme: 'dark',
},
},
});
// Mount the button
prButton.mount('#payment-request-button');
// Handle the payment request
paymentRequest.on('paymentmethod', async function(event) {
// Send the payment method ID to your server
const response = await fetch('/process-payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
paymentMethodId: event.paymentMethod.id,
amount: 1000, // Amount in cents
currency: 'usd',
}),
}).then((res) => res.json());
if (response.error) {
// Show error to your customer
event.complete('fail');
} else {
// Payment successful
event.complete('success');
}
});
} else {
// Apple Pay not available, hide the button
document.getElementById('payment-request-button').style.display = 'none';
}
});
Add the corresponding HTML:
Step 13: Test Your Implementation
For iOS:
For Web:
Step 14: Go Live
When you're ready to go live:
Remember to thoroughly test the payment flow in both development and production environments before making it available to users.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.