Initialize PayPal SDK
- Start by creating a Maven or Gradle project to manage PayPal dependencies. Add the PayPal SDK in the `pom.xml` if you’re using Maven:
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>rest-api-sdk</artifactId>
<version>1.14.0</version>
</dependency>
- If you're using Gradle, add the following to your `build.gradle`:
implementation 'com.paypal.sdk:rest-api-sdk:1.14.0'
Set Up API Context
- Create an `APIContext` class instance using your PayPal client ID and secret. This context will store the credentials and the mode (sandbox or live):
APIContext apiContext = new APIContext("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "sandbox");
Define Subscription Plan
- Construct a Subscription Plan using PayPal's SDK. Define billing cycles, payment preferences, and merchant preferences:
import com.paypal.api.payments.*;
Plan plan = new Plan();
plan.setName("Monthly Subscription Plan");
plan.setDescription("Monthly subscription plan for premium content");
plan.setType("fixed");
PaymentDefinition paymentDefinition = new PaymentDefinition();
paymentDefinition.setName("Regular Payments");
paymentDefinition.setType("REGULAR");
paymentDefinition.setFrequency("MONTH");
paymentDefinition.setFrequencyInterval("1");
paymentDefinition.setCycles("12");
paymentDefinition.setAmount(new Currency("USD", "10.00"));
List<PaymentDefinition> paymentDefinitions = new ArrayList<>();
paymentDefinitions.add(paymentDefinition);
plan.setPaymentDefinitions(paymentDefinitions);
MerchantPreferences merchantPreferences = new MerchantPreferences();
merchantPreferences.setReturnUrl("https://example.com/return");
merchantPreferences.setCancelUrl("https://example.com/cancel");
merchantPreferences.setAutoBillAmount("YES");
merchantPreferences.setInitialFailAmountAction("CONTINUE");
merchantPreferences.setMaxFailAttempts("0");
merchantPreferences.setSetupFee(new Currency("USD", "1.00"));
plan.setMerchantPreferences(merchantPreferences);
plan.create(apiContext);
Activate the Plan
- After creating the plan, you must activate it. Update the plan state to `ACTIVE`:
List<Patch> patchRequestList = new ArrayList<>();
Map<String, String> value = new HashMap<>();
value.put("state", "ACTIVE");
Patch patch = new Patch();
patch.setOp("replace");
patch.setPath("/");
patch.setValue(value);
patchRequestList.add(patch);
plan.update(apiContext, patchRequestList);
Create a Subscription
- Create an agreement (subscription) object and set the plan ID of the active plan. Include payer information and redirect URLs:
Agreement agreement = new Agreement();
agreement.setName("Monthly Subscription Agreement");
agreement.setDescription("Agreement for Monthly Subscription");
agreement.setStartDate("2023-12-01T00:00:00Z");
Plan newPlan = new Plan();
newPlan.setId(plan.getId());
agreement.setPlan(newPlan);
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
agreement.setPayer(payer);
Agreement result = agreement.create(apiContext);
for (Links links : result.getLinks()) {
if ("approval_url".equals(links.getRel())) {
// Redirect to PayPal payment approval URL
System.out.println("Redirect user to: " + links.getHref());
}
}
Execute the Agreement
- After the user approves the subscription, execute it to finalize the agreement. Use the `token` you get from the return URL as part of the execution:
Agreement executedAgreement = new Agreement();
executedAgreement.setToken("TOKEN_FROM_QUERY_PARAMETER");
executedAgreement.execute(apiContext, executedAgreement.getToken());
Handling Webhooks
- Use PayPal Webhooks to handle events such as subscription approvals, payments, and cancellations. Configure a webhook listener endpoint in your server, process the incoming data, and validate it using PayPal’s SDK:
WebhookEvent verifyEvent = WebhookEvent.verifyReceivedEvent(apiContext, requestBody, headers);
if (verifyEvent != null) {
// Process the event
}
Testing and Finalizing
- Always test your subscription flow in PayPal's sandbox environment before deploying live. Check each step — from plan creation to subscription execution and webhook handling — ensuring all components work smoothly.
Remember to replace placeholder values such as YOUR_CLIENT_ID
and URLs with real values before deploying. Integrating PayPal subscriptions can be streamlined by following these structured steps, enhancing your application's payment system robustly.