Class: Payment::Gateways::Paypal

Inherits:
BasePaymentGateway
  • Object
show all
Defined in:
app/services/payment/gateways/paypal.rb

Overview

PayPal gateway strategy. Drives Orders API v2 authorize/capture/void
/refund and the PayPal vault flow used for repeat customers, and
bridges PayPal events into local Payment state and Receipts.

Defined Under Namespace

Classes: PaypalSetupResult, ReceiptResult, Result

Instance Method Summary collapse

Constructor Details

#initialize(payment = nil, _delivery = nil) ⇒ Paypal

Returns a new instance of Paypal.



17
18
19
# File 'app/services/payment/gateways/paypal.rb', line 17

def initialize(payment = nil, _delivery = nil)
  @payment = payment
end

Instance Method Details

#authorizeObject

Called after the PayPal JS SDK has created and approved an order on the client,
and the server has authorized it via Orders API v2. The payment's
paypal_transaction_id holds the PayPal authorization ID.



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
# File 'app/services/payment/gateways/paypal.rb', line 24

def authorize
  auth_id = @payment.paypal_transaction_id
  response = Payment::Apis::Paypal.get_authorization(auth_id)
  tx = OrderTransaction.record_paypal(
    action: 'authorization',
    paypal_response: response,
    amount_cents: (@payment.amount * 100).to_i
  )
  @payment.transactions.push(tx)

  if tx.success?
    @payment.authorization_code = auth_id
    @payment.capture_before = Time.current + Payment::PAYPAL_HONOR_PERIOD
    store_authorization_expiry(response)
    sync_seller_protection_from_auth(response)
    @payment.payment_authorized!
    success = true
  else
    @payment.last_response = tx.message
    @payment.error_codes = response['details']&.first&.dig('issue') rescue nil
    success = false
    @payment.transaction_declined!
  end
  @payment.save!
  Result.new(success: success, message: tx.message)
end

#authorize_from_vault(vault_token_id) ⇒ Payment::Gateways::Paypal::Result

Create a PayPal Orders API v2 order against a stored vault token,
authorize it, and reflect the result on the local Payment. Used
by repeat-customer "pay with PayPal on file" flows.

Parameters:

  • vault_token_id (String)

Returns:



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
# File 'app/services/payment/gateways/paypal.rb', line 57

def authorize_from_vault(vault_token_id)
  order = @payment.order

  response = Payment::Apis::Paypal.create_order_from_vault(
    vault_id: vault_token_id,
    amount: @payment.amount,
    currency: @payment.currency,
    intent: 'AUTHORIZE',
    description: "Order #{order&.reference_number}",
    metadata: { order_id: order&.id, invoice_id: order&.reference_number }
  )

  unless response['id'].present?
    tx = OrderTransaction.new(
      action: 'authorization', amount: (@payment.amount * 100).to_i, success: false,
      message: "PayPal vault order creation failed: #{response['message'] || response.to_json}",
      params: response, test: !Rails.env.production?
    )
    @payment.transactions.push(tx)
    @payment.transaction_declined!
    @payment.save!
    return Result.new(success: false, message: tx.message)
  end

  paypal_order_id = response['id']

  authorization = response.dig('purchase_units', 0, 'payments', 'authorizations', 0)
  auth_response = response

  unless authorization
    auth_response = Payment::Apis::Paypal.authorize_order(paypal_order_id)
    authorization = auth_response.dig('purchase_units', 0, 'payments', 'authorizations', 0)
  end

  payer = auth_response['payer']

  unless authorization && auth_response['_http_success']
    tx = OrderTransaction.new(
      action: 'authorization', amount: (@payment.amount * 100).to_i, success: false,
      message: "PayPal vault authorization failed: #{auth_response['message'] || auth_response.to_json}",
      params: auth_response, test: !Rails.env.production?
    )
    @payment.transactions.push(tx)
    @payment.transaction_declined!
    @payment.save!
    return Result.new(success: false, message: tx.message)
  end

  auth_id = authorization['id']

  auth_for_recording = authorization.merge(
    '_http_success' => true,
    '_http_status' => auth_response['_http_status']
  )
  tx = OrderTransaction.record_paypal(
    action: 'authorization', paypal_response: auth_for_recording,
    amount_cents: (@payment.amount * 100).to_i
  )
  @payment.transactions.push(tx)

  if tx.success?
    @payment.paypal_transaction_id = auth_id
    @payment.authorization_code = auth_id
    @payment.capture_before = Time.current + Payment::PAYPAL_HONOR_PERIOD
    @payment. = (@payment. || {}).merge(
      'paypal_order_id' => paypal_order_id,
      'vault_authorized' => true,
      'payer_id' => payer&.dig('payer_id'),
      'payer_name' => [payer&.dig('name', 'given_name'), payer&.dig('name', 'surname')].compact.join(' ').presence
    ).compact
    store_authorization_expiry(authorization)
    sync_seller_protection_from_auth(authorization)
    @payment.payment_authorized!
    @payment.save!
    Result.new(success: true)
  else
    @payment.last_response = tx.message
    @payment.transaction_declined!
    @payment.save!
    Result.new(success: false, message: tx.message)
  end
end

#capture(capture_amount, options = {}) ⇒ Payment::Gateways::Paypal::Result

Capture funds against this PayPal authorization. Detects external
captures (already captured on PayPal dashboard), respects multicapture
via StrategyResolver#capture_options, and falls back to a
smaller capture amount when an over-capture exceeds the allowed
115% headroom on a shared authorization.

Parameters:

  • capture_amount (BigDecimal, Numeric)

    in dollars

  • options (Hash) (defaults to: {})

    forwarded to PayPal (:final_capture, :order_id)

Returns:



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'app/services/payment/gateways/paypal.rb', line 208

def capture(capture_amount, options = {})
  if @payment.captured_on_paypal?
    auth_response = Payment::Apis::Paypal.get_authorization(@payment.authorization_code)
    capture_id = extract_capture_id_from_auth(auth_response) || @payment.authorization_code
    funds_captured = true
    tx = OrderTransaction.new(
      action: 'capture',
      amount: capture_amount * 100,
      success: true,
      reference: capture_id,
      message: 'Already captured on PayPal',
      params: {},
      test: !Rails.env.production?
    )
    @payment.transactions.push(tx)
    return finish_capture(capture_amount, tx, funds_captured, options)
  end

  resolver = Payment::StrategyResolver.new(@payment)
  order = @payment.order
  capture_opts = order ? resolver.capture_options(order: order) : Payment::StrategyResolver::CaptureOptions.new
  final_capture = options.key?(:final_capture) ? options[:final_capture] : capture_opts.final_capture
  order_ref = order&.reference_number

  tx, funds_captured = attempt_paypal_capture(capture_amount, final_capture, order_ref, options)
  @payment.transactions.push(tx)

  if !funds_captured && @payment.shared_paypal_auth? && @payment.paypal_shared_auth_total
    fallback = paypal_fallback_capture_amount(capture_amount)
    if fallback && fallback > 0 && fallback < capture_amount
      logger.info("#{Time.current}: PayPal over-capture failed for payment #{@payment.id} " \
                   "(tried #{capture_amount}, auth limit allows #{fallback}). Retrying at #{fallback}.")
      tx2, funds_captured = attempt_paypal_capture(fallback, final_capture, order_ref, options)
      @payment.transactions.push(tx2)
      if funds_captured
        capture_amount = fallback
        tx = tx2
      end
    end
  end

  finish_capture(capture_amount, tx, funds_captured, options)
end

#create_receipt(invoice, amount, balance) ⇒ Payment::Gateways::Paypal::ReceiptResult

Build the Receipt for a successful PayPal capture and stamp the
auth code on it. Falls back to attaching the receipt to the order
when there is no invoice yet (e.g. partial captures during checkout).

Parameters:

  • invoice (Invoice, nil)
  • amount (BigDecimal, Numeric)
  • balance (BigDecimal, nil)

    retained for API parity

Returns:



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'app/services/payment/gateways/paypal.rb', line 354

def create_receipt(invoice, amount, balance)
  resource = invoice
  resource ||= @payment.order

  new_receipt = @payment.receipts.new(
    company: resource.company,
    customer: resource.customer,
    category: 'PayPal',
    amount: amount,
    reference: @payment.reference,
    card_type: nil,
    currency: @payment.currency,
    payment: @payment,
    bank_account: resource.company.,
    gl_date: Date.current,
    receipt_date: Date.current,
    email: @payment.email,
    remark: @payment.authorization_code.present? ? "Auth Code: #{@payment.authorization_code}" : nil
  )

  if resource.is_a?(Invoice)
    new_receipt.receipt_details << ReceiptDetail.new(
      category: 'Invoice', invoice: resource, amount: amount, gl_date: Date.current
    )
  end

  begin
    new_receipt.save!
    Rails.logger.info("#{Time.current}: Created new receipt id: #{new_receipt.id}")
    success = true
  rescue StandardError => exc
    success = false
    report_exception exc, payment_id: @payment.id, message: "Unable to create new receipt for PayPal payment, captured but no receipt"
  end
  ReceiptResult.new(success: success, receipt: new_receipt)
end

#reauthorize(amount, options = {}) ⇒ Payment::Gateways::Paypal::Result

Re-authorize an expiring PayPal authorization for amount. Updates
the local authorization_code and capture_before when PayPal
returns a fresh auth id.

Parameters:

  • amount (BigDecimal, Numeric)
  • options (Hash) (defaults to: {})

    reserved

Returns:



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
# File 'app/services/payment/gateways/paypal.rb', line 147

def reauthorize(amount, options = {})
  response = Payment::Apis::Paypal.reauthorize_authorization(
    @payment.authorization_code,
    amount: amount,
    currency: @payment.currency
  )
  tx = OrderTransaction.record_paypal(
    action: 'reauthorization',
    paypal_response: response,
    amount_cents: (amount * 100).to_i
  )
  @payment.transactions.push(tx)

  if tx.success?
    new_auth_id = response.dig('id')
    @payment.authorization_code = new_auth_id if new_auth_id.present?
    @payment.capture_before = Time.current + Payment::PAYPAL_HONOR_PERIOD
    store_authorization_expiry(response)
    Rails.logger.info("#{Time.current}: PayPal reauthorization of #{amount} successful for payment id: #{@payment.id}")
  else
    @payment.last_response = tx.message
  end
  @payment.save!
  Result.new(success: tx.success?, message: tx.message)
end

#refund(refund_amount, credit_memo) ⇒ Payment::Gateways::Paypal::Result

Refund a previously captured PayPal payment against credit_memo,
creating the matching Receipt for the negative amount. Records a
refund transaction even if the receipt creation fails so the
PayPal-side state stays consistent.

Parameters:

  • refund_amount (BigDecimal, Numeric)
  • credit_memo (CreditMemo)

Returns:



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'app/services/payment/gateways/paypal.rb', line 290

def refund(refund_amount, credit_memo)
  capture_tx = @payment.transactions.where(action: 'capture', success: true).last
  capture_id = capture_tx&.reference

  unless capture_id.present?
    return Result.new(success: false, message: 'No capture transaction found to refund')
  end

  response = Payment::Apis::Paypal.refund_capture(
    capture_id,
    amount: refund_amount,
    currency: @payment.currency,
    invoice_id: credit_memo&.reference_number,
    note_to_payer: "Refund for Order #{@payment.order&.reference_number} - WarmlyYours"
  )
  tx = OrderTransaction.record_paypal(
    action: 'refund',
    paypal_response: response,
    amount_cents: (refund_amount * 100).to_i
  )
  @payment.transactions.push(tx)

  receipt_ok = false
  if tx.success?
    Rails.logger.info("#{Time.current}: PayPal Refund of Payment ID #{@payment.id} Amount #{refund_amount} succeeded")
    @payment.payment_refunded!
     = @payment.invoice&.company&. || credit_memo.company.
    new_receipt = Receipt.new(
      company: credit_memo.company,
      customer: credit_memo.customer,
      category: 'PayPal',
      amount: -refund_amount,
      reference: @payment.reference,
      card_type: @payment.card_type,
      currency: @payment.currency,
      payment: @payment,
      bank_account: ,
      gl_date: Date.current,
      receipt_date: Date.current
    )
    new_receipt.receipt_details << ReceiptDetail.new(
      category: 'Credit Memo', credit_memo: credit_memo, amount: -refund_amount, gl_date: Date.current
    )
    begin
      new_receipt.save!
      receipt_ok = true
      Rails.logger.info("#{Time.current}: Created new receipt id: #{new_receipt.id}")
    rescue StandardError => exc
      report_exception exc, payment_id: @payment.id, message: "Unable to create new receipt for PayPal payment"
    end
  else
    Rails.logger.info("#{Time.current}: PayPal Refund of Payment ID #{@payment.id} Amount #{refund_amount} failed")
  end
  Result.new(success: (tx.success? && receipt_ok))
end

#register_shared_authorization(authorization_code, amount_cents:) ⇒ Payment::Gateways::Paypal::Result

Attach this Payment to an existing PayPal authorization (the
split-order/multicapture pattern) without making a fresh API call.
Records a synthetic authorization transaction so the audit trail
still ties the dollars back.

Parameters:

  • authorization_code (String)

    PayPal authorization id to share

  • amount_cents (Integer)

Returns:



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'app/services/payment/gateways/paypal.rb', line 181

def register_shared_authorization(authorization_code, amount_cents:)
  tx = OrderTransaction.new(
    action: 'authorization',
    amount: amount_cents,
    success: true,
    reference: authorization_code,
    message: 'Shared PayPal authorization (split order)',
    params: {},
    test: !Rails.env.production?
  )
  @payment.transactions.push(tx)
  @payment.payment_authorized!
  Result.new(success: true)
rescue StandardError => e
  Rails.logger.error("Failed to register shared PayPal auth for payment #{@payment.id}: #{e.message}")
  Result.new(success: false, message: e.message)
end

#void(report_fraud = false) ⇒ Payment::Gateways::Paypal::Result

Void the active PayPal authorization. Records a void transaction
whether the API call succeeded or not so the trail is preserved.

Parameters:

  • report_fraud (Boolean) (defaults to: false)

    retained for parity with CC gateway

Returns:



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'app/services/payment/gateways/paypal.rb', line 257

def void(report_fraud = false)
  return Result.new(success: false) unless @payment.authorized?

  response = Payment::Apis::Paypal.void_authorization(@payment.authorization_code)
  void_success = response[:success]

  tx = OrderTransaction.new(
    action: 'void',
    success: void_success,
    reference: @payment.authorization_code,
    message: void_success ? 'voided' : "void failed (HTTP #{response[:status]})",
    params: response,
    test: !Rails.env.production?
  )
  @payment.transactions.push(tx)

  if void_success
    Rails.logger.info("#{Time.current}: PayPal Void of Auth ID #{@payment.id} succeeded")
    @payment.payment_voided!
  else
    Rails.logger.info("#{Time.current}: PayPal Void of Auth ID #{@payment.id} failed")
  end
  Result.new(success: void_success, message: tx.message)
end