Skip to main content

Overview

The CardService class handles creation and deletion of saved payment methods (cards) for MercadoPago customers. Saved cards allow customers to make payments without re-entering card details. Source: src/Services/CardService.php:9
Customer cards require an existing customer. Use CustomerService to create customers first.

Constructor

public function __construct(
    private MercadoPagoClientFactory $clientFactory,
) {}

Dependencies

clientFactory
MercadoPagoClientFactory
required
Factory for creating and configuring MercadoPago SDK clients. Automatically injected by Laravel’s service container.

Methods

create()

Saves a tokenized card to a customer’s account.
public function create(string $customerId, array $payload): mixed
Source: src/Services/CardService.php:15

Parameters

customerId
string
required
The MercadoPago customer ID to associate the card with
payload
array
required
The card configuration data.
The token parameter contains all card information (number, CVV, expiration, holder name) securely tokenized by MercadoPago’s frontend SDK. Never send raw card data to your server.

Returns

response
mixed
MercadoPago card object containing:

Usage

use Fitodac\LaravelMercadoPago\Services\CardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class CustomerCardController
{
    public function store(
        Request $request,
        CardService $cardService
    ): JsonResponse {
        $customerId = auth()->user()->mercadopago_customer_id;
        
        $card = $cardService->create($customerId, [
            'token' => $request->card_token,
        ]);
        
        return response()->json([
            'card_id' => data_get($card, 'id'),
            'last_four' => data_get($card, 'last_four_digits'),
            'payment_method' => data_get($card, 'payment_method.id'),
        ], 201);
    }
}

delete()

Removes a saved card from a customer’s account.
public function delete(string $customerId, string $cardId): mixed
Source: src/Services/CardService.php:29

Parameters

customerId
string
required
The MercadoPago customer ID that owns the card
cardId
string
required
The card ID to delete (obtained from card creation)

Returns

response
mixed
Deletion confirmation response from MercadoPago API

Usage

use Fitodac\LaravelMercadoPago\Services\CardService;
use Illuminate\Http\JsonResponse;

public function destroy(
    string $cardId,
    CardService $cardService
): JsonResponse {
    $customerId = auth()->user()->mercadopago_customer_id;
    
    $cardService->delete($customerId, $cardId);
    
    return response()->json([
        'message' => 'Card removed successfully',
    ]);
}

Common Patterns

Save card during payment

Allow customers to save their card while making a payment:
use Fitodac\LaravelMercadoPago\Services\PaymentService;
use Fitodac\LaravelMercadoPago\Services\CardService;

// Process payment
$payment = app(PaymentService::class)->create([
    'transaction_amount' => 100,
    'token' => $cardToken,
    'description' => 'Premium subscription',
    'installments' => 1,
    'payment_method_id' => 'visa',
    'payer' => ['email' => '[email protected]'],
]);

// If approved and customer wants to save
if (data_get($payment, 'status') === 'approved' && $saveCard) {
    $customerId = auth()->user()->mercadopago_customer_id;
    
    app(CardService::class)->create($customerId, [
        'token' => $cardToken,
    ]);
}

List customer cards

While this service doesn’t provide a list method, you can retrieve the customer to see their cards:
use Fitodac\LaravelMercadoPago\Services\CustomerService;

$customer = app(CustomerService::class)->get($customerId);
$cards = data_get($customer, 'cards', []);

foreach ($cards as $card) {
    echo "Card ending in {$card['last_four_digits']}\n";
}

Sync cards to database

Maintain a local copy of customer cards:
use Fitodac\LaravelMercadoPago\Services\CardService;

$card = app(CardService::class)->create($customerId, [
    'token' => $cardToken,
]);

// Store in local database
auth()->user()->paymentMethods()->create([
    'mercadopago_card_id' => data_get($card, 'id'),
    'last_four' => data_get($card, 'last_four_digits'),
    'brand' => data_get($card, 'payment_method.id'),
    'expiration_month' => data_get($card, 'expiration_month'),
    'expiration_year' => data_get($card, 'expiration_year'),
]);

Security Considerations

Never store or transmit raw card data (numbers, CVV, expiration dates) through your server. Always use MercadoPago.js to tokenize cards client-side before sending to your backend.

PCI Compliance

By using card tokens:
  • Raw card data never touches your servers
  • You maintain PCI DSS compliance
  • MercadoPago handles secure card storage
  • Your scope of PCI compliance is minimized

Error Handling

MercadoPagoConfigurationException
exception
Thrown when:
  • MercadoPago SDK is not installed
  • Required SDK classes are not found
  • SDK methods are unavailable
MercadoPagoException
exception
Thrown by the MercadoPago SDK for API errors:
  • Invalid credentials
  • Invalid card token
  • Customer not found
  • Card not found (for delete() method)
  • Duplicate card
  • Network errors

Error handling example

use Fitodac\LaravelMercadoPago\Exceptions\MercadoPagoConfigurationException;

try {
    $card = $cardService->create($customerId, $payload);
} catch (MercadoPagoConfigurationException $e) {
    return response()->json(['error' => 'Service misconfigured'], 500);
} catch (\Exception $e) {
    if (str_contains($e->getMessage(), 'customer not found')) {
        return response()->json(['error' => 'Customer not found'], 404);
    }
    
    \Log::error('Card creation failed', [
        'customer_id' => $customerId,
        'error' => $e->getMessage(),
    ]);
    
    return response()->json(['error' => 'Card creation failed'], 500);
}

CustomerService

Create and manage customers

PaymentService

Process payments with saved cards

Additional Resources

Managing Customers Guide

Complete guide including card management

MercadoPago API Documentation

Official cards API reference

Build docs developers (and LLMs) love