asciisd/knet/knet-development

Claude Code and agent skill by asciisd/knet

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Build and work with KNET payment gateway integration, including payment initiation, callback handling, refunds, and event-driven payment flows.

Install

npx vskill@latest install asciisd/knet/knet-development

SKILL.md

KNET Payment Development

When to use this skill

Use this skill when:

  • Integrating KNET payments into a Laravel application
  • Creating payment flows that redirect users to the KNET gateway
  • Handling KNET payment callbacks and response processing
  • Implementing refunds (full or partial) for KNET transactions
  • Querying transaction status from the KNET gateway
  • Listening to payment events to trigger business logic
  • Working with the knet_transactions table or KnetTransaction model

Package Overview

asciisd/knet provides a fluent Laravel interface to Kuwait's KNET payment gateway. It handles AES-encrypted communication, payment initiation, callback verification, transaction inquiry, and refunds.

Architecture

The package follows SOLID principles with focused interfaces:

  • CreatesPayments — payment creation and response handling
  • InquiresPayments — transaction status inquiry
  • RefundsPayments — full and partial refunds
  • TransactionRepository — data access abstraction
  • EncryptsPayload — encryption abstraction (wraps AES-128-CBC)

KnetPaymentService is a pure delegating facade that implements all three payment interfaces. Prefer depending on the narrower interface when only a subset of functionality is needed.

Setup

Environment Variables
env
KNET_TRANSPORT_ID=your_transport_id
KNET_TRANSPORT_PASSWORD=your_password
KNET_RESOURCE_KEY=your_resource_key
KNET_REDIRECT_URL=/payment/success
KNET_CURRENCY=414
KNET_LANGUAGE=EN
KNET_DEBUG=false
Add the Trait

Add HasKnet to any model that can make payments (typically User):

php
use Asciisd\Knet\HasKnet;
class User extends Authenticatable
{
use HasKnet;
}

This adds:

  • pay(float $amount, array $options = []): KnetTransaction — create a payment
  • payWithKfast(float $amount, array $options = []): KnetTransaction — KFAST faster checkout (auto-generates 8-digit token)
  • refund(KnetTransaction $transaction, ?float $amount = null): array — full or partial refund
  • kfastToken(): string — overridable 8-digit numeric KFAST token generator
  • knetTransactions(): HasMany — relationship to all transactions

Creating Payments

Via the Trait
php
$transaction = $user->pay(10.000, [
'udf1' => 'order_123',
'udf2' => 'product_subscription',
]);
return redirect($transaction->url);
Via Service Injection
php
use Asciisd\Knet\Services\KnetPaymentService;
public function checkout(KnetPaymentService $paymentService)
{
$transaction = $paymentService->createPayment(
user: auth()->user(),
amount: 25.500,
options: [
'udf1' => 'invoice_789',
'trackid' => 'custom-track-id', // optional, auto-generated if omitted
]
);
return redirect($transaction->url);
}
Via Focused Interface

If you only need payment creation, type-hint the narrower interface:

php
use Asciisd\Knet\Contracts\CreatesPayments;
public function checkout(CreatesPayments $payments)
{
$transaction = $payments->createPayment(auth()->user(), 25.500);
return redirect($transaction->url);
}
With KFAST (Faster Checkout)
php
// Auto-generates 8-digit token from user ID (e.g., user ID 42 → "00000042")
$transaction = $user->payWithKfast(25.500, [
'udf1' => 'order_id',
]);
return redirect($transaction->url);
// Or with a custom token override
$transaction = $user->payWithKfast(25.500, [
'udf3' => '99887766',
]);
// Or pass udf3 directly to pay()
$transaction = $user->pay(25.500, [
'udf3' => '12345678',
]);

Override the token strategy by implementing kfastToken() on your model:

php
class User extends Authenticatable
{
use HasKnet;
public function kfastToken(): string
{
return str_pad((string) $this->customer_number, 8, '0', STR_PAD_LEFT);
}
}

KFAST token rules:

  • Must be exactly 8 numeric digits (validated automatically by PaymentRequest)
  • Must uniquely identify the customer
  • KFAST must be enabled on the terminal by the acquirer bank
Important Rules
  • Amounts MUST use 3 decimal places (KWD format): 10.000, 25.500, 0.250
  • Currency code 414 is the ISO code for Kuwaiti Dinar
  • Track IDs must be unique per transaction
  • UDF fields (udf1–udf5) carry custom data through the full payment lifecycle
  • The $transaction->url contains the full KNET gateway URL to redirect the user to

Payment Flow

  1. Initiate: Call $user->pay() or KnetPaymentService::createPayment() — returns a KnetTransaction with a url
  2. Redirect: Send the user to $transaction->url (the KNET payment page)
  3. Callback: KNET POSTs encrypted trandata to /knet/response — middleware decrypts once and passes payload via request attributes
  4. Events: KnetPaymentSucceeded or KnetPaymentFailed is dispatched
  5. Redirect back: User is redirected to KNET_REDIRECT_URL with the result

Handling Payment Events

php
use Asciisd\Knet\Events\KnetPaymentSucceeded;
use Asciisd\Knet\Events\KnetPaymentFailed;
use Illuminate\Support\Facades\Event;
// In a service provider or EventServiceProvider
Event::listen(KnetPaymentSucceeded::class, function ($event) {
$transaction = $event->transaction;
// Fulfill the order, send confirmation, etc.
});
Event::listen(KnetPaymentFailed::class, function ($event) {
$transaction = $event->transaction;
$error = $event->errorMessage;
// Notify user, log failure, etc.
});
All Available Events
EventPayload
KnetPaymentSucceededKnetTransaction $transaction
KnetPaymentFailedKnetTransaction $transaction, ?string $errorMessage
KnetRefundSucceededKnetTransaction $transaction, KnetTransaction $refundTransaction, float $amount
KnetRefundFailedKnetTransaction $transaction, KnetTransaction $refundTransaction, string $reason
KnetResponseReceivedarray $payload
KnetResponseHandledarray $payload
KnetTransactionCreatedKnetTransaction $transaction
KnetTransactionUpdatedKnetTransaction $transaction
KnetTransactionHasErrorsKnetTransaction $transaction
KnetReceiptSeenKnetTransaction $transaction

Working with KnetTransaction

php
use Asciisd\Knet\KnetTransaction;
// Check status
$transaction->isCaptured(); // true if result == 'CAPTURED'
$transaction->hasStatus(); // true if result is not empty
$transaction->isRefundable(); // true if captured and not yet refunded
$transaction->isRefunded(); // true if refunded
// Get amount
$transaction->rawAmount(); // float, e.g. 10.0
$transaction->formattedAmount(); // string, e.g. "10.000"
// Access relationship
$transaction->owner; // the User (or custom model) who made the payment

To find by track ID, use the repository:

php
use Asciisd\Knet\Contracts\TransactionRepository;
$repository = app(TransactionRepository::class);
$transaction = $repository->findByTrackId('track-123');
Key Columns
ColumnTypeDescription
trackidstringUnique tracking identifier
paymentidstringKNET payment ID
resultstringPayment result (CAPTURED, FAILED, etc.)
amtstringPayment amount
authstringAuthorization code
refstringReference number
tranidstringTransaction ID
udf1–udf5stringUser-defined fields
paidbooleanWhether payment was successful
refundedbooleanWhether transaction was refunded
refund_amountdecimalRefund amount (if partial)

Payment Status Enum

php
use Asciisd\Knet\Enums\PaymentStatus;
$status = PaymentStatus::from($transaction->result);
$status->isSuccessful(); // CAPTURED or SUCCESS
$status->isFailed(); // FAILED, ABANDONED, CANCELLED, DECLINED, etc.
$status->isPending(); // INITIATED, PENDING, UNKNOWN
$status->displayName(); // Human-readable name

For presentation (colors, images), use the presenter:

php
$presenter = $status->presenter();
$presenter->styleColor(); // 'success-status', 'info-status', 'danger-status'
$presenter->textColor(); // 'successText', 'infoText', 'dangerText'
$presenter->bgColor(); // 'successBG', 'infoBG', 'dangerBG'
$presenter->imageUrl(); // URL to status image
$presenter->toArray(); // Full presentation array

Inquiry & Refunds

Transaction Inquiry
php
use Asciisd\Knet\Services\KnetPaymentService;
// Re-check transaction status with KNET gateway and update locally
$transaction = $paymentService->inquireAndUpdateTransaction($transaction);
// Raw inquiry (returns array)
$result = $paymentService->inquirePayment(10.000, 'track-123');
Refunds
Via Trait
php
// Full refund
$result = $user->refund($transaction);
// Partial refund
$result = $user->refund($transaction, 5.000);
Via Service
php
// Full refund
$result = $paymentService->refundPayment($transaction);
// Partial refund (5 KWD of a 10 KWD transaction)
$result = $paymentService->refundPayment($transaction, 5.000);
Refund Validation

The service automatically validates before processing:

  • Transaction must be captured and not already refunded (isRefundable())
  • Refund amount must be greater than zero
  • Refund amount must not exceed the original transaction amount

Throws KnetException on validation failure.

Refund Behavior
  • On success: original transaction is marked refunded = true, refunded_at is set, refund_amount is recorded
  • A separate KnetTransaction record is created for the refund (with action = 2 and original_transaction_id linking to the original)
  • KnetRefundSucceeded event is dispatched on success; KnetRefundFailed on failure
  • Refund result is CAPTURED for success; any other value is a failure

Routes

The package auto-registers these routes (prefix configurable via KNET_PATH):

MethodURIPurpose
POST/knet/responseKNET encrypted callback (with signature verification middleware)
POST/knet/handlePost-success redirect handler
GET/POST/knet/errorError callback handler

Disable auto-registration with Knet::ignoreRoutes() in a service provider.

Customization

Custom Billable Model
php
use Asciisd\Knet\KnetTransaction;
// In AppServiceProvider::boot()
KnetTransaction::useCustomerModel(\App\Models\Customer::class);
Skip Package Migrations
php
use Asciisd\Knet\Knet;
// In AppServiceProvider::register()
Knet::ignoreMigrations();
Skip Package Routes
php
use Asciisd\Knet\Knet;
// In AppServiceProvider::register()
Knet::ignoreRoutes();

Artisan Commands

CommandPurpose
php artisan knet:installPublish config, run migrations, validate setup
php artisan knet:checkValidate credentials and configuration
php artisan knet:publishPublish config (--config) and/or migrations (--migrations)

Common Patterns

Complete Checkout Controller
php
use Asciisd\Knet\Services\KnetPaymentService;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
public function __construct(
private readonly KnetPaymentService $paymentService
) {}
public function pay(Request $request)
{
$request->validate(['amount' => 'required|numeric|min:0.001']);
$transaction = $this->paymentService->createPayment(
$request->user(),
$request->amount,
['udf1' => $request->order_id]
);
return redirect($transaction->url);
}
}
Payment Success Listener
php
use Asciisd\Knet\Events\KnetPaymentSucceeded;
class HandleSuccessfulPayment
{
public function handle(KnetPaymentSucceeded $event): void
{
$transaction = $event->transaction;
$orderId = $transaction->udf1;
Order::where('id', $orderId)->update(['status' => 'paid']);
}
}

KNET Gateway Protocol (K-064)

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
14
Repository forks
7
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 18 Mar 2026, 7 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/asciisd/knet/knet-development/badge)](https://verified-skill.com/skills/asciisd/knet/knet-development)

Something wrong with this skill or its page? Tell us.