PayPal Integration with Python Flask for Secure Payments


PayPal is one of the most widely used payment platforms globally, making it an excellent choice for adding payment functionality to your web applications. In this guide, we’ll walk you through integrating PayPal with a Python Flask application from scratch. You’ll learn how to set up your environment, configure PayPal’s REST API, create and execute payments, and test the integration. By the end, you’ll have a fully functional payment flow that you can expand for your specific needs.


Step 1: Setup Your Environment

  1. Install Python
    Ensure you have Python 3.7+ installed. You can download it from Python's official website.

  2. Create a Flask Project
    Create a new directory for your project and set up a virtual environment:

    mkdir flask-paypal-integration
    cd flask-paypal-integration
    python -m venv venv
    source venv/bin/activate  # For Windows, use `venv\Scripts\activate`
    pip install flask
  3. Install Required Libraries
    Install Flask and the PayPal SDK:

    pip install flask flask-cors paypalrestsdk

Step 2: Set Up a PayPal Developer Account

  1. Go to PayPal Developer Dashboard.
  2. Log in and create a REST API app.
    • Choose a name for your app.
    • Get your Client ID and Secret Key from the dashboard.
    • Choose the Sandbox environment for testing.

Step 3: Create the Flask App

Create a app.py file with the following content:

from flask import Flask, request, jsonify, redirect, url_for
import paypalrestsdk

app = Flask(__name__)

# PayPal SDK Configuration
paypalrestsdk.configure({
    "mode": "sandbox",  # Change to "live" for production
    "client_id": "YOUR_PAYPAL_CLIENT_ID",
    "client_secret": "YOUR_PAYPAL_SECRET_KEY"
})


@app.route('/')
def home():
    return "<h1>Welcome to PayPal Flask Integration</h1>"


@app.route('/create-payment', methods=['POST'])
def create_payment():
    data = request.json
    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "redirect_urls": {
            "return_url": "http://localhost:5000/execute-payment",
            "cancel_url": "http://localhost:5000/cancel-payment"
        },
        "transactions": [{
            "item_list": {
                "items": [{
                    "name": data['item_name'],
                    "sku": data['item_sku'],
                    "price": data['item_price'],
                    "currency": "USD",
                    "quantity": 1
                }]
            },
            "amount": {
                "total": data['item_price'],
                "currency": "USD"
            },
            "description": data['item_description']
        }]
    })

    if payment.create():
        for link in payment.links:
            if link.rel == "approval_url":
                return jsonify({"approval_url": link.href})
    else:
        return jsonify({"error": payment.error}), 400


@app.route('/execute-payment', methods=['GET'])
def execute_payment():
    payment_id = request.args.get('paymentId')
    payer_id = request.args.get('PayerID')

    payment = paypalrestsdk.Payment.find(payment_id)

    if payment.execute({"payer_id": payer_id}):
        return "<h1>Payment executed successfully!</h1>"
    else:
        return jsonify({"error": payment.error}), 400


@app.route('/cancel-payment')
def cancel_payment():
    return "<h1>Payment canceled!</h1>"


if __name__ == '__main__':
    app.run(debug=True)

Step 4: Test the Application

  1. Start the Flask server:

    python app.py
  2. Use a tool like Postman or cURL to create a payment:

    • Endpoint: http://localhost:5000/create-payment
    • Method: POST
    • Body (JSON):
      {
          "item_name": "Test Item",
          "item_sku": "12345",
          "item_price": "10.00",
          "item_description": "A description of the test item."
      }
  3. The response will include an approval_url. Open it in your browser to test the PayPal payment flow.

  4. After approval, you'll be redirected to the /execute-payment endpoint, where the payment will be processed.


  5. Step 5: Move to Production

    1. Update the mode in the PayPal configuration to "live".
    2. Replace the sandbox client_id and client_secret with live credentials.
    3. Deploy your Flask app on a hosting platform like Heroku, AWS, or Azure.

    Optional Features

    • Webhook Integration: Configure PayPal webhooks to listen for payment events.
    • Database Storage: Use a database like MySQL or MongoDB to store payment data.
    • Logging: Use Python's logging module to log errors and transactions.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete