Managing Customers
With your custom PaystackCustomer model in place, you can now manage the relationship between your application's users and Paystack customers.
Creating a Paystack Customer
To create a customer on Paystack and link it to your local model, you can use the paystack()->customer()->create() method and then save the result to your database.
php
use App\Models\User;
use App\Models\PaystackCustomer;
$user = User::find(1);
// 1. Create Customer on Paystack
$response = paystack()->customer()->create([
'email' => $user->email,
'first_name' => 'Stephen',
'last_name' => 'Asare',
'phone' => '+233551234567'
]);
if ($response['status']) {
// 2. Save to your local database
$paystackCustomer = PaystackCustomer::create([
'billable_id' => $user->id,
'billable_type' => get_class($user),
'paystack_id' => $response['data']['customer_code'],
'email' => $response['data']['email']
]);
echo "Customer created: " . $paystackCustomer->paystack_id;
}Updating a Customer
If a user updates their profile in your application, you might want to sync those changes to Paystack.
php
$user = User::find(1);
$paystackId = $user->paystackCustomer->paystack_id;
// 1. Update on Paystack
paystack()->customer()->update($paystackId, [
'first_name' => 'New Name',
'phone' => '+233559876543'
]);
// 2. Update local record if necessary (e.g. email changed)
$user->paystackCustomer->update([
'email' => '[email protected]'
]);Fetching Customer Details
You can retrieve the full customer object from Paystack using the ID stored in your database.
php
$user = User::find(1);
if ($user->paystackCustomer) {
$details = paystack()->customer()->fetch($user->paystackCustomer->paystack_id);
// Access Paystack data
// $details['data']['metadata'], etc.
}Use Case: Syncing Existing Users
If you have existing users and want to migrate them to Paystack, you can run a script to create them all.
php
User::chunk(100, function ($users) {
foreach ($users as $user) {
if (!$user->paystackCustomer) {
try {
$response = paystack()->customer()->create(['email' => $user->email]);
$user->paystackCustomer()->create([
'paystack_id' => $response['data']['customer_code'],
'email' => $response['data']['email']
]);
} catch (\Exception $e) {
// Log error
}
}
}
});