# All files / services paypalService.js

0% Statements 0/51
0% Branches 0/42
0% Functions 0/6
0% Lines 0/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165

     /**
     * PayPal Service - Payment Integration
     * Handles PayPal payment creation and status checking
     */

    const paypal = require('@paypal/checkout-server-sdk');
    const { logger } = require('../config/logger');

    class PayPalService {
      constructor(clientId, clientSecret, sandbox = true) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.sandbox = sandbox;

        // Configure environment
        const environment = sandbox
          ? new paypal.core.SandboxEnvironment(clientId, clientSecret)
          : new paypal.core.LiveEnvironment(clientId, clientSecret);

        this.client = new paypal.core.PayPalHttpClient(environment);
      }

      async createPayment(data) {
        try {
          const request = new paypal.orders.OrdersCreateRequest();
          request.prefer('return=representation');
          const currency = (data.currency || 'USD').toString().toUpperCase();
          request.requestBody({
            intent: 'CAPTURE',
            purchase_units: [
              {
                reference_id: data.reference_id || Date.now().toString(),
                amount: {
                  currency_code: currency,
                  value: data.amount.toFixed(2)
                },
                description: data.description || 'Payment via WhatsApp'
              }
            ],
            payer: {
              name: {
                given_name: data.customer_name?.split(' ')[0] || 'Customer',
                surname: data.customer_name?.split(' ').slice(1).join(' ') || ''
              }
            },
            application_context: {
              return_url: `${process.env.BASE_URL || 'http://localhost:3000'}/payments/success`,
              cancel_url: `${process.env.BASE_URL || 'http://localhost:3000'}/payments/cancel`,
              brand_name: process.env.APP_NAME || 'Payment System',
              locale: 'en-US',
              landing_page: 'BILLING',
              shipping_preference: 'NO_SHIPPING',
              user_action: 'PAY_NOW'
            }
          });

          const order = await this.client.execute(request);

          // Find approval link
          const approvalUrl = order.result.links.find((link) => link.rel === 'approve')?.href;

          if (!approvalUrl) {
            throw new Error('Approval URL not found in PayPal response');
          }

          return {
            success: true,
            payment_id: order.result.id,
            payment_url: approvalUrl,
            status: order.result.status.toLowerCase()
          };
        } catch (error) {
          logger.error('Error creating PayPal payment:', error);

          // Check for authentication errors
          if (error.statusCode === 401 || error.message?.includes('Authentication')) {
            logger.error('PayPal authentication failed. Check Client ID and Secret.');
            return {
              success: false,
              error: 'PayPal authentication failed. Please verify your Client ID and Secret are correct.',
              details: error.message
            };
          }

          return {
            success: false,
            error: error.message || 'Error creating PayPal payment',
            details: error.response?.data || error.details || null
          };
        }
      }

      async capturePayment(orderId) {
        try {
          const request = new paypal.orders.OrdersCaptureRequest(orderId);
          request.requestBody({});

          const capture = await this.client.execute(request);

          return {
            success: true,
            status: capture.result.status,
            capture_id: capture.result.purchase_units[0].payments.captures[0].id,
            amount: capture.result.purchase_units[0].payments.captures[0].amount
          };
        } catch (error) {
          logger.error('Error capturing PayPal payment:', error);
          return {
            success: false,
            error: error.message || 'Error capturing payment'
          };
        }
      }

      async getPaymentStatus(orderId) {
        try {
          const request = new paypal.orders.OrdersGetRequest(orderId);
          const order = await this.client.execute(request);

          let status = 'pending';
          let paid_at = null;

          if (order.result.status === 'COMPLETED') {
            status = 'paid';
            paid_at = new Date();
          } else if (order.result.status === 'CANCELLED') {
            status = 'cancelled';
          } else if (order.result.status === 'APPROVED') {
            status = 'pending';
          }

          return {
            success: true,
            status: status,
            paid_at: paid_at,
            paypal_status: order.result.status
          };
        } catch (error) {
          logger.error('Error checking PayPal status:', error);
          return {
            success: false,
            error: error.message || 'Error checking status',
            status: 'pending',
            paid_at: null
          };
        }
      }

      validateWebhook(_headers, _body, _webhookId) {
        // Basic webhook validation
        // For production, implement full PayPal webhook signature verification
        // https://developer.paypal.com/api/rest/webhooks/

        if (process.env.NODE_ENV === 'development') {
          logger.info('PayPal webhook validation skipped (development mode)');
          return true;
        }

        logger.warn('PayPal webhook validation not fully configured');
        return true;
      }
    }

    module.exports = PayPalService;