All files / src/features/donation/services paypal.service.ts

98.27% Statements 57/58
90.9% Branches 20/22
100% Functions 7/7
98.27% Lines 57/58

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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                            17x     17x 17x       15x 15x   15x   15x   15x       15x       15x       8x 8x   8x 8x 8x                       7x   1x 1x                         3x 3x 2x 2x       2x   2x                         2x                 1x               2x 2x                   3x 3x   3x 1x 1x     2x 2x 2x 2x   2x                   2x 2x                         2x 1x     1x   1x 1x         3x 3x 3x 3x     3x             2x 3x 1x   1x                         1x   2x 2x        
import { Injectable, Logger } from '@nestjs/common'
import { IncomingHttpHeaders } from 'http'
import { ConfigService } from '@nestjs/config'
import { HttpService } from '@nestjs/axios'
import { firstValueFrom } from 'rxjs'
import {
    PaymentProvider,
    CreatePaymentIntentResult,
    PaymentConfig,
} from '../interfaces/payment-provider.interface'
import { PayPalProviderConfig } from '@fundraising/white-labeling'
 
@Injectable()
export class PayPalService implements PaymentProvider {
    private readonly logger = new Logger(PayPalService.name)
 
    constructor(
        private configService: ConfigService,
        private readonly httpService: HttpService,
    ) {}
 
    private getCredentials(config?: PaymentConfig) {
        const ppConfig = config as PayPalProviderConfig
        const clientId = ppConfig?.clientId || this.configService.get<string>('PAYPAL_CLIENT_ID')
        const clientSecret =
            ppConfig?.clientSecret || this.configService.get<string>('PAYPAL_CLIENT_SECRET')
        const sandbox =
            ppConfig?.sandbox ?? this.configService.get<string>('PAYPAL_SANDBOX') === 'true'
 
        Iif (!clientId || !clientSecret) {
            this.logger.warn('PAYPAL_CLIENT_ID or PAYPAL_CLIENT_SECRET not defined')
        }
 
        return { clientId, clientSecret, sandbox }
    }
 
    private getBaseUrl(sandbox: boolean): string {
        return sandbox ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com'
    }
 
    private async getAccessToken(config?: PaymentConfig): Promise<string> {
        const { clientId, clientSecret, sandbox } = this.getCredentials(config)
        const baseUrl = this.getBaseUrl(sandbox)
 
        const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
        try {
            const { data } = await firstValueFrom(
                this.httpService.post(
                    `${baseUrl}/v1/oauth2/token`,
                    'grant_type=client_credentials',
                    {
                        headers: {
                            Authorization: `Basic ${auth}`,
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                    },
                ),
            )
            return data.access_token
        } catch (error) {
            this.logger.error(`Error getting access token: ${error.message}`)
            throw error
        }
    }
 
    /**
     * Creates a PayPal Order (equivalent to PaymentIntent)
     */
    async createPaymentIntent(
        amount: number,
        currency: string = 'USD',
        metadata: Record<string, any> = {},
        config?: PaymentConfig,
    ): Promise<CreatePaymentIntentResult> {
        try {
            const accessToken = await this.getAccessToken(config)
            const { sandbox } = this.getCredentials(config)
            const baseUrl = this.getBaseUrl(sandbox)
 
            // PayPal expects standard units (e.g. 10.00), not cents.
            // Assuming amount passed is in CENTS.
            const amountUnit = (amount / 100).toFixed(2)
 
            const payload = {
                intent: 'CAPTURE',
                purchase_units: [
                    {
                        amount: {
                            currency_code: currency.toUpperCase(),
                            value: amountUnit,
                        },
                        custom_id: JSON.stringify(metadata), // Storing metadata in custom_id or just relying on local DB
                    },
                ],
            }
 
            const { data } = await firstValueFrom(
                this.httpService.post(`${baseUrl}/v2/checkout/orders`, payload, {
                    headers: {
                        Authorization: `Bearer ${accessToken}`,
                        'Content-Type': 'application/json',
                    },
                }),
            )
 
            return {
                id: data.id,
                // PayPal doesn't have a 'client_secret' in the same way Stripe does for some flows,
                // but for standard JS SDK, the Order ID is enough.
                // We will return the ID as the secret too or null. Use ID for both to be safe.
                clientSecret: data.id,
            }
        } catch (error) {
            this.logger.error(`Error creating PayPal order: ${error.message}`)
            throw error
        }
    }
 
    // Verification via API
    async constructEventFromPayload(
        headers: IncomingHttpHeaders | string,
        payload: Buffer,
        config?: PaymentConfig,
    ): Promise<any> {
        const ppConfig = config as PayPalProviderConfig
        const webhookId = ppConfig?.webhookId || this.configService.get<string>('PAYPAL_WEBHOOK_ID')
 
        if (!webhookId) {
            this.logger.warn('PAYPAL_WEBHOOK_ID not set. Skipping verification (INSECURE).')
            return JSON.parse(payload.toString())
        }
 
        const accessToken = await this.getAccessToken(config)
        const { sandbox } = this.getCredentials(config) // Get sandbox status
        const baseUrl = this.getBaseUrl(sandbox)
        const body = JSON.parse(payload.toString())
 
        const verificationBody = {
            auth_algo: headers['paypal-auth-algo'],
            cert_url: headers['paypal-cert-url'],
            transmission_id: headers['paypal-transmission-id'],
            transmission_sig: headers['paypal-transmission-sig'],
            transmission_time: headers['paypal-transmission-time'],
            webhook_id: webhookId,
            webhook_event: body,
        }
 
        try {
            const { data: result } = await firstValueFrom(
                this.httpService.post(
                    `${baseUrl}/v1/notifications/verify-webhook-signature`,
                    verificationBody,
                    {
                        headers: {
                            Authorization: `Bearer ${accessToken}`,
                            'Content-Type': 'application/json',
                        },
                    },
                ),
            )
 
            if (result.verification_status !== 'SUCCESS') {
                throw new Error('PayPal webhook verification failed: Invalid Signature')
            }
 
            return body
        } catch (error) {
            this.logger.error(`Webhook verification error: ${error.message}`)
            throw error
        }
    }
 
    async refundDonation(paymentId: string, config?: PaymentConfig): Promise<any> {
        try {
            const accessToken = await this.getAccessToken(config)
            const { sandbox } = this.getCredentials(config)
            const baseUrl = this.getBaseUrl(sandbox)
 
            // Look up the capture ID associated with this Order ID
            const { data: orderData } = await firstValueFrom(
                this.httpService.get(`${baseUrl}/v2/checkout/orders/${paymentId}`, {
                    headers: { Authorization: `Bearer ${accessToken}` },
                }),
            )
 
            // Find capture ID from purchase units
            const captureId = orderData.purchase_units?.[0]?.payments?.captures?.[0]?.id
            if (!captureId)
                throw new Error('No capture found for this order. Has it been captured?')
 
            const { data } = await firstValueFrom(
                this.httpService.post(
                    `${baseUrl}/v2/payments/captures/${captureId}/refund`,
                    {},
                    {
                        headers: {
                            Authorization: `Bearer ${accessToken}`,
                            'Content-Type': 'application/json',
                        },
                    },
                ),
            )
 
            return data
        } catch (error) {
            this.logger.error(`Error refunding PayPal donation: ${error.message}`)
            throw error
        }
    }
}