|

|  How to Implement PayPal Subscription API in Java

How to Implement PayPal Subscription API in Java

October 31, 2024

Learn to integrate the PayPal Subscription API in Java with our step-by-step guide, enhancing your app with seamless payment solutions.

How to Implement PayPal Subscription API in Java

 

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.

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi 開発キット 2

無限のカスタマイズ

OMI 開発キット 2

$69.99

Omi AIネックレスで会話を音声化、文字起こし、要約。アクションリストやパーソナライズされたフィードバックを提供し、あなたの第二の脳となって考えや感情を語り合います。iOSとAndroidでご利用いただけます。

  • リアルタイムの会話の書き起こしと処理。
  • 行動項目、要約、思い出
  • Omi ペルソナと会話を活用できる何千ものコミュニティ アプリ

もっと詳しく知る

Omi Dev Kit 2: 新しいレベルのビルド

主な仕様

OMI 開発キット

OMI 開発キット 2

マイクロフォン

はい

はい

バッテリー

4日間(250mAH)

2日間(250mAH)

オンボードメモリ(携帯電話なしで動作)

いいえ

はい

スピーカー

いいえ

はい

プログラム可能なボタン

いいえ

はい

配送予定日

-

1週間

人々が言うこと

「記憶を助ける、

コミュニケーション

ビジネス/人生のパートナーと、

アイデアを捉え、解決する

聴覚チャレンジ」

ネイサン・サッズ

「このデバイスがあればいいのに

去年の夏

記録する

「会話」

クリスY.

「ADHDを治して

私を助けてくれた

整頓された。"

デビッド・ナイ

OMIネックレス:開発キット
脳を次のレベルへ

最新ニュース
フォローして最新情報をいち早く入手しましょう

最新ニュース
フォローして最新情報をいち早く入手しましょう

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Manifesto

Compliance

Products

Omi

Wrist Band

Omi Apps

omi Dev Kit

omiGPT

Personas

Omi Glass

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

Ambassadors

Resellers

© 2025 Based Hardware. All rights reserved.