Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions docs/guides/product-feed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Product Feed

The **Product Feed** addon publishes your store catalogue as JSON, so your website can show the same prices,
options and addons the order form charges, without copying them by hand.

## Turn it on

1. Go to **Extensions → Manage extensions**, find **Product Feed** and activate it.
2. Open it. The page shows the feed address and the address of each published group.

The feed is at `https://<your PNLCS>/feed/products.json`. It needs no login: it shows only what anyone can already
see in the store.

## What it contains

- the groups you publish, each with its name, slug, headline and tagline;
- their products that are neither hidden nor retired: name, slug, description (as written and as HTML), whether tax
applies, the order link, and the price and setup fee of each billing cycle the product is sold on;
- the product's configurable options and their values that are not hidden, priced on the product's cycles (a value
not sold on a cycle has no price for it);
- the product addons offered with it, priced the same way.

Prices are in the default currency, the one the store sells in, as you entered them (before tax).

## Parameters

| Parameter | Example | Effect |
| --- | --- | --- |
| `group` | `?group=backup` | only that group |
| `product` | `?product=backup-500` | only that product |
| `lang` | `?lang=it` | descriptions in that language, order links that open the store in it |

## Settings

- **Groups to publish**: group slugs, separated by commas. Empty publishes every group the store lists. A hidden
group can be published by naming it here, for a landing page that is not in the store menu.
- **Websites allowed to read it from the browser**: one address per line (`https://www.example.com`), or `*`.
Needed only when JavaScript on another domain reads the feed. A site that reads it on its server, or when its
pages are built, needs nothing here.
- **Cache (minutes)**: how long an answer is kept, 10 by default. A price change shows in the feed after this time.
`0` turns the cache off.

The feed answers at most 60 requests a minute from the same address.

## Using it on a website

The simplest and most robust way is to read the feed when the site is built, and write the prices into the pages:
the site stays fast and keeps working if PNLCS is unreachable. Build again after a price change, or every night.

```sh
curl -s 'https://billing.example.com/feed/products.json?group=backup&lang=en' -o products.json
```
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ nav:
- Guides:
- Configure Email: guides/configure-email.md
- Payment Gateways: guides/payment-gateways.md
- Product Feed: guides/product-feed.md
- Connect a Server: guides/connect-a-server.md
- "Plesk: Existing Accounts & Resellers": guides/plesk-existing-accounts.md
- Live Servers: guides/live-servers.md
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

namespace Modules\Addons\ProductFeed\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AddonSetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Modules\Addons\ProductFeed\Services\ProductFeed;

/**
* GET /feed/products.json: the public catalogue as JSON, for a website that
* prints the store's prices. No login; the answer is the same for everyone and
* is cached for the minutes set on the addon.
*/
class ProductFeedController extends Controller
{
public function products(Request $request, ProductFeed $feed): JsonResponse
{
$validated = $request->validate([
'group' => ['nullable', 'string', 'max:255'],
'product' => ['nullable', 'string', 'max:255'],
'lang' => ['nullable', 'string', 'max:10', 'regex:/^[a-z]{2}(-[a-z]{2})?$/'],
]);

$language = isset($validated['lang']) && File::isDirectory(lang_path($validated['lang'])) ? $validated['lang'] : null;
$minutes = max(0, (int) AddonSetting::getSetting(ProductFeed::ADDON, 'cache_minutes', 10));
$key = 'productfeed:'.sha1(json_encode([$validated['group'] ?? null, $validated['product'] ?? null, $language]));

$build = function () use ($feed, $validated, $language): array {
$previous = app()->getLocale();
if ($language !== null) {
app()->setLocale($language);
}

try {
return ['generated_at' => now()->toIso8601String()]
+ $feed->build($validated['group'] ?? null, $validated['product'] ?? null, $language);
} finally {
app()->setLocale($previous);
}
};

$data = $minutes > 0 ? Cache::remember($key, now()->addMinutes($minutes), $build) : $build();

return response()->json($data, 200, $this->corsHeaders($request) + [
'Cache-Control' => 'public, max-age='.($minutes * 60),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

/**
* The origins allowed to read the feed from a browser. A site that builds
* its pages on the server needs none of this; JavaScript on another domain
* does.
*
* @return array<string, string>
*/
private function corsHeaders(Request $request): array
{
$allowed = ProductFeed::listSetting('allowed_origins');
$origin = (string) $request->headers->get('Origin', '');

if (in_array('*', $allowed, true)) {
return ['Access-Control-Allow-Origin' => '*'];
}

if ($origin !== '' && in_array(rtrim($origin, '/'), array_map(fn (string $value) => rtrim($value, '/'), $allowed), true)) {
return ['Access-Control-Allow-Origin' => $origin, 'Vary' => 'Origin'];
}

return [];
}
}
100 changes: 100 additions & 0 deletions modules/Addons/ProductFeed/ProductFeedModule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

namespace Modules\Addons\ProductFeed;

use App\Contracts\AddonModuleInterface;
use Illuminate\Http\Request;
use Modules\Addons\ProductFeed\Services\ProductFeed;

/**
* Publishes the store's catalogue as JSON at /feed/products.json, so a
* website can show the prices and options the order form charges without
* copying them by hand.
*/
class ProductFeedModule implements AddonModuleInterface
{
public function getName(): string
{
return ProductFeed::ADDON;
}

public function getDisplayName(): string
{
return 'Product Feed';
}

public function getDescription(): string
{
return 'Public JSON feed of the store catalogue (products, prices, options and addons) for your website.';
}

public function getVersion(): string
{
return '1.0.0';
}

public function getAuthor(): string
{
return 'PNLCS';
}

/** @return array{success: bool, message: string} */
public function activate(): array
{
return ['success' => true, 'message' => 'Product Feed activated'];
}

/** @return array{success: bool, message: string} */
public function deactivate(): array
{
return ['success' => true, 'message' => 'Product Feed deactivated'];
}

/** @return list<array{name: string, label: string, type: string, default: string, hint: string}> */
public function config(): array
{
return [
['name' => 'groups', 'label' => __('product-feed::addon.groups'), 'type' => 'text', 'default' => '',
'hint' => __('product-feed::addon.groups_hint')],
['name' => 'allowed_origins', 'label' => __('product-feed::addon.allowed_origins'), 'type' => 'textarea', 'default' => '',
'hint' => __('product-feed::addon.allowed_origins_hint')],
['name' => 'cache_minutes', 'label' => __('product-feed::addon.cache_minutes'), 'type' => 'text', 'default' => '10',
'hint' => __('product-feed::addon.cache_minutes_hint')],
];
}

/** @return list<array{label: string, icon: string, url: string}> */
public function sidebar(): array
{
return [];
}

/** @return array{success: bool, message: string} */
public function upgrade(string $fromVersion): array
{
return ['success' => true, 'message' => 'Upgraded from '.e($fromVersion)];
}

public function output(Request $request): string
{
$url = url('feed/products.json');
$groups = app(ProductFeed::class)->publishedGroups();

$html = '<p>'.e(__('product-feed::addon.intro')).'</p>';
$html .= '<p><a href="'.e($url).'" target="_blank" rel="noopener"><code>'.e($url).'</code></a></p>';
$html .= '<p style="font-size:13px;color:var(--pn-muted);">'.e(__('product-feed::addon.parameters')).'</p>';
$html .= '<h6 style="margin-top:16px;">'.e(__('product-feed::addon.published_groups')).'</h6>';

if ($groups->isEmpty()) {
return $html.'<p style="color:var(--pn-muted);">'.e(__('product-feed::addon.no_groups')).'</p>';
}

$html .= '<ul>';
foreach ($groups as $group) {
$groupUrl = $url.'?group='.rawurlencode((string) $group->slug);
$html .= '<li>'.e((string) $group->name).' — <a href="'.e($groupUrl).'" target="_blank" rel="noopener"><code>'.e($groupUrl).'</code></a></li>';
}

return $html.'</ul>';
}
}
14 changes: 14 additions & 0 deletions modules/Addons/ProductFeed/ProductFeedServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Modules\Addons\ProductFeed;

use Illuminate\Support\ServiceProvider;

class ProductFeedServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadRoutesFrom(__DIR__.'/routes.php');
$this->loadTranslationsFrom(__DIR__.'/lang', 'product-feed');
}
}
Loading
Loading