PHP code example of kitelab-dev / byl-laravel
1. Go to this page and download the library: Download kitelab-dev/byl-laravel library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kitelab-dev / byl-laravel example snippets
use Byl\Laravel\Facades\Byl;
$checkout = Byl::checkouts()->builder()
->successUrl(route('purchase.success'))
->addPrice('starter_monthly')
->customer($customer->byl_customer_id)
->create();
return redirect()->away($checkout->url);
use Byl\Laravel\Facades\Byl;
$invoice = Byl::invoices()->create([
'amount' => 25000,
'description' => 'Гишүүнчлэлийн төлбөр',
'auto_advance' => true, // draft-аас шууд open болгоно
]);
$invoice->id; // 5708
$invoice->number; // "DEMO-0011"
$invoice->status; // Byl\Laravel\Enums\InvoiceStatus::Open
$invoice->url; // төлбөрийн хуудасны хаяг
$invoice->dueDate; // Carbon
$invoice->isPaid(); // false
// Хураангуй хэлбэр
$invoice = Byl::invoices()->createFor(25000, 'Гишүүнчлэлийн төлбөр');
Byl::invoices()->find(5708);
Byl::invoices()->void(5708); // төлөгдөөгүй нэхэмжлэхийг хүчингүй болгох
Byl::invoices()->delete(5708);
public function pay(Order $order)
{
return Byl::invoices()->createFor($order->total, "Захиалга #{$order->id}");
}
$checkout = Byl::checkouts()->builder()
->successUrl(route('purchase.success'))
->cancelUrl(route('cart'))
->addPriceData(15000, 'Гутал', quantity: 2) // шууд үнэ
->addPriceId(3) // Byl дээрх үнийн ID
->addPrice('starter_monthly') // lookup key
->collectPhoneNumber()
->collectDeliveryAddress()
->allowPromotionCodes() // хөнгөлөлтийн кодын талбар
->discount(5400, 'Хямдрал') // нийт дүнгээс хөнгөлөх
->clientReferenceId("order_{$order->id}")
->create();
return redirect()->away($checkout->url);
$checkout = Byl::checkouts()->create([
'success_url' => route('purchase.success'),
'items' => [
['price' => 'starter_monthly', 'quantity' => 1],
],
]);
$checkout = Byl::checkouts()->find(13338);
$checkout->status; // CheckoutStatus::Open|Pending|Complete|Expired
$checkout->amountTotal;
$checkout->items; // Collection<CheckoutItem>
$checkout->couponCodes; // Collection<CouponCode>
$checkout->discountTotal();
$customer = Byl::customers()->upsert([
'email' => $user->email,
'name' => $user->name,
'client_reference_id' => (string) $user->id,
]);
$customer->id; // checkout-д дамжуулах customer_id
// Лавлах — хариунд эрхтэй захиалгууд хамт ирнэ
$customer = Byl::customers()->find(12);
$customer = Byl::customers()->findByClientReferenceId((string) $user->id);
$customer = Byl::customers()->findByClientReferenceIdOrNull((string) $user->id); // олдоогүй бол null
$customer->isSubscribed(); // эрхтэй захиалга байгаа эсэх
$customer->subscriptionForLookupKey('starter_monthly');
$customer->subscriptionForProduct(7);
Byl::checkouts()->builder()
->customer($customer->id)
->addPrice('starter_monthly')
->successUrl(route('subscribe.success'))
->create();
Byl::checkouts()->builder()
->customer($customer->id)
->subscription($subscriptionId)
->addPrice('growth_monthly') // өөр үнэ → багц солилт, ижил үнэ → сунгалт
->create();
$subscription = Byl::subscriptions()->find(4);
$subscription->status; // SubscriptionStatus::Trialing|Active|PastDue|Canceled
$subscription->isEntitled(); // canceled-аас бусад бүх төлөв → true
$subscription->currentPeriodEnd; // эрхийн дуусах хугацаа (Carbon)
$subscription->daysUntilPeriodEnd();
$subscription->cancelRequested(); // цуцлалт хүссэн ч мөчлөг дуусаагүй
// Жагсаалт (хуудаслалттай). Filter: customer_id, price_id, price, status
$page = Byl::subscriptions()->list(['status' => 'active']);
$page = Byl::subscriptions()->list(['price' => 'starter_monthly']);
$page = Byl::subscriptions()->forCustomer(12, SubscriptionStatus::Active);
foreach ($page as $subscription) { /* ... */ }
$page->hasMorePages();
// Бүх хуудсыг lazy байдлаар
Byl::subscriptions()->all(['status' => 'active'])->each(fn ($subscription) => /* ... */);
// Туршилт (төлбөргүй) — 1–365 хоног. Үнийн ID эсвэл lookup key
Byl::subscriptions()->startTrial(customerId: 12, price: 3, trialDays: 14);
Byl::subscriptions()->startTrial(customerId: 12, price: 'starter_monthly', trialDays: 14);
// Цуцлах / буцаах (мөчлөгийн төгсгөлд хэрэгжинэ)
Byl::subscriptions()->cancel(4);
Byl::subscriptions()->resume(4);
use Byl\Laravel\Billing\Billable;
class User extends Authenticatable
{
use Billable;
}
$user->subscribed(); // эрхтэй эсэх (trialing/active/past_due)
$user->subscribed('starter_monthly'); // тодорхой багц дээр
$user->subscribedToPrice(3);
$user->subscribedToProduct(7);
$user->onTrial();
$user->onGracePeriod(); // цуцлалт хүссэн ч мөчлөг дуусаагүй
$user->pastDue();
$user->subscriptionEnded(); // эрх нь дууссан
$subscription = $user->bylSubscription(); // Eloquent модель
$subscription->current_period_end; // Carbon
$subscription->daysUntilPeriodEnd();
$user->bylSubscriptions; // бүх захиалга (relation)
Route::get('/dashboard', ...)->middleware('byl.subscribed');
Route::get('/pro', ...)->middleware('byl.subscribed:growth_monthly');
// Recurring checkout — төлөгдмөгц subscription үүсч webhook ирнэ
return $user->newSubscription('starter_monthly')
->successUrl(route('subscribe.success'))
->allowPromotionCodes()
->checkout(); // CreatedCheckout (шууд return хийвэл redirect)
// Хэд хэдэн мөчлөгийг нэг дор
$user->newSubscription('starter_monthly')->cycles(3)->checkout();
// Төлбөргүй туршилт — lookup key эсвэл үнийн ID
$user->newSubscription('starter_monthly')->startTrial(14);
$subscription = $user->bylSubscription();
return $subscription->renewCheckout(3); // 3 мөчлөгөөр сунгах
return $subscription->swapCheckout('growth_monthly'); // багц солих (кредит хасагдана)
$subscription->cancel(); // мөчлөгийн төгсгөлд, локал төлөв шууд шинэчлэгдэнэ
$subscription->resume();
$subscription->syncFromByl(); // Byl дээрх төлөвөөр дахин таарах
$user->syncBylSubscriptions(); // Byl дээрх захиалгуудыг локал хүснэгтэд татах
$user->asBylCustomer(); // API-аас харилцагчийн мэдээлэл (эрхтэй захиалгын хамт)
$user->syncBylCustomerDetails(); // нэр/и-мэйл/утсаа Byl дээр шинэчлэх
// config/byl.php
'billable' => ['client_reference_column' => 'uuid'],
// эсвэл бүрэн өөрийн логик (AppServiceProvider::boot)
Byl::resolveBillableUsing(fn (string $reference) => Team::where('slug', $reference)->first());
Route::get('/billing', function () {
$customer = Byl::customers()->findByClientReferenceId((string) auth()->id());
return Byl::billingPortal()->createSession($customer->id); // portal руу redirect
});
$session = Byl::billingPortal()->createSession($customer->id);
$session->url;
$session->expiresAt;
// app/Providers/AppServiceProvider.php
use Byl\Laravel\Events\CheckoutCompleted;
use Byl\Laravel\Events\SubscriptionCanceled;
use Illuminate\Support\Facades\Event;
Event::listen(function (CheckoutCompleted $event) {
$checkout = $event->checkout;
Order::where('id', $checkout->clientReferenceId)->update(['paid_at' => now()]);
});
Event::listen(function (SubscriptionCanceled $event) {
User::where('id', $event->subscription->customer?->clientReferenceId)
->update(['plan' => null]); // эрхийг энэ үед хаана
});
use Byl\Laravel\Events\PaymentAwaitingVerification;
Event::listen(function (PaymentAwaitingVerification $event) {
$payment = $event->payment;
$payment->status; // PaymentStatus::Pending
$payment->reference; // '482913' — шилжүүлгийн лавлагаа
$payment->amount; // 150000.0
$payment->bankName;
$payment->accountNumber;
$payment->claimedAt; // харилцагч мэдэгдсэн хугацаа
$payment->expiresAt;
$payment->payableType(); // 'checkout' | 'invoice'
$payment->payableId();
$payment->payableUrl();
Admin::notify("Шилжүүлэг баталгаажуулна уу: {$payment->reference}");
});
// config/byl.php
'webhook' => [
'route' => [
'enabled' => true,
'path' => 'integrations/byl/webhook',
'middleware' => [],
],
],
Route::post('/my/byl-webhook', MyWebhookController::class)->middleware('byl-signature');
use Byl\Laravel\Exceptions\BylException;
use Byl\Laravel\Exceptions\ValidationException;
try {
Byl::invoices()->create(['amount' => 5]);
} catch (ValidationException $exception) {
$exception->status(); // 422
$exception->errorFor('amount'); // "The amount must be at least 10."
} catch (BylException $exception) {
report($exception);
}
Byl::project(7)->invoices()->createFor(1000); // өөр төсөл, ижил токен
Byl::project(7, 'other-token')->invoices()->find(1); // өөр төсөл, өөр токен
Byl::withToken('temp-token')->customers()->find(12);
use Byl\Laravel\Facades\Byl;
it('захиалга үүсгэхэд checkout үүснэ', function () {
$byl = Byl::fake();
$this->post('/orders', ['product' => 'starter'])->assertRedirect();
$byl->assertCheckoutCreated(fn (array $payload) => $payload['items'][0]['price'] === 'starter_monthly');
});
$byl = Byl::fake()
->respond('GET', 'customers/*', ['id' => 12, 'email' => '[email protected] '])
->respondWithError('POST', 'invoices', 422, [
'message' => 'The amount field is t(1);
$byl->assertSentForProject(7, 'POST', 'invoices');
$byl->recorded('POST', 'invoices'); // Collection
use Byl\Laravel\Enums\WebhookEventType;
use Byl\Laravel\Events\SubscriptionCanceled;
use Byl\Laravel\Testing\FakeWebhook;
it('захиалга цуцлагдахад эрх хаагдана', function () {
$webhook = FakeWebhook::subscription(WebhookEventType::SubscriptionCanceled, [
'id' => 4,
'status' => 'canceled',
]);
$this->postJson(route('byl.webhook'), $webhook->payload(), $webhook->headers())->assertOk();
expect($user->fresh()->plan)->toBeNull();
});
$webhook = FakeWebhook::subscription(
WebhookEventType::SubscriptionCreated,
SubscriptionFactory::withoutLookupKey(['id' => 4]),
);
bash
php artisan vendor:publish --tag=byl-config
bash
php artisan vendor:publish --tag=byl-migrations
php artisan migrate
bash
php artisan byl:backfill-subscriptions
php artisan byl:backfill-subscriptions --chunk=500