### Shop Helper Functions in PHP Source: https://context7.com/azuriom/plugin-shop/llms.txt Provides examples of using global helper functions for accessing shop functionality like payment management, currency handling, cart operations, and user retrieval. ```php name; } ``` -------------------------------- ### Get Shop Statistics API Endpoint Source: https://context7.com/azuriom/plugin-shop/llms.txt Use this endpoint to retrieve shop statistics for game server integration. Requires a server API token for authentication. ```bash curl -X GET "https://example.com/api/shop/azlink" \ -H "Authorization: Bearer YOUR_SERVER_TOKEN" \ -H "Accept: application/json" ``` -------------------------------- ### Shop API Response Structure Source: https://context7.com/azuriom/plugin-shop/llms.txt Example JSON structure for the shop statistics API response, detailing currency, donation goals, top contributors, and recent donations. ```json { "currency": "USD", "goal": { "progress": 1250.50, "total": 5000.00 }, "top": [ { "user": {"id": 1, "name": "Player1", "game_id": "uuid-1"}, "amount": 500.00, "currency": "USD" } ], "recent": [ { "user": {"id": 2, "name": "Player2", "game_id": "uuid-2"}, "amount": 29.99, "currency": "USD", "timestamp": "2024-01-15T10:30:00+00:00" } ] } ``` -------------------------------- ### Create and Manage Payments Source: https://context7.com/azuriom/plugin-shop/llms.txt Use the Payment model to create pending payments, add items, query by status, and perform actions like delivering or revoking items. Includes methods for formatting prices and getting status colors. ```php auth()->id(), 'price' => 29.99, 'currency' => 'USD', 'gateway_type' => 'stripe', 'status' => 'pending', 'transaction_id' => 'txn_123456', ]); // Add items to payment $payment->items()->create([ 'name' => 'VIP Package', 'price' => 29.99, 'quantity' => 1, 'buyable_type' => 'shop.packages', 'buyable_id' => 1, ]); // Query payments $completed = Payment::completed()->get(); $pending = Payment::pending()->get(); $realMoney = Payment::withRealMoney()->get(); $siteMoney = Payment::withSiteMoney()->get(); // Check payment status if ($payment->isPending()) { // Process payment... } if ($payment->isCompleted()) { // Already delivered } // Deliver payment (mark complete and deliver items) $payment->deliver($renewal = false); // Revoke items (for refunds/chargebacks) $payment->revoke('refund'); // or 'chargeback' // Format price for display echo $payment->formatPrice(); // e.g., "$29.99" or "29.99 coins" // Get status color for UI $color = $payment->statusColor(); // 'success', 'warning', 'danger', etc. // Purge old pending payments (2+ weeks old) Payment::purgePendingPayments(); ``` -------------------------------- ### Create and Manage Discounts Source: https://context7.com/azuriom/plugin-shop/llms.txt Demonstrates creating global and role-specific discounts, attaching them to packages, and checking their status. Use for setting up automatic price reductions. ```php 'Holiday Sale', 'discount' => 20, // 20% off 'is_global' => true, // All packages 'is_enabled' => true, 'roles' => null, // All roles (or array of role IDs) 'start_at' => now(), 'end_at' => now()->addWeek(), ]); // Create a role-specific discount $vipDiscount = Discount::create([ 'name' => 'VIP Discount', 'discount' => 15, 'is_global' => true, 'is_enabled' => true, 'roles' => [2, 3], // Only role IDs 2 and 3 'start_at' => now(), 'end_at' => now()->addYear(), ]); // Attach to specific packages $discount->packages()->attach([1, 2, 3, 4]); // Check if discount is active if ($discount->isActive()) { // Discount currently running } // Check if discount applies to user's role if ($discount->activeForRole($user->role)) { // User qualifies for this discount } // Get all currently active global discounts $globalDiscounts = Discount::getGlobalDiscounts(); // Query discounts $activeDiscounts = Discount::active()->get(); $globalOnly = Discount::global()->get(); ``` -------------------------------- ### Create and Manage Subscriptions Source: https://context7.com/azuriom/plugin-shop/llms.txt Shows how to create subscription packages, check user subscriptions, query subscription states, and manage subscription lifecycle events like cancellation and renewal. ```php 'Premium Monthly', 'price' => 9.99, 'billing_type' => 'subscription', 'billing_period' => '1 months', 'category_id' => 1, 'is_enabled' => true, ]); // Check if user is subscribed if ($package->isUserSubscribed($user)) { // User has active subscription } // Query subscriptions $active = Subscription::active()->get(); $pendingExpiration = Subscription::pendingExpiration()->get(); $waitingRenewal = Subscription::waitingForRenewal()->get(); // Get subscription details $subscription = Subscription::find(1); echo $subscription->formatPrice(); // "$9.99" echo $subscription->getTypeName(); // "Stripe" echo $subscription->statusColor(); // "success" // Check subscription state if ($subscription->isActive()) { echo "Ends at: " . $subscription->ends_at; } if ($subscription->isCanceled()) { // Still active until ends_at, but won't renew } if ($subscription->isEnded()) { // Subscription period has passed } // Cancel subscription $subscription->cancel(); // Handle renewal payment $payment = $subscription->addRenewalPayment($transactionId); // Expire subscription and revoke items $subscription->expire(); ``` -------------------------------- ### Define and Manage Shop Packages with PHP Source: https://context7.com/azuriom/plugin-shop/llms.txt The Package model represents purchasable items. It supports pricing, discounts, limits, subscriptions, and server commands for delivery and expiration. ```php 1, 'name' => 'VIP Rank', 'short_description' => 'Get VIP status on the server', 'description' => 'Full VIP access with exclusive perks', 'price' => 9.99, 'position' => 1, 'has_quantity' => false, 'user_limit' => 1, // Max 1 per user 'global_limit' => 100, // Max 100 total sales 'is_enabled' => true, 'commands' => [ [ 'trigger' => 'purchase', 'server' => 1, 'require_online' => false, 'commands' => ['lp user {player} parent set vip'], ], [ 'trigger' => 'expiration', 'server' => 1, 'require_online' => false, 'commands' => ['lp user {player} parent set default'], ], ], ]); // Query enabled packages $packages = Package::enabled()->get(); // Get package pricing with discounts $originalPrice = $package->getOriginalPrice(); $discountedPrice = $package->getPrice(); $isDiscounted = $package->isDiscounted(); // Check purchase limits $maxQuantity = $package->getMaxQuantity(); $userPurchases = $package->countUserPurchases(); $totalPurchases = $package->countTotalPurchases(); // Check requirements $hasBoughtRequired = $package->hasBoughtRequirements(); $hasRequiredRole = $package->hasRequiredRole($user->role); // Check if subscription if ($package->isSubscription()) { $periodCount = $package->subscriptionPeriodCount(); // e.g., 1 $periodUnit = $package->subscriptionPeriodUnit(); // e.g., 'months' $isSubscribed = $package->isUserSubscribed($user); } // Deliver package items to user $package->deliver($paymentItem, $renewal = false); // Handle expiration (revoke items) $package->expire($paymentItem, 'expiration'); ``` -------------------------------- ### Create and Manage Coupons Source: https://context7.com/azuriom/plugin-shop/llms.txt Create percentage or fixed-amount discount coupons with options for global or package-specific application, usage limits, and expiration dates. Coupons can be validated and applied to packages. ```php 'SUMMER25', 'discount' => 25, // 25% off 'is_fixed' => false, // Percentage discount 'is_global' => true, // Applies to all packages 'is_enabled' => true, 'can_cumulate' => false, // Cannot combine with other coupons 'user_limit' => 1, // Once per user 'global_limit' => 100, // 100 total uses 'start_at' => now(), 'expire_at' => now()->addMonth(), ]); // Create a fixed amount coupon for specific packages $fixedCoupon = Coupon::create([ 'code' => 'SAVE10', 'discount' => 10, // $10 off 'is_fixed' => true, // Fixed amount discount 'is_global' => false, // Specific packages only 'is_enabled' => true, 'user_limit' => 0, // Unlimited per user 'global_limit' => 0, // Unlimited total 'start_at' => now(), 'expire_at' => null, // Never expires ]); // Attach coupon to specific packages $fixedCoupon->packages()->attach([1, 2, 3]); // Validate and use coupon $coupon = Coupon::where('code', $request->input('code'))->first(); if (!$coupon) { return back()->with('error', 'Invalid coupon code'); } if (!$coupon->isActive()) { return back()->with('error', 'Coupon is not active'); } if ($coupon->hasReachLimit(auth()->user())) { return back()->with('error', 'Coupon limit reached'); } // Check if coupon applies to a specific package $package = Package::find(1); if ($coupon->isActiveOn($package)) { $discountedPrice = $coupon->applyOn($package->price); } // Query active coupons $activeCoupons = Coupon::active()->get(); $enabledCoupons = Coupon::enabled()->get(); ``` -------------------------------- ### Manage Categories Source: https://context7.com/azuriom/plugin-shop/llms.txt Illustrates creating parent and subcategories, querying them, accessing relationships, and checking purchase limits for single-purchase categories. ```php 'Ranks', 'slug' => 'ranks', 'description' => 'Server rank packages', 'position' => 1, 'parent_id' => null, 'cumulate_purchases' => true, // Deduct previous rank price 'cumulate_strict' => false, // Allow downgrade 'single_purchase' => false, // Allow multiple purchases 'is_enabled' => true, ]); // Create subcategory $subCategory = Category::create([ 'name' => 'Premium Ranks', 'slug' => 'premium-ranks', 'parent_id' => $category->id, 'position' => 1, 'is_enabled' => true, ]); // Query categories $parentCategories = Category::parents()->enabled()->get(); $enabledCategories = Category::enabled()->get(); // Get category relationships $parent = $subCategory->category; // Parent category $children = $category->categories; // Subcategories $packages = $category->packages; // Packages in category // Check purchase limits for single_purchase categories if ($category->hasReachLimit($user)) { return back()->with('error', 'You can only purchase one item from this category'); } ``` -------------------------------- ### Create Custom Payment Gateway Class Source: https://github.com/azuriom/plugin-shop/blob/master/README.md Extend the `PaymentMethod` class to implement a new payment gateway. Set the `$id` and `$name` properties. Implement `startPayment`, `notification`, `view`, `rules`, and `image` methods to handle payment processes and configuration. ```php createPayment($cart, $amount, $currency); // Start the payment process with the payment gateway $response = Http::post('https://api.bestpayment.pay', [ // The routes below will automatically call the methods in this class 'success_url' => route('shop.payments.success', $this->id), 'failure_url' => route('shop.payments.failure', $this->id), 'status_url' => route('shop.payments.notification', $this->id), 'custom_id' => $payment->id, // the Azuriom payment identifier 'amount' => $amount, // amount to pay 'currency' => $currency, // ISO 4217 currency code 'secret_key' => $this->gateway->data['secret_key'], ]); // Redirect the user to the payment gateway // You can also return a view depending on the payment gateway requirements return redirect()->away($response->json('url')); } /** * Handle a payment notification request sent by the payment gateway and return a response. */ public function notification(Request $request, ?string $paymentId) { // This method is associated to `route('shop.payments.notification', $this->id)` // Always verify the request is authentic to avoid fraud abort_if(! $this->verifySignature($request), 400); $payment = Payment::findOrFail($request->input('custom_id')); $transactionId = $request->input('transaction_id'); $status = $request->integer('status'); if ($status === 'refunded') { return $this->processRefund($payment); } if ($status === 'chargeback') { return $this->processChargeback($payment); } if ($status !== 'success') { // You can return a response to the payment gateway to notify it of the error return $this->invalidPayment($payment, $transactionId, 'Invalid status: '.$status); } // Process the payment and deliver the items to the user return $this->processPayment($payment, $transactionId); } /** * Get the view for the gateway config in the admin panel. */ public function view(): string { return 'best-payment::admin.config'; } /** * Get the validation rules for the gateway config in the admin panel. */ public function rules(): array { return [ 'public_key' => ['required', 'string'], 'secret_key' => ['required', 'string'], ]; } public function image(): string { return asset('plugins/best-payment/img/best.svg'); } } ``` -------------------------------- ### Manage Shopping Cart with PHP Source: https://context7.com/azuriom/plugin-shop/llms.txt Use the Cart class to manage items, coupons, and gift cards in the session. It calculates totals and allows clearing the cart. ```php session()); // Add a package to the cart $package = Package::find(1); $cartItem = $cart->add($package, 2); // Add 2 of this package // Set specific quantity for a package $cart->set($package, 5); // Set quantity to 5 // Check if package is in cart if ($cart->has($package)) { $item = $cart->get($package); echo "Quantity: " . $item->quantity; } // Apply a coupon $coupon = Coupon::where('code', 'SUMMER20')->first(); if ($coupon && $coupon->isActive()) { $cart->addCoupon($coupon); } // Apply a giftcard $giftcard = Giftcard::where('code', '1234-5678-9012-3456')->first(); if ($giftcard && $giftcard->isActive()) { $cart->addGiftcard($giftcard); } // Get cart totals $originalTotal = $cart->originalTotal(); // Total without discounts $total = $cart->total(); // Total after coupons $payableTotal = $cart->payableTotal(); // Final total after giftcards // Get cart contents $items = $cart->content(); $itemCount = $cart->count(); // Clear cart $cart->clear(); // Clear items only $cart->clearCoupons(); // Clear coupons only $cart->destroy(); // Clear everything (items, coupons, giftcards) ``` -------------------------------- ### Shop Web Routes Reference Source: https://context7.com/azuriom/plugin-shop/llms.txt Reference for web routes available in the Azuriom Shop plugin, covering public access, cart management, coupon and giftcard operations, package purchases, subscriptions, and payment flows. ```php registerPaymentMethod()` helper. ```php public function boot(): void { payment_manager()->registerPaymentMethod('best-payment', BestPaymentMethod::class); } ``` -------------------------------- ### Shop Statistics API Source: https://context7.com/azuriom/plugin-shop/llms.txt Retrieve shop statistics for game server integration. Requires a server API token for authentication. ```APIDOC ## GET /api/shop/azlink ### Description Retrieves shop statistics, including currency, donation goals, top donors, and recent donations. ### Method GET ### Endpoint /api/shop/azlink ### Parameters #### Query Parameters None #### Headers - **Authorization** (string) - Required - Bearer token for server authentication. - **Accept** (string) - Optional - `application/json` to specify response format. ### Response #### Success Response (200) - **currency** (string) - The shop's currency code (e.g., "USD"). - **goal** (object) - Donation goal information. - **progress** (float) - Current amount raised towards the goal. - **total** (float) - The total amount for the donation goal. - **top** (array) - List of top donors. - **user** (object) - Donor's user information. - **id** (integer) - User's unique identifier. - **name** (string) - User's display name. - **game_id** (string) - User's game-specific identifier. - **amount** (float) - The amount donated by the user. - **currency** (string) - The currency of the donation. - **recent** (array) - List of recent donations. - **user** (object) - Donor's user information (same structure as in 'top'). - **amount** (float) - The amount of the donation. - **currency** (string) - The currency of the donation. - **timestamp** (string) - The time the donation was made (ISO 8601 format). ### Request Example ```bash curl -X GET "https://example.com/api/shop/azlink" \ -H "Authorization: Bearer YOUR_SERVER_TOKEN" \ -H "Accept: application/json" ``` ### Response Example ```json { "currency": "USD", "goal": { "progress": 1250.50, "total": 5000.00 }, "top": [ { "user": {"id": 1, "name": "Player1", "game_id": "uuid-1"}, "amount": 500.00, "currency": "USD" } ], "recent": [ { "user": {"id": 2, "name": "Player2", "game_id": "uuid-2"}, "amount": 29.99, "currency": "USD", "timestamp": "2024-01-15T10:30:00+00:00" } ] } ``` ``` -------------------------------- ### Web Routes Reference Source: https://context7.com/azuriom/plugin-shop/llms.txt Reference for web routes used by the storefront, cart, checkout, and user profile functionalities. ```APIDOC ## Web Routes Reference ### Public Routes - **GET `/shop`**: Displays the main shop page with a list of categories. - **GET `/shop/categories/{slug}`**: Shows packages within a specific category identified by its slug. - **GET `/shop/packages/{package}`**: Displays detailed information about a specific package. ### Cart Routes Requires shop authentication. - **GET `/shop/cart`**: View the contents of the shopping cart. - **POST `/shop/cart`**: Update quantities of items in the cart. - **POST `/shop/cart/remove/{package}`**: Remove a specific package from the cart. - **POST `/shop/cart/clear`**: Empty the entire shopping cart. - **POST `/shop/cart/payment`**: Initiate payment for the cart using site money. ### Coupon Routes - **POST `/shop/cart/coupons/add`**: Add a coupon code to the cart. - **POST `/shop/cart/coupons/remove/{coupon}`**: Remove a specific coupon from the cart. - **POST `/shop/cart/coupons/clear`**: Remove all applied coupons from the cart. ### Giftcard Routes - **POST `/shop/cart/giftcards/add`**: Add a gift card to the cart for payment. - **POST `/shop/cart/giftcards/remove/{giftcard}`**: Remove a gift card from the cart. - **POST `/shop/giftcards/add`**: Add a gift card to the user's account. ### Package Purchase Routes - **POST `/shop/packages/{package}/buy`**: Initiate the purchase process for a package. - **GET `/shop/packages/{package}/options`**: Display the form for selecting package options/variables. - **POST `/shop/packages/{package}/options`**: Purchase a package with selected options. - **GET `/shop/packages/{package}/files/{file}`**: Download a purchased file associated with a package. ### Subscription Routes - **POST `/shop/subscriptions/{package}`**: Select a payment gateway for a package subscription. - **POST `/shop/subscriptions/{package}/{gateway}`**: Start a subscription for a package with a chosen gateway. - **DELETE `/shop/subscriptions/{subscription}`**: Cancel an existing subscription. ### Payment Routes - **GET `/shop/payments/payment`**: Select a payment gateway for a transaction. - **POST `/shop/payments/{gateway}/pay`**: Initiate payment processing with a specific gateway. - **GET `/shop/payments/{gateway}/success`**: Callback URL for successful payment processing. - **GET `/shop/payments/{gateway}/failure`**: Callback URL for failed payment processing. ### Offers Routes For direct real money purchases of offers. - **GET `/shop/offers`**: View available offers and select a payment method. - **GET `/shop/offers/{gateway}`**: View offers compatible with a specific payment gateway. - **POST `/shop/offers/{offer}/{gateway}`**: Purchase a specific offer using a chosen gateway. ### Profile - **GET `/shop/profile`**: View the user's purchase history. ``` -------------------------------- ### Manage Payments with PaymentManager Source: https://context7.com/azuriom/plugin-shop/llms.txt Use the PaymentManager to register, retrieve, and manage payment methods. It also handles direct purchases using site money and allows manual creation of pending payment records. ```php getPaymentMethods(); // Check if a payment method exists if ($manager->hasPaymentMethod('stripe')) { $stripe = $manager->getPaymentMethod('stripe', $gateway); } // Get payment method or fail with 404 $method = $manager->getPaymentMethodOrFail('paypal', $gateway); // Register a custom payment method $manager->registerPaymentMethod('custom-pay', CustomPayMethod::class); // Buy packages using site money (virtual currency) $cart = Cart::fromSession(request()->session()); if (use_site_money()) { $user = auth()->user(); $total = $cart->payableTotal(); if ($user->hasMoney($total)) { $user->removeMoney($total); $manager->buyPackages($cart); $cart->destroy(); } } // Create a pending payment record manually $payment = PaymentManager::createPayment( $cart, $price = 49.99, $currency = 'USD', $gatewayId = 'stripe', $transactionId = null ); ``` -------------------------------- ### Manage Giftcards Source: https://context7.com/azuriom/plugin-shop/llms.txt Create and manage giftcards with automatic code generation, balance tracking, and expiration dates. Giftcards can be validated, added to the cart, and their status checked. ```php Giftcard::randomCode(), // e.g., "1234-5678-9012-3456" 'balance' => 50.00, 'original_balance' => 50.00, 'start_at' => now(), 'expire_at' => now()->addYear(), ]); // Validate giftcard $giftcard = Giftcard::where('code', $code)->first(); if ($giftcard && $giftcard->isActive()) { // Add to cart $cart->addGiftcard($giftcard); } // Check if giftcard has pending transaction if ($giftcard->isPending()) { // Balance locked for in-progress payment } // Refresh balance after failed payment $giftcard->refreshBalance(); // Notify user about purchased giftcard $giftcard->notifyUser($user); // Get shareable link $shareUrl = $giftcard->shareableLink(); // Returns: https://example.com/shop/profile?giftcard=1234-5678-9012-3456 // Query active giftcards $activeCards = Giftcard::active()->get(); ``` -------------------------------- ### Payment Gateway Notification Endpoint Source: https://context7.com/azuriom/plugin-shop/llms.txt This endpoint is used by payment gateways to send webhook notifications about payment events. Ensure the correct content type and signature headers are used. ```bash curl -X POST "https://example.com/api/shop/payments/stripe/notification" \ -H "Content-Type: application/json" \ -H "Stripe-Signature: t=1234,v1=signature..." \ -d '{"type":"checkout.session.completed","data":{"object":{...}}}' ``` -------------------------------- ### Payment Notification Webhook Source: https://context7.com/azuriom/plugin-shop/llms.txt Endpoint for payment gateways to send notifications about payment status updates. This is typically a POST request. ```APIDOC ## ANY /api/shop/payments/{gateway}/notification/{id?} ### Description Receives payment gateway notifications (webhooks) to update order statuses and confirm payments. ### Method ANY (typically POST) ### Endpoint /api/shop/payments/{gateway}/notification/{id?} - `{gateway}`: The payment gateway identifier (e.g., 'stripe'). - `{id?}`: Optional notification ID. ### Parameters #### Path Parameters - **gateway** (string) - Required - The identifier of the payment gateway. - **id** (string) - Optional - A specific notification identifier. #### Request Body The structure of the request body depends on the payment gateway. It typically contains event details and payment information. ### Request Example (Stripe) ```bash curl -X POST "https://example.com/api/shop/payments/stripe/notification" \ -H "Content-Type: application/json" \ -H "Stripe-Signature: t=1234,v1=signature..." \ -d '{"type":"checkout.session.completed","data":{"object":{...}}}' ``` ### Response #### Success Response (200) Typically returns an empty response or a simple acknowledgment (e.g., `OK`). The actual processing happens server-side. #### Error Response - **400 Bad Request**: If the request is malformed or invalid. - **403 Forbidden**: If authentication or signature verification fails. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.