Skip to content

Payment Methods

Complete reference for the PaymentMethod model, configuration, and payment management in Shopper.

Payment methods represent the ways customers can pay for their orders. Shopper provides a flexible system to manage multiple payment providers, each with its own driver, description, and customer-facing instructions.

Model

The model used is Shopper\Core\Models\PaymentMethod. It implements Shopper\Core\Models\Contracts\PaymentMethod and uses the HasSlug and HasZones traits. The model is not configurable via config/shopper/models.php.

Database Schema

PaymentMethod Table

ColumnTypeNullableDefaultDescription
idbigintnoautoPrimary key
titlestringno-Payment method name
slugstringyesnullURL-friendly identifier (unique)
logostringyesnullNot read by Shopper: the logo comes from the driver, see Logo Handling
link_urlstringyesnullPayment provider website or documentation URL
descriptiontextyesnullDescription displayed to customers when choosing a payment method
instructionstextyesnullInstructions displayed to customers after placing an order
is_enabledbooleannofalseWhether the method is active. Methods added in the admin start disabled
driverstringyesnullPayment driver code (manual, stripe or a custom driver), added by shopper/payment. null is handled as manual
metadatajsonbyesnullCustom data. The model does not cast it, so it reads back as a JSON string
created_attimestampyesnullCreation timestamp
updated_attimestampyesnullLast update timestamp

The admin fills slug from the title. In code, the slug is not generated: pass it yourself. The HasSlug trait turns the value into a slug and appends -1, -2 when it is already taken.

Contract

The PaymentMethod contract defines the interface that all payment method models must implement:

namespace Shopper\Core\Models\Contracts;

use Illuminate\Database\Eloquent\Relations\MorphToMany;

interface PaymentMethod
{
    public function zones(): MorphToMany;
}

Payment methods use zones to control availability by geographic region. A payment method can be assigned to multiple zones, and a zone can have multiple payment methods.

The driver column connects a payment method to a registered payment driver. manual is built in, stripe comes with the shopper/stripe package, and you add others with Payment::extend(). A null driver resolves to manual, and a code that no driver is registered under makes Payment::driver() throw an InvalidArgumentException. When the PaymentProcessingService processes a payment, it uses this value to resolve the correct driver. See Payments for driver registration and the full payment lifecycle.

Relationships

Zones

Payment methods can be scoped to specific geographic zones using the HasZones trait:

$paymentMethod->zones;
$paymentMethod->zones()->attach([$zoneId1, $zoneId2]);
$paymentMethod->zones()->detach($zoneId);

In the admin, payment methods are assigned to a zone from the zone form. From the zone side, use $zone->paymentMethods (see Zones).

Orders

Orders reference payment methods via the payment_method_id foreign key:

$order->paymentMethod;
Order::query()
    ->where('payment_method_id', $paymentMethod->id)
    ->get();

The foreign key is nullable: deleting a payment method keeps its orders and sets their payment_method_id to null.

Query Scopes

PaymentMethod::query()->enabled()->get();

Logo Handling

A payment method shows the logo of its driver. The logo() method returns the URL the driver provides (the manual and stripe drivers ship one), or null when the driver has none or shopper/payment is not installed. PaymentProcessingService::getLogoUrl() returns the same value:

use Shopper\Payment\Services\PaymentProcessingService;

$paymentMethod->logo(); // Driver logo URL or null

$service = resolve(PaymentProcessingService::class);
$service->getLogoUrl($paymentMethod); // Same as $paymentMethod->logo()

The logo column is neither filled by the admin nor read by logo(). To show a logo for your own driver, return its URL from the driver's logo() method (see Custom Drivers).

Creating Payment Methods

Basic Payment Method

The stripe driver needs the shopper/stripe package (see Available Drivers). Leave out is_enabled and the method is created disabled.

use Shopper\Core\Models\PaymentMethod;

$paymentMethod = PaymentMethod::query()->create([
    'title' => 'Credit Card',
    'slug' => 'credit-card',
    'driver' => 'stripe',
    'link_url' => 'https://stripe.com',
    'description' => 'Pay securely with your credit or debit card.',
    'instructions' => 'Your card will be charged immediately upon order confirmation.',
    'is_enabled' => true,
]);

Cash on Delivery

$cod = PaymentMethod::query()->create([
    'title' => 'Cash on Delivery',
    'slug' => 'cash-on-delivery',
    'driver' => 'manual',
    'description' => 'Pay with cash when your order is delivered.',
    'instructions' => 'Please have the exact amount ready for the delivery driver.',
    'is_enabled' => true,
]);

Bank Transfer

$bankTransfer = PaymentMethod::query()->create([
    'title' => 'Bank Transfer',
    'slug' => 'bank-transfer',
    'driver' => 'manual',
    'description' => 'Pay via direct bank transfer.',
    'instructions' => 'Please transfer the total amount to the following account: IBAN XX00 0000 0000 0000. Use your order number as the payment reference.',
    'is_enabled' => true,
]);

Zone-Scoped Payment Method

$mobileMoney = PaymentMethod::query()->create([
    'title' => 'Mobile Money',
    'slug' => 'mobile-money',
    'link_url' => 'https://notchpay.co',
    'description' => 'Pay with your mobile money wallet.',
    'is_enabled' => true,
]);

$mobileMoney->zones()->attach([$africaZoneId]);

Retrieving Payment Methods

$methods = PaymentMethod::query()->enabled()->get();

Find by slug:

$method = PaymentMethod::query()
    ->where('slug', 'credit-card')
    ->first();

PaymentMethod::findBySlug('credit-card') from the HasSlug trait does the same, but throws a ModelNotFoundException when no method matches.

Payment methods available in a specific zone:

$methods = PaymentMethod::query()
    ->enabled()
    ->whereHas('zones', fn ($q) => $q->where('zone_id', $zoneId))
    ->get();

PaymentProcessingService::getMethodsForZone() returns the zone's enabled methods whose driver is configured. It only returns methods attached to the zone (see Payments):

use Shopper\Payment\Services\PaymentProcessingService;

$methods = resolve(PaymentProcessingService::class)->getMethodsForZone($zone);

Payment methods with no zone restriction (available everywhere):

$globalMethods = PaymentMethod::query()
    ->enabled()
    ->whereDoesntHave('zones')
    ->get();

Working with Orders

When creating an order, associate it with the selected payment method:

use Shopper\Core\Models\Order;

$order = Order::query()->create([
    'number' => $orderNumber,
    'customer_id' => $customerId,
    'payment_method_id' => $paymentMethod->id,
    // ... other order fields
]);

$order->paymentMethod->title;
$order->paymentMethod->instructions;

CreateOrderFromCartAction does not set payment_method_id. Set it on the order the action returns (see Order Conversion):

$order->update(['payment_method_id' => $paymentMethod->id]);

Storefront Example

Checkout Payment Selection

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Shopper\Cart\Facades\Cart;
use Shopper\Core\Models\PaymentMethod;
use Shopper\Core\Models\Zone;

class CheckoutController extends Controller
{
    public function showPayment()
    {
        $zone = $this->getCustomerZone();

        $paymentMethods = PaymentMethod::query()
            ->enabled()
            ->where(function ($query) use ($zone): void {
                $query->whereHas('zones', fn ($q) => $q->where('zone_id', $zone?->id))
                    ->orWhereDoesntHave('zones');
            })
            ->get();

        return view('checkout.payment', compact('paymentMethods'));
    }

    public function storePayment(Request $request)
    {
        $paymentMethod = PaymentMethod::query()->enabled()->findOrFail(
            $request->input('payment_method_id')
        );

        session()->put('checkout.payment_method_id', $paymentMethod->id);

        return redirect()->route('checkout.review');
    }

    private function getCustomerZone(): ?Zone
    {
        $countryId = Cart::current()?->shippingAddress()?->country_id;

        if (! $countryId) {
            return null;
        }

        return Zone::query()
            ->enabled()
            ->whereHas('countries', fn ($q) => $q->where('id', $countryId))
            ->first();
    }
}

In this example, payment methods without any zone are shown to all customers regardless of their location. getMethodsForZone() does not follow this rule: it only returns methods attached to the zone.

Use Cases

Any of these can be a payment method. A method that charges online needs a driver: Shopper ships manual and stripe, and you write custom drivers for the others.

Payment MethodDescription
Credit CardOnline card payments via Stripe, PayPal, etc.
Bank TransferDirect bank wire transfer
Cash on DeliveryPayment at delivery time
Mobile MoneyMobile wallet payments (M-Pesa, Orange Money, etc.)
PayPalPayPal account or guest checkout
CryptocurrencyBitcoin, Ethereum, etc.
ScenarioImplementation
Single payment providerCreate one enabled payment method
Region-specific methodsUse zones to restrict availability
Offline paymentsUse instructions field for post-order guidance
Gateway documentationUse link_url to reference provider docs
Display at checkoutQuery enabled methods filtered by customer zone

Last updated on

Edit on GitHub