Class: Payment::Gateways::Paypal

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

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.



14
15
16
# File 'app/services/payment/gateways/paypal.rb', line 14

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.



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

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) ⇒ Object



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

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 = {}) ⇒ Object



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
212
213
214
215
216
217
# File 'app/services/payment/gateways/paypal.rb', line 175

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) ⇒ Object



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

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 = {}) ⇒ Object



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

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) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'app/services/payment/gateways/paypal.rb', line 244

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:) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'app/services/payment/gateways/paypal.rb', line 157

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) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'app/services/payment/gateways/paypal.rb', line 219

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