Payment gateways are pretty small, but they can be smaller.

Examples from the onsite example:

    $test = $this->getMode() == 'test';
    $payment->setTest($test);

This can be done in Payment::preSave() which has access to the payment gateway. Especially since we also need to replace the test boolean with a mode property that is mapped 1-1 to the gateway.

    if ($payment->getState()->value != 'authorization') {
      throw new \InvalidArgumentException('Only payments in the "authorization" state can be captured.');
    }

The most common validation is ensuring that the passed payment has the right state.
So, we add an assertPaymentState($payment, array $states) to the gateway base class and make that a one liner.

    if (empty($payment_method)) {
      throw new \InvalidArgumentException('The provided payment has no payment method referenced.');
    }
    if (\Drupal::time()->getRequestTime() >= $payment_method->getExpiresTime()) {
      throw new HardDeclineException('The provided payment method has expired');
    }

Same as above. $this->assertPaymentMethod().

    // Validate the requested amount.
    $balance = $payment->getBalance();
    if ($amount->greaterThan($balance)) {
      throw new InvalidRequestException(sprintf("Can't refund more than %s.", $balance->__toString()));
    }

$this->assertRefundAmount($payment, $refund_amount).

Comments

bojanz created an issue. See original summary.

  • bojanz committed f720b77 on 8.x-2.x
    Issue #2883597 by bojanz: Reduce payment gateway boilerplate
    
bojanz’s picture

Status: Active » Fixed

Done.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.