Skip to content

feat: implement PKPassBundle #155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
186 changes: 186 additions & 0 deletions docs/PKPassBundle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
# PKPassBundle API Documentation

The `PKPassBundle` class allows you to create a bundle of multiple passes, which can be output as a `.pkpasses` file. This is useful when you need to distribute multiple passes together.

## Table of Contents

- [Constructor](#constructor)
- [Bundle Management](#bundle-management)
- [Output Methods](#output-methods)
- [Constants](#constants)

## Constructor

### `__construct()`

Creates a new PKPassBundle instance.

**Example:**
```php
use PKPass\PKPassBundle;

$bundle = new PKPassBundle();
```

## Bundle Management

### `add(PKPass $pass)`

Adds a pass to the bundle.

**Parameters:**
- `$pass` (PKPass): A PKPass instance to add to the bundle

**Throws:** `InvalidArgumentException` if the parameter is not a PKPass instance

**Example:**
```php
use PKPass\PKPass;
use PKPass\PKPassBundle;

// Create individual passes
$pass1 = new PKPass('/path/to/certificate.p12', 'password');
$pass1->setData($passData1);
$pass1->addFile('/path/to/icon1.png');

$pass2 = new PKPass('/path/to/certificate.p12', 'password');
$pass2->setData($passData2);
$pass2->addFile('/path/to/icon2.png');

// Create bundle and add passes
$bundle = new PKPassBundle();
$bundle->add($pass1);
$bundle->add($pass2);
```

## Output Methods

### `save($path)`

Saves the bundle as a `.pkpasses` file to the filesystem.

**Parameters:**
- `$path` (string): File path where the bundle should be saved

**Throws:** `RuntimeException` if the file cannot be written

**Example:**
```php
$bundle->save('/path/to/my-passes.pkpasses');
```

### `output()`

Outputs the bundle as a `.pkpasses` file directly to the browser for download.

This method sets appropriate HTTP headers and streams the file content directly to the browser, then terminates the script with `exit`.

**Headers set:**
- `Content-Type: application/vnd.apple.pkpasses`
- `Content-Disposition: attachment; filename="passes.pkpasses"`
- `Cache-Control: no-cache, no-store, must-revalidate`
- `Pragma: no-cache`

**Throws:** `RuntimeException` if the stream cannot be created

**Example:**
```php
// This will trigger a download in the browser
$bundle->output();
// Script execution stops here
```

## Complete Example

Here's a complete example showing how to create a bundle with multiple passes:

```php
use PKPass\PKPass;
use PKPass\PKPassBundle;

try {
// Create first pass (boarding pass)
$boardingPass = new PKPass('/path/to/certificate.p12', 'password');
$boardingPass->setData([
'description' => 'Flight Ticket',
'formatVersion' => 1,
'organizationName' => 'Airline Inc',
'passTypeIdentifier' => 'pass.com.airline.boarding',
'serialNumber' => 'FLIGHT001',
'teamIdentifier' => 'TEAM123',
'boardingPass' => [
'primaryFields' => [
[
'key' => 'destination',
'label' => 'TO',
'value' => 'SFO'
]
]
]
]);
$boardingPass->addFile('/path/to/flight-icon.png', 'icon.png');

// Create second pass (event ticket)
$eventPass = new PKPass('/path/to/certificate.p12', 'password');
$eventPass->setData([
'description' => 'Concert Ticket',
'formatVersion' => 1,
'organizationName' => 'Music Venue',
'passTypeIdentifier' => 'pass.com.venue.event',
'serialNumber' => 'EVENT001',
'teamIdentifier' => 'TEAM123',
'eventTicket' => [
'primaryFields' => [
[
'key' => 'event',
'label' => 'EVENT',
'value' => 'Rock Concert'
]
]
]
]);
$eventPass->addFile('/path/to/concert-icon.png', 'icon.png');

// Create bundle and add passes
$bundle = new PKPassBundle();
$bundle->add($boardingPass);
$bundle->add($eventPass);

// Save to file
$bundle->save('/path/to/travel-bundle.pkpasses');

// Or output directly to browser
// $bundle->output();

} catch (Exception $e) {
echo 'Error creating bundle: ' . $e->getMessage();
}
```

## Error Handling

The PKPassBundle class can throw several types of exceptions:

- `InvalidArgumentException`: When trying to add something other than a PKPass instance
- `RuntimeException`: When ZIP operations fail or file operations fail

Always wrap bundle operations in try-catch blocks:

```php
try {
$bundle = new PKPassBundle();
$bundle->add($pass1);
$bundle->add($pass2);
$bundle->save('/path/to/bundle.pkpasses');
} catch (InvalidArgumentException $e) {
echo 'Invalid pass object: ' . $e->getMessage();
} catch (RuntimeException $e) {
echo 'Bundle creation failed: ' . $e->getMessage();
}
```

## File Format

The `.pkpasses` file is a ZIP archive containing multiple `.pkpass` files. Each individual pass in the bundle is a complete, signed pass that could be distributed independently. The bundle format allows iOS to import multiple passes at once when the user opens the `.pkpasses` file.

Note that this format is only supported by iOS Safari. No other browsers or platforms support the `.pkpasses` format for direct import into Apple Wallet.
80 changes: 80 additions & 0 deletions examples/bundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

/**
* Simple PKPassBundle example
*
* This demonstrates how to create a bundle of multiple passes
* and output them as a single .pkpasses file.
*/

use PKPass\PKPass;
use PKPass\PKPassBundle;

require('../vendor/autoload.php');

// Create a bundle
$bundle = new PKPassBundle();

// Create first pass - boarding pass
$pass1 = new PKPass('../Certificates.p12', 'password');
$pass1->setData([
'description' => 'Flight to London',
'formatVersion' => 1,
'organizationName' => 'Flight Express',
'passTypeIdentifier' => 'pass.com.includable.pkpass-example',
'serialNumber' => 'FLIGHT001',
'teamIdentifier' => '839X4P2FV8',
'boardingPass' => [
'primaryFields' => [
[
'key' => 'origin',
'label' => 'San Francisco',
'value' => 'SFO',
],
[
'key' => 'destination',
'label' => 'London',
'value' => 'LHR',
],
],
'transitType' => 'PKTransitTypeAir',
],
'barcodes' => [
[
'format' => 'PKBarcodeFormatQR',
'message' => 'Flight-GateF12-ID6643679AH7B',
'messageEncoding' => 'iso-8859-1',
]
],
'backgroundColor' => 'rgb(32,110,247)'
]);
$pass1->addFile('images/icon.png');

// Create second pass - hotel booking
$pass2 = new PKPass('../Certificates.p12', 'password');
$pass2->setData([
'description' => 'Hotel Reservation',
'formatVersion' => 1,
'organizationName' => 'London Hotel',
'passTypeIdentifier' => 'pass.com.includable.pkpass-example',
'serialNumber' => 'HOTEL001',
'teamIdentifier' => '839X4P2FV8',
'generic' => [
'primaryFields' => [
['key' => 'hotel', 'label' => 'Hotel', 'value' => 'London Grand']
],
'secondaryFields' => [
['key' => 'checkin', 'label' => 'Check-in', 'value' => 'Nov 7, 2024']
]
],
'barcodes' => [['format' => 'PKBarcodeFormatQR', 'message' => 'HOTEL001']],
'backgroundColor' => 'rgb(220,20,60)'
]);
$pass2->addFile('images/icon.png');

// Add passes to bundle
$bundle->add($pass1);
$bundle->add($pass2);

// Output the bundle to browser
$bundle->output();
122 changes: 122 additions & 0 deletions src/PKPassBundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<?php

namespace PKPass;

use ZipArchive;

/**
* A bundle of multiple passes, which can be output as a `.pkpasses` file.
*/
class PKPassBundle
{
/**
* @var PKPass[]
*/
private $passes = [];

/**
* @var string|null
*/
private $tempFile = null;

/**
* @var string
*/
private $tempPath;

public function __construct()
{
$this->tempPath = sys_get_temp_dir();
}

/**
* Set the path to the temporary directory.
*
* @param string $path Path to temporary directory
*/
public function setTempPath($path)
{
$this->tempPath = $path;
}

/**
* Add a pass to the bundle.
*
* @param PKPass $pass
*/
public function add(PKPass $pass)
{
if (!($pass instanceof PKPass)) {
throw new \InvalidArgumentException('Expected instance of PKPass.');
}

$this->passes[] = $pass;
}

private function createZip(): ZipArchive
{
if (empty($this->passes)) {
throw new \RuntimeException('Cannot create bundle with no passes. Add at least one pass before creating the bundle.');
}

$zip = new ZipArchive();
$this->tempFile = tempnam($this->tempPath, 'pkpasses');

if ($zip->open($this->tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new \RuntimeException('Could not create zip archive.');
}

$counter = 1;
foreach ($this->passes as $pass) {
$zip->addFromString("pass{$counter}.pkpass", $pass->create(false));
$counter++;
}

if ($zip->close() === false) {
throw new \RuntimeException('Could not close zip archive.');
}

// Re-open the zip to read it
if ($zip->open($this->tempFile) !== true) {
throw new \RuntimeException('Could not reopen zip archive.');
}

return $zip;
}

/**
* Save the bundle as a `.pkpasses` file to the filesystem.
*
* @param string $path
*/
public function save(string $path)
{
$zip = $this->createZip();
$zip->close();

if (@copy($this->tempFile, $path) === false) {
unlink($this->tempFile);
throw new \RuntimeException('Could not write zip archive to file.');
}

unlink($this->tempFile);
}

/**
* Output the bundle as a `.pkpasses` file to the browser.
*/
public function output()
{
$zip = $this->createZip();
$zip->close();

header('Content-Type: application/vnd.apple.pkpasses');
header('Content-Disposition: attachment; filename="passes.pkpasses"');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');

readfile($this->tempFile);
unlink($this->tempFile);
exit;
}
}
Loading