25: 集成

大多数应用程序最终都会与外部服务进行交互:聊天服务、日历、会计后端、刷卡终端、支付处理器。Phlo 提供了两种用于此的功能,均在运行时中,因此无需额外的 SDK 进行集成,也无需单独的客户端进行连接。连接器是围绕 JSON REST API 的轻量级统一封装;支付资源封装了 Stripe 和 SumUp。

25.1: 连接器

连接器是一个小类,用于一个第三方 REST API。每个连接器都扩展 Connector,读取其自己的凭据部分,并返回相同的结果形状,因此调用 Slack 的方式与调用 Shopify 的方式相同。

$slack = Slack::make()
$res = $slack->send('#general', 'Deploy finished')
if ($res->ok) log('sent') else log($res->error)

make() 从 data/creds.ini 中加载连接器的凭据(Slack 读取 [Slack],Shopify 读取 [Shopify],依此类推)。每次调用都会返回一个标准化的对象,因此你可以根据 ->ok 进行分支,并读取 ->data,而不是为每个服务解析不同的错误格式:

obj(ok: true,  status: 200, data: {...})   // success
obj(ok: false, status: 401, error: '...')  // failure

在底层,Connector 处理请求动词(get/post/put/patch/del/form)、分页(paginate())和身份验证头。每个连接器还公开一个 static fields 凭证架构,因此设置屏幕或 CMS 可以在不硬编码的情况下进行配置。

可用连接器

组别连接器
消息Slack, Telegram, Twilio, MessageBird, Resend
云GoogleCalendar, GoogleSheets, MicrosoftGraph
财务ExactOnline, Moneybird, EBoekhouden
商务Lightspeed, Shopify

使用 OAuth2 进行身份验证的服务(如 Google、Exact)扩展 OAuthConnector 而不是 Connector。它在 TokenStore 中保持一个自动刷新的承载令牌(持久化在 data/tokens/ 下,使用独占锁刷新),因此您的代码只需调用 ->events(...),令牌的处理保持不可见。

每个连接器的方法列表在 Manual 的 connectors 下实时更新。它是从资源文件生成的,因此不会与代码偏离。

25.2: Payments

Stripe

The Stripe resource is a thin layer over the official stripe/stripe-php SDK (add it with Composer). Call Stripe::boot() once with your secret key, then use the static helpers:

Stripe::boot(%creds->Stripe)
$session = Stripe::checkout([
	'mode' => 'subscription',
	'line_items' => [['price' => 'price_123', 'quantity' => 1]],
	'success_url' => 'https://example.com/done',
	'cancel_url' => 'https://example.com/pricing',
])
location($session->url)

checkout() creates a Checkout Session, portal($customerId, $returnUrl) opens the Billing Portal, and verifyWebhook($payload, $sigHeader, $secret) validates an incoming event before you act on it. customer, createCustomer, subscription, subscriptions, product and price cover the rest of the common surface.

Mollie

Mollie::make()->pay(9.50, 'Order 7', $redirectUrl, $webhookUrl) starts a payment and Mollie::checkout($payment) is where you send the customer. The webhook carries only the id of the payment, so ask Mollie::make()->payment($id) what happened and read it with Mollie::paid(). The webhook carries no cookie and no browser header, so the CSRF guard lets it through without an entry in %CSRF.except. A test key runs the whole flow without money.

SumUp

SumUp handles card-present payments on a paired SumUp Solo reader over the Cloud API. It is a connector (SumUp::make(), [SumUp] credentials), so it returns the same obj(ok, ...) result:

$res = SumUp::make()->createReaderCheckout(1250, 'EUR', description: 'Table 4')

createReaderCheckout($amountMinor, $currency, ...) pushes a checkout to the reader (the amount is in minor units, so 1250 is €12.50). transaction() and transactions() look up the result, and terminateReaderCheckout() cancels a pending one.

25.3: Mail

mail::send(to:, subject:, html:) goes out through the transport in the [mail] section of creds: sendmail (the default), smtp, resend, graph, or log, which writes the message to data/mail.log for development. Header values stay on one line and HTML gets a text part. Over SMTP a password only goes out over TLS, unless tls = none says otherwise.

mail::later(...) takes the same arguments and sends from a process of its own. A send that fails stays in data/mail/, and mail::retry() from a task sends it again.

25.4: Webhooks

Check the signature before reading anything from the body:

route POST webhook stripe {
	webhook::stripe(%creds->Stripe->webhookSecret) || error('Bad signature', 400)
	if (!webhook::once(%payload->id)) return output('seen')
}

Also hmac(), slack() and standard(). %req->header('Name') and %req->body give what a signature of your own needs.

25.5: Uploads

Enable files/upload and every request with a file reports its progress: the html element gets the class uploading and --upload from 0 to 1, and document receives an upload event. An <input type=file data-upload> sends a large file in parts that resume after a break, and upload::take($id) gives the finished file. prop %upload.canUpload => (bool)%account->user says who may; what nobody took for a day is cleared.

A file field holds the server to accept and maxSize, and img turns a phone photo upright.

25.6: Text and files from outside

sanitize_html($html) keeps the markup of a mail or an editor and removes what can run. markdown::html($md) renders markdown with the text escaped first. HTTP($url, public: true) reaches only a public address, for a URL someone gave you. CSV::download($rows, 'export.csv') and XLSX::download(['Sheet' => $rows], 'export.xlsx') write rows no spreadsheet will run as formulas.

25.7: Credentials per record

When each customer has an account of their own, the record holds the credentials: $shop->connector = Shopify::seal(['token' => $token]) encrypts them with the key in the [connectors] section of creds, and Shopify::for($shop)->get('orders') uses them. seal() needs security/encryption.

25.8: Small formats

qr::svg($text) draws a QR code as inline SVG, without a library. ICS::download($events, 'agenda.ics') writes a calendar file and ICS::feed($events) a feed a calendar subscribes to. feed::output('My blog', $items) serves an Atom feed. PDOK::make()->address('1012RJ', 147) gives a Dutch address from the government's open register, without a key.

25.9: Without a line

The offline resource keeps an app working when the line is gone: pages come from a service worker, posts wait in a queue in the browser and go out in order when the line is back.

prop %offline.pages = ['orders']
prop %offline.queue = ['note']
prop %offline.owner => (string)%session->user

route async POST note {
	offline::once(fn() => note::create(text: %payload->text, at: offline::at()))
	return apply(main: $this->main)
}

view head:
%offline

An answer can get lost after the work is done, so a post can arrive twice. offline::once() commits a mark and the work together, and the second time does nothing. A refusal moves a post aside with its reason, a 5xx stops the queue because the order matters, and with another owner on the device the cached pages go and the queue waits for the person it belongs to. html.offline, html.queued and [data-offline-count] are there for your CSS, and the queue event for your scripts.

最近更新于 2026年11月5日

我们使用必要的cookie来使该网站正常工作。在您的许可下,我们还使用分析工具来改善网站。