- 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
Save PayPal for purchase later with the Android SDK
Last updated: Feb 25th, 3:19pm
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
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 custome
- The payer saves their payment method.
- For a first-time payer, PayPal creates a customer ID. Store this within your system for future use.
- 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.
Check eligibility
- Go to paypal.com and sign in with your business account.
- Go to Account Settings > Payment Preferences > Save PayPal and Venmo payment methods.
- In the Save PayPal and Venmo payment methods section, select Get Started.
- When you submit profile details, PayPal reviews your eligibility to save PayPal Wallets and Venmo accounts.
- After PayPal reviews your eligibility, you'll see a status of Success, Need more information, or Denied.
Set up account to save payments
Set up your sandbox and live business accounts to save payment methods:
- Log in to the Developer Dashboard.
- Under REST API apps, select your app name.
- Under Sandbox App Settings > App Feature Options, check Accept payments.
- 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.
Add the PayPalWebPayments module to your app
Add the PayPalWebPayments
package dependency for your app using a Gradle dependency:
Add the following dependency to your app's build.gradle
file.
- Groovy
- Kotlin
1dependencies {2 implementation 'com.paypal.android:paypal-web-payments:<CURRENT-VERSION>'3}
Create setup token
Request a setup token from your server, create a PayPalVaultRequest
object, and call the vault()
method.
1// Client-side code sample23val coreConfig = CoreConfig(CLIENT_ID)4val setupTokenResponse = createVaultSetupToken()5val vaultRequest = PayPalWebVaultRequest(setupTokenResponse.setupTokenId)67val paypalClient = PayPalWebCheckoutClient(activity, coreConfig, URL_SCHEME)8paypalClient.vaultListener = this9paypalClient.vault(vaultRequest)1011override fun onPayPalWebVaultSuccess(result: PayPalWebVaultResult) {12 // Handle success13}1415override fun onPayPalWebVaultFailure(error: PayPalSDKError) {16 // Handle failure17}1819override fun onPayPalWebVaultCanceled() {20 // Handle cancellation21}
Modify the code
Copy the code sample and modify it as follows:
- Change
CLIENT_ID
to your clientId. - Replace
URL_SCHEME
with the custom URL scheme used to return to your app. - Implement the callback listeners to handle success, failure, and cancellation.
- In the
createPayPalSetupToken
method, call the endpoint on your server to create a setup token with the Payment Method Tokens API.createPayPalSetupToken
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
- Change
ACCESS-TOKEN
to your sandbox app's access token. - 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
Convert the setup token to a payment token that can be used to process a transaction:
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
- Change
ACCESS-TOKEN
to your sandbox app's access token. - Change
REQUEST-ID
to a set of unique alphanumeric characters such as a timestamp. - Change
VAULT-SETUP-TOKEN
to the value passed from the client. - Save the resulting
payment token
returned from the API to use in future transactions.
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"));78// Create setup token9app.post("/create/setup/token", async (req, res) => {10 try {11 // Use your access token to securely generate a setup token12 // with an empty payment_source13 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 client22 res.json(vaultResponse);23 } catch (err) {24 res.status(500).send(err.message);25 }26})2728// Create payment token from a setup token29app.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.id49 const customerId = paymentTokenResult.customer.id50 await save(paymentMethodToken, customerId)51 res.json(captureData);52 } catch (err) {53 res.status(500).send(err.message);54 }55})5657const save = async function(paymentMethodToken, customerId) {58 // Specify where to save the payment method token59}6061app.listen(PORT, () => {62 console.log('Server listening at http://localhost:${PORT}/');63})
Test your integration
- In your app, render a PayPal button and initate the vault.
- Create a setup token.
- Call the vault function in the SDK.
- Create a payment token with the updated setup token.
- Store the PayPal-generated customer ID in your system.
- Log in to sandbox with your merchant account and verify the transaction.
- Return to your app and initiate another transaction. Use the PayPal-generated payment token as a payment source.
- 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.