# PHP quickstart

> From an API key to a first decision and outcome, in a free test environment. You need PHP 8.1 or later with the curl extension.

## 1. Create a project and copy its test key

1. Sign in at [/signin/](https://zigbongo.com/signin/). If you don't have an account yet, the e-mailed sign-in link creates one.
2. Name your organization (usually your company) and accept the Terms of Service.
3. Create a project, such as "Checkout". It comes with two environments: **live**, for real customers, and **test**,
   for development and staging.
4. You land on the project's **API keys** page. Under **Test environment**, give the key a label if you like (such as
   "laptop") and select **Create key**.
5. Copy the key now: it's shown only once. It starts with `zb_`.

The test environment is free, and it learns separately from live, so test traffic never sways live decisions. Keep
the key on your server, for example in an environment variable. Never ship it in a browser or app.

## 2. Install the SDK

The SDK is published to Zigbongo's Composer registry on GitLab. Add it to your project's repositories, then require
the SDK:

```sh
composer config repositories.zigbongo composer https://gitlab.com/api/v4/group/144185712/-/packages/composer/packages.json
composer require zigbongo/sdk
```

No token is needed. The first line leaves this in your `composer.json`, which you can also write yourself:

```json
{
    "repositories": [{
        "name": "zigbongo",
        "type": "composer",
        "url": "https://gitlab.com/api/v4/group/144185712/-/packages/composer/packages.json"
    }]
}
```

`composer require` adds the latest release, and `composer.lock` keeps it. To upgrade, run `composer update
zigbongo/sdk`.

The SDK needs PHP 8.1 or later with the `curl` extension, and nothing else.

## 3. Configure it from the environment

Set `ZIGBONGO_KEY` in the environment your PHP code runs in. From a shell:

```sh
export ZIGBONGO_KEY="zb_..."
```

Then create the client, where your code needs it:

```php
use Zigbongo\Zigbongo;

$zb = new Zigbongo(apiKey: getenv('ZIGBONGO_KEY'), baseUrl: 'https://zigbongo.com');
```

## 4. Make your first decision

Pick a choice your product already makes. In this example, the checkout can offer an annual upgrade, and today it
doesn't:

```php
$s = $zb->session('checkout', $user->id);
$upsell = $s->decide('upsell', ['none', 'annual'], 'none');

if ($upsell->option === 'annual') {
    // show the annual upgrade
}
```

- `'checkout'` is the flow. It's created the first time you ask about it, so there's nothing to register.
- `$user->id` is the subject: your own id for this customer, a string or an int. Send the same id every time. An int
  is sent as its text, so `42` and `'42'` are the same customer.
- `'upsell'` is the decision point, `['none', 'annual']` are its options, and `'none'` is the default, the option you
  show today.

`decide()` returns a `Decision`:

| Property | What it holds |
|---|---|
| `option` | The option to show. |
| `arm` | `optimised` when Zigbongo chose, `holdout` when this customer keeps your defaults, `paused` when the flow is paused, `fallback` when the SDK fell back. |
| `fallback` | `true` when the SDK returned your default because Zigbongo didn't answer in time or failed. |
| `sessionId` | The session. `$s` keeps it for its next calls. |
| `decisionId` | This decision. |

Zigbongo starts from your default: at first your customers mostly see what they see today, and traffic moves as the
evidence builds.

`decide()` never throws. If Zigbongo doesn't answer within 150 ms, can't be reached or answers with an error, you get
your default back with `fallback: true`. The SDK then reports the fallback, so that decision is never learned from.
PHP has nothing running in the background, so reports wait in the client and go out when the script ends, when the
client is destroyed or when you call `$zb->flush()`, within a second in all. Under PHP-FPM, finish the response first with
`fastcgi_finish_request()` so nobody waits for them (Symfony and Laravel already do). In a long-running worker, call
`$zb->flush()` after each job. The details are in [Fallbacks and timeouts](https://zigbongo.com/docs/fallbacks-and-timeouts.md).

Before PHP 8.5, each request that decides opens a new connection to Zigbongo, and that counts towards the 150 ms.
From PHP 8.5, the worker keeps its connection between requests.

### More decision points, across pages

If the flow has more choices, call `$s->decide()` at each one: they all count as one session, however many there are.
When each step is its own page, keep the session's ids between requests and carry on from them:

```php
$s = $zb->session('checkout', $user->id,
    sessionId: $_SESSION['zb_session'] ?? null, lastDecisionId: $_SESSION['zb_last'] ?? null);
$plan = $s->decide('plan', ['monthly', 'annual'], 'monthly');
$_SESSION['zb_session'] = $s->sessionId;
$_SESSION['zb_last'] = $s->lastDecisionId;
```

`decide()` also takes a `result:` describing what happened at the previous decision point, such as the answer given,
and the SDK attaches it to the decision in `lastDecisionId`. See [Sessions and outcomes](https://zigbongo.com/docs/sessions-and-outcomes.md).

### Context, if you have it

Send what you know about the customer as inputs, so each group of customers can get its own best option:

```php
$upsell = $s->decide('upsell', ['none', 'annual'], 'none',
    inputs: ['plan' => 'starter', 'country' => 'LT', 'source' => 'newsletter']);
```

Inputs are flat: strings, numbers, booleans or `null`, raw or bucketed. They add up over the session. See
[Inputs](https://zigbongo.com/docs/inputs.md).

## 5. Report the outcome

When the customer pays, report what it's worth. In PHP, that usually happens in another request: the confirmation
page, or your payment provider's webhook. So report it **per customer**:

```php
// in your payment handler
$zb->outcome($invoice->id, 'checkout', $invoice->total, subjectId: $user->id);
```

### Why per customer

In PHP, the session object `$s` lives for one request: it, and the session id it holds, are gone once the page that
made the decision has been sent. The request that sees the payment doesn't have them, but it does know who paid. An
outcome reported per customer needs only that: it counts towards each of that customer's sessions in the flow whose
attribution window it falls in. Send the same `subjectId` you used for the decision.

The attribution window is one day from the session's start, by default. For renewals or churn, make it longer in the
flow's settings (up to 90 days).

### Per session, if you keep its id

To credit one session exactly, keep its id with the order when you decide, and report by it later:

```php
// when deciding
$order->zigbongo_session = $upsell->sessionId;

// in your payment handler
$zb->outcome($invoice->id, 'checkout', $invoice->total, sessionId: $order->zigbongo_session);
```

A decision that fell back before any session started has a `sessionId` of `null`: report that customer's outcome per
customer instead. In the same request as the decision, `$s->outcome($invoice->total, $invoice->id)` reports per
session, or per customer when there's no session.

### Good to know

- `value` is a number: revenue, margin, or 1 for a renewal. Higher is better unless you change that in the flow's
  settings.
- The outcome id (the first argument) is your own id for the outcome, a string or an int, such as the invoice id.
  Reporting it again is harmless: nothing counts twice, and `outcome()` usually returns `duplicate` (it may return
  `accepted` when the repeat reaches another of Zigbongo's servers). It's unique across the environment, not per flow,
  so if you report one payment to two flows, give each report its own id.
- `outcome()` returns `accepted` or `duplicate`. It retries timeouts, rate limits (429) and server errors, waiting as
  long as Zigbongo asks, up to 10 seconds in all, and throws a `ZigbongoException` otherwise. Its `errorCode` is
  `invalid_input`, for example, for a flow key that isn't valid, such as one with a space in it. An outcome for a flow
  that has had no decision yet is accepted, and changes nothing. The waits hold the PHP worker, so report outcomes from
  a queued job where you can.

## 6. See it in the dashboard

Open the project's **Flows** page and switch it to **Test**. `checkout` is listed after its first decision, marked
"optimizing". Open it to see:

- how many sessions it has had, and when the report was last updated;
- the value per session of the customers Zigbongo chooses for against the holdout's, with a 95% interval, once
  each side has enough sessions with an outcome (the page says how many it's waiting for);
- each decision point's options, their share of traffic, and how often the SDK fell back.

Sessions whose attribution window is still open show as pending. On the **API keys** page, each key shows when it was
last used, and by which SDK.

## 7. Switch to the live key

When it works in test:

1. On the project's **API keys** page, under **Live environment**, create a key and copy it.
2. Set `ZIGBONGO_KEY` to it on your production servers. The code doesn't change: the key decides the environment.

The live environment learns on its own, starting from your defaults, and its flows appear on their first live
decision. Live sessions count towards your usage: 10,000 free every month, then €4 per 1,000, excluding VAT (see
[Pricing](https://zigbongo.com/pricing/)). Keep the test key for development and staging.

## Next

- [Sessions and outcomes](https://zigbongo.com/docs/sessions-and-outcomes.md): sessions across requests, step results and attribution.
- [Fallbacks and timeouts](https://zigbongo.com/docs/fallbacks-and-timeouts.md): `onError`, `flush()` and the report timeout.
- [Holdout and lift](https://zigbongo.com/docs/holdout-and-lift.md): reading the report.
- [Environments and keys](https://zigbongo.com/docs/environments-and-keys.md): revoking and rotating keys.

---

The Markdown of https://zigbongo.com/docs/quickstart/php/. Every docs page: https://zigbongo.com/llms.txt
