Save PayPal for purchase later with the iOS SDK

CurrentLast updated: February 8th 2024, @ 12:25:19 pm


Allow customers to save their PayPal Wallets and charge them after a set amount of time. For example, you can offer a free trial and charge payers after the trial expires. Payers don't need to be present when charged and no checkout is required.

Customers with a PayPal Wallet can:

  • Review PayPal transactions and transaction history
  • Review, add, or remove funding sources
  • Review and cancel recurring payments
  • Hold a balance in their PayPal account
  • Use PayPal to send and receive money
  • Withdraw money to a linked bank account
  • Use PayPal to transact with merchants

Availability

  • Australia
  • Austria
  • Belgium
  • Bulgaria
  • Canada
  • China
  • Cyprus
  • Czech Republic
  • Denmark
  • Estonia
  • Finland
  • France
  • Germany
  • Hong Kong
  • Hungary
  • Ireland
  • Italy
  • Japan
  • Latvia
  • Liechtenstein
  • Lithuania
  • Luxembourg
  • Malta
  • Netherlands
  • Norway
  • Poland
  • Portugal
  • Romania
  • Singapore
  • Slovakia
  • Slovenia
  • Spain
  • Sweden
  • United Kingdom
  • United States

Use cases

Businesses save payment methods if they want customers to:

  • Check out without re-entering a payment method
  • Pay after use, for example, ride-sharing and food delivery

Know before you code

  • To save payment methods, you must be able to identify payers uniquely. For example, payers create an account and log in to your site.
  • Complete the steps in Get started to get the following sandbox account information from the Developer Dashboard:
    • Your sandbox account login information
    • Your access token

  • This integration requires a PayPal Developer account.
  • This integration must include a server-side call to exchange a setup token for a payment method token.

How it works

PayPal encrypts payment method information and stores it in a digital vault for that customer.

  1. The payer saves their payment method.
  2. For a first-time payer, PayPal creates a customer ID. Store this within your system for future use.
  3. Use the customer ID to retrieve saved payment methods and add new ones for existing customers in your application.

The checkout process is now shorter because it uses saved payment information.

1. Check eligibility

  1. Go to paypal.com and sign in with your business account.
  2. Go to Account Settings > Payment Preferences > Save PayPal and Venmo payment methods.
  3. In the Save PayPal and Venmo payment methods section, select Get Started.
  4. When you submit profile details, PayPal reviews your eligibility to save PayPal Wallets and Venmo accounts.
  5. After PayPal reviews your eligibility, you'll see a status of Success, Need more information, or Denied.

2. Set up account to save payments

Set up your sandbox and live business accounts to save payment methods:

  1. Log in to the Developer Dashboard.
  2. Under REST API apps, select your app name.
  3. Under Sandbox App Settings > App Feature Options, check Accept payments.
  4. Expand Advanced options. Confirm that Vault is selected.

To go live, you'll need to be vetted to save PayPal Wallets. You can start the vetting process from the Developer Dashboard.

  • Only your sandbox business account is enabled to save payment methods. Your developer account remains unaffected.
  • You'll complete production onboarding when you're ready to go live.

Tip: When prompted for data such as a phone number for a sandbox business request, enter any number that fits the required format. Since this is a sandbox request, the data doesn't have to be real.

3. Add the PayPalWebPayments module to your app

Add the PayPalWebPayments package dependency for your app using Swift Package Manager or CocoaPods:

  1. Swift Package Manager
  2. CocoaPods
1. Open Xcode. 2. Follow the guide to add package dependencies to your app.3. Enter https://github.com/paypal/paypal-ios/ as the repository URL.4. Select the checkbox for the PayPalWebPayments framework.

4. Add PayPal button

Add a button to your app's UI:

1Button("PayPal") {
2 // Create a setup token server-side (see next step)
3}

5. Create setup token

Request a setup token from your server, create a PayPalVaultRequest object, and call the vault() method.

Client-side code sample

1let config = CoreConfig(clientID: "CLIENT_ID", environment: .sandbox)
2let setupTokenResponse = createVaultSetupToken()
3let vaultRequest = PayPalVaultRequest(setupTokenID: setupTokenResponse.setupTokenId)
4
5let paypalClient = PayPalWebCheckoutClient(config: config)
6paypalClient.vaultDelegate = self
7paypalClient.vault(vaultRequest)
8
9// MARK: - PayPalVaultDelegate
10func paypal(_ paypalWebClient: PayPalWebCheckoutClient, didFinishWithVaultResult paypalVaultResult: PayPalVaultResult) {
11 // Handle success
12}
13
14func paypal(_ paypalWebClient: PayPalWebCheckoutClient, didFinishWithVaultError vaultError: CoreSDKError) {
15 // Handle error
16}
17
18func paypalDidCancel(_ paypalWebClient: PayPalWebCheckoutClient) {
19 // Handle cancellation
20}

Modify the code

Copy the code sample and modify it as follows:

  1. Change CLIENT_ID to your clientId.
  2. In the createVaultSetupToken method, call the endpoint on your server to create a setup token with the Payment Method Tokens API. createVaultSetupToken returns the setup token as a string.

Server-side code sample

Set up your server to call the Payment Method Tokens API.

The SDK uses the Payment Method Tokens API to save payment methods in the background. Use the following request as a template to create a setup token.

Note: The return_url and cancel_url values are required, but can have filler values such as in the following sample.

1curl -v -k -X POST 'https://api-m.sandbox.paypal.com/v3/vault/setup-tokens' \
2 -H 'Content-Type: application/json' \
3 -H 'Authorization: Bearer ACCESS-TOKEN' \
4 -H 'PayPal-Request-Id: REQUEST-ID' \
5 -d '{
6 "payment_source": {
7 "paypal": {
8 "usage_type": "PLATFORM",
9 "experience_context": {
10 "return_url": "https://example.com/returnUrl",
11 "cancel_url": "https://example.com/cancelUrl"
12 }
13 }
14 }
15 }'

Modify the code

  1. Change ACCESS-TOKEN to your sandbox app's access token.
  2. Change REQUEST-ID to a set of unique alphanumeric characters such as a timestamp.

Response

1{
2 "id": "4G4976650J0948357",
3 "customer": {
4 "id": "customer_4029352050"
5 },
6 "status": "PAYER_ACTION_REQUIRED",
7 "payment_source": {
8 "paypal": {
9 "description": "Description for PayPal to be shown to PayPal payer",
10 "usage_pattern": "IMMEDIATE",
11 "shipping": {
12 "name": {
13 "full_name": "Firstname Lastname"
14 },
15 "address": {
16 "address_line_1": "123 Main Street",
17 "address_line_2": "Unit A",
18 "admin_area_2": "Anytown",
19 "admin_area_1": "CA",
20 "postal_code": "12345",
21 "country_code": "US"
22 }
23 },
24 "permit_multiple_payment_tokens": false,
25 "usage_type": "PLATFORM",
26 "customer_type": "CONSUMER"
27 }
28 },
29 "links": [
30 {
31 "href": "https://api-m.sandbox.paypal.com/v3/vault/setup-tokens/4G4976650J0948357",
32 "rel": "self",
33 "method": "GET",
34 "encType": "application/json"
35 },
36 {
37 "href": "https://sandbox.paypal.com/agreements/approve?approval_session_id=4G4976650J0948357",
38 "rel": "approve",
39 "method": "GET",
40 "encType": "application/json"
41 }
42 ]
43 }

Payer approval

If payer approval is required, the client SDK calls the payer approval flow. The approval flow takes the payer through PayPal Checkout.

6. Create a payment token with the vault setup token ID

Convert the setup token to a payment token that can be used to process a transaction:

1curl -v -k -X POST 'https://api-m.sandbox.paypal.com/v3/vault/payment-tokens' \
2 -H "Content-Type: application/json" \
3 -H "Authorization: Bearer ACCESS-TOKEN" \
4 -H "PayPal-Request-Id: REQUEST-ID" \
5 -d '{
6 "payment_source": {
7 "token": {
8 "id": "VAULT-SETUP-TOKEN",
9 "type": "SETUP_TOKEN"
10 }
11 }
12 }'

Modify the code

  1. Change ACCESS-TOKEN to your sandbox app's access token.
  2. Change REQUEST-ID to a set of unique alphanumeric characters such as a timestamp.
  3. Change VAULT-SETUP-TOKEN to the value passed from the client.
  4. Save the resulting payment token returned from the API to use in future transactions.

7. Integrate back end

The following sample shows a complete back-end integration to save PayPal for purchase later:

1import "dotenv/config";
2import express from "express";
3const { PORT = 8888 } = process.env;
4const app = express();
5app.set("view engine", "ejs");
6app.use(express.static("public"));
7
8// Create setup token
9app.post("/create/setup/token", async (req, res) => {
10 try {
11 // Use your access token to securely generate a setup token
12 // with an empty payment_source
13 const vaultResponse = await fetch("https://api-m.sandbox.paypal.com/v3/vault/setup-tokens", {
14 method: "POST",
15 body: JSON.stringify({ payment_source: { paypal: {}} }),
16 headers: {
17 Authorization: 'Bearer ${ACCESS-TOKEN}',
18 "PayPal-Request-Id": Date.now(),
19 }
20 })
21 // Return the reponse to the client
22 res.json(vaultResponse);
23 } catch (err) {
24 res.status(500).send(err.message);
25 }
26})
27
28// Create payment token from a setup token
29app.post("/create/payment/token/", async (req, res) => {
30 try {
31 const paymentTokenResult = await fetch(
32 "https://api-m.sandbox.paypal.com/v3/vault/payment-tokens",
33 {
34 method: "POST",
35 body: {
36 payment_source: {
37 token: {
38 id: req.body.vaultSetupToken,
39 type: "SETUP_TOKEN"
40 }
41 }
42 },
43 headers: {
44 Authorization: 'Bearer ${ACCESS-TOKEN}',
45 "PayPal-Request-Id": Date.now(),
46 }
47 })
48 const paymentMethodToken = paymentTokenResult.id
49 const customerId = paymentTokenResult.customer.id
50 await save(paymentMethodToken, customerId)
51 res.json(captureData);
52 } catch (err) {
53 res.status(500).send(err.message);
54 }
55})
56
57const save = async function(paymentMethodToken, customerId) {
58 // Specify where to save the payment method token
59}
60
61app.listen(PORT, () => {
62 console.log('Server listening at http://localhost:${PORT}/');
63})

8. Test your integration

  1. In your app, render a PayPal button and initate the vault.
  2. Create a setup token.
  3. Call the vault function in the SDK.
  4. Create a payment token with the updated setup token.
  5. Store the PayPal-generated customer ID in your system.
  6. Log in to sandbox with your merchant account and verify the transaction.
  7. Return to your app and initiate another transaction. Use the PayPal-generated payment token as a payment source.
  8. Verify that the transaction captures successfully without having to complete PayPal Web Checkout again.

Optional: Show saved payment methods

Create a view where payers can see their payment methods using the Payment Method Tokens API

Next step

Go live with your integration.