Skip to content

PayPal Payment Integration Documentation


Overview

This documentation provides a detailed explanation of the views and helper functions required for PayPal payment integration in a Django-based project. The integration includes: 1. Generating PayPal payment links 2. Capturing payments 3. Handling successful or cancelled payments 4. Managing transactions, product purchases, and sending email notifications to users and vendors.


File Structure

The relevant files involved are: - views.py: Contains API views for handling PayPal payments. - paypal_services.py: Provides helper functions to interact with PayPal APIs. - tasks.py: Manages asynchronous email notifications (assumed). - email templates: HTML templates for user and vendor emails.


API Endpoints

1. List Transactions

  • URL: /api/v1/payments/transactions/
  • Method: GET
  • Permissions: IsAuthenticated
  • Description: Lists user-specific transactions with filtering, ordering, and pagination.

Query Parameters:

  • start_date: Filter transactions starting from a specific date.
  • end_date: Filter transactions up to a specific date.
  • order_id: Filter by order ID.
  • product_name: Filter transactions by product name (case-insensitive).
  • ordering: Order results by created_at or amount.

Response:

{
    "pageSize": 20,
    "count": 1,
    "page_count": 1,
    "active_page": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 2,
            "transaction_id": "4BL61604ED2373943",
            "amount": "10.00",
            "payment_method": "PayPal",
            "status": true,
            "created_at": "12-17-2024 08:18:09",
            "updated_at": "12-17-2024 08:20:19",
            "product_purchased": {
                "id": 3,
                "applied_coupon": null,
                "total_purchased": "10000.00",
                "discounted_amount": "0.00",
                "net_amount": "10000.00",
                "has_purchased_succeed": true,
                "purchased_at": "12-17-2024 05:13:01",
                "purchased_cart_items": [
                    {
                        "id": 8,
                        "order_id": "KS8f510439",
                        "cart_item": {
                            "id": 4,
                            "product": {
                                "id": 5,
                                "name": "Floral Embroidered Georgette Saree",
                                "slug": "floral-embroidered-georgette-saree",
                                "price": "67868.00",
                                "is_active": true
                            },
                            "variant": {
                                "id": 15,
                                "color": "Dirty Blue",
                                "value": "#3F829D",
                                "variant_price": "10000.00",
                                "stock_quantity": 244,
                                "is_available": true,
                                "is_active": true,
                                "variant_images": [],
                                "size": {
                                    "size": "Small",
                                    "value": "S"
                                }
                            },
                            "quantity": 1,
                            "has_purchased": true,
                            "created_at": "12-17-2024 06:43:20",
                            "updated_at": "12-17-2024 08:18:09"
                        },
                        "status": true,
                        "created_at": "12-17-2024 06:43:30",
                        "updated_at": "12-17-2024 08:18:09"
                    }
                ]
            }
        }
    ]
}

2. Retrieve Transaction Details

  • URL: /api/v1/payments/transactions/{transaction_id}/
  • Method: GET
  • Permissions: IsAuthenticated
  • Description: Retrieves detailed information for a specific transaction.

Response:

{
    "id": 2,
    "transaction_id": "4BL61604ED2373943",
    "amount": "10.00",
    "payment_method": "PayPal",
    "status": true,
    "created_at": "12-17-2024 08:18:09",
    "updated_at": "12-17-2024 08:20:19",
    "product_purchased": {
        "id": 3,
        "applied_coupon": null,
        "total_purchased": "10000.00",
        "discounted_amount": "0.00",
        "net_amount": "10000.00",
        "has_purchased_succeed": true,
        "purchased_at": "12-17-2024 05:13:01",
        "purchased_cart_items": [
            {
                "id": 8,
                "order_id": "KS8f510439",
                "cart_item": {
                    "id": 4,
                    "product": {
                        "id": 5,
                        "name": "Floral Embroidered Georgette Saree",
                        "slug": "floral-embroidered-georgette-saree",
                        "price": "67868.00",
                        "is_active": true
                    },
                    "variant": {
                        "id": 15,
                        "color": "Dirty Blue",
                        "value": "#3F829D",
                        "variant_price": "10000.00",
                        "stock_quantity": 244,
                        "is_available": true,
                        "is_active": true,
                        "variant_images": [],
                        "size": {
                            "size": "Small",
                            "value": "S"
                        }
                    },
                    "quantity": 1,
                    "has_purchased": true,
                    "created_at": "12-17-2024 06:43:20",
                    "updated_at": "12-17-2024 08:18:09"
                },
                "status": true,
                "created_at": "12-17-2024 06:43:30",
                "updated_at": "12-17-2024 08:18:09"
            }
        ]
    }
}

3. Create PayPal Payment

  • URL: /api/v1/payments/paypal/
  • Method: POST
  • Permissions: IsAuthenticated
  • Description: Generates a PayPal payment link and returns an approval URL for user redirection.

Payload:

{
    "amount": "100.00",
    "product_purchased_id": 1,
    "shipment_address_id": 10
}

Response:

{
    "approval_url": "https://www.sandbox.paypal.com/checkoutnow?token=2HB61379BH904350R"
}

4. Execute PayPal Payment

  • URL: /api/v1/payments/paypal/execute/
  • Method: GET
  • Permissions: IsAuthenticated
  • Description: Captures the PayPal order, updates transaction records, and sends email notifications.

Response:

{
    "status": "Payment executed successfully."
}

5. Cancel PayPal Payment

  • URL: /api/v1/payments/paypal/cancel/
  • Method: GET
  • Permissions: IsAuthenticated
  • Description: Handles cancelled PayPal payments.

Helper Functions: paypal_services.py

1. Get PayPal Access Token

def get_paypal_access_token():
    url = f"{settings.PAYPAL_API_BASE_URL}/v1/oauth2/token"
    response = requests.post(url, auth=HTTPBasicAuth(settings.PAYPAL_CLIENT_ID, settings.PAYPAL_CLIENT_SECRET))
    response.raise_for_status()
    return response.json()['access_token']

2. Create PayPal Order

def create_paypal_order(amount, return_url, cancel_url):
    access_token = get_paypal_access_token()
    url = f"{settings.PAYPAL_API_BASE_URL}/v2/checkout/orders"
    headers = {"Authorization": f"Bearer {access_token}"}
    data = {
        "intent": "CAPTURE",
        "purchase_units": [{"amount": {"currency_code": "USD", "value": amount}}],
        "application_context": {"return_url": return_url, "cancel_url": cancel_url}
    }
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
    return response.json()

3. Capture PayPal Order

def capture_paypal_order(order_id):
    access_token = get_paypal_access_token()
    url = f"{settings.PAYPAL_API_BASE_URL}/v2/checkout/orders/{order_id}/capture"
    headers = {"Authorization": f"Bearer {access_token}"}
    response = requests.post(url, headers=headers)
    response.raise_for_status()
    return response.json()