Skip to content

Commit

Permalink
Merge pull request #744 from mollie/feature/add-sessions
Browse files Browse the repository at this point in the history
Add sessions endpoint
  • Loading branch information
sandervanhooft authored Sep 30, 2024
2 parents cdfb298 + 2e741aa commit 0a26175
Show file tree
Hide file tree
Showing 19 changed files with 965 additions and 81 deletions.
5 changes: 4 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ jobs:
extensions: dom, curl, libxml, mbstring, zip
tools: composer:v2
coverage: none
- name: Remove PHP CS Fixer dependency to prevent unnecessary dependency collisions
run: |
composer remove --dev friendsofphp/php-cs-fixer
- name: Install dependencies
run: |
composer update --prefer-dist --no-interaction --no-progress
- name: PHPStan
if: ${{ matrix.php >= 7.3 }}
run: |
composer require "phpstan/phpstan:1.9.2"
composer require "phpstan/phpstan:1.12.5"
vendor/bin/phpstan analyse --no-progress
- name: Execute tests
run: vendor/bin/phpunit --verbose
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"eloquent/liberator": "^2.0||^3.0",
"friendsofphp/php-cs-fixer": "^3.0",
"guzzlehttp/guzzle": "^6.3 || ^7.0",
"phpstan/phpstan": "^1.4",
"phpstan/phpstan": "^1.12",
"phpunit/phpunit": "^8.5 || ^9.5"
},
"suggest": {
Expand Down
1 change: 1 addition & 0 deletions examples/pagination/backwards.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* - paymentRefunds
* - profiles
* - refunds
* - sessions
* - settlementCaptures
* - settlementChargebacks
* - settlementPayments
Expand Down
1 change: 1 addition & 0 deletions examples/pagination/basic_usage.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* - paymentRefunds
* - profiles
* - refunds
* - sessions
* - settlementCaptures
* - settlementChargebacks
* - settlementPayments
Expand Down
22 changes: 22 additions & 0 deletions examples/sessions/cancel-session.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php
/*
* Cancel an session using the Mollie API.
*/

try {
/*
* Initialize the Mollie API library with your API key or OAuth access token.
*/
require "../initialize.php";

/*
* Cancel the session with ID "sess_dfsklg13jO"
*
* See: https://docs.mollie.com/reference/v2/sessions-api/cancel-session
*/
$session = $mollie->sessions->get("sess_dfsklg13jO");

$session->cancel();
} catch (\Mollie\Api\Exceptions\ApiException $e) {
echo "API call failed: " . htmlspecialchars($e->getMessage());
}
53 changes: 53 additions & 0 deletions examples/sessions/create-session.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
/*
* How to create a new session in the Mollie API.
*/

try {
/*
* Initialize the Mollie API library with your API key or OAuth access token.
*/
require "../initialize.php";

/*
* Generate a unique session id for this example. It is important to include this unique attribute
* in the redirectUrl (below) so a proper return page can be shown to the customer.
*/
$sessionId = time();

/*
* Determine the url parts to these example files.
*/
$protocol = isset($_SERVER['HTTPS']) && strcasecmp('off', $_SERVER['HTTPS']) !== 0 ? "https" : "http";
$hostname = $_SERVER['HTTP_HOST'];
$path = dirname($_SERVER['REQUEST_URI'] ?? $_SERVER['PHP_SELF']);

/*
* Session creation parameters.
*
* See: https://docs.mollie.com/reference/v2/sessions-api/create-session
*/
$session = $mollie->sessions->create([
"paymentData" => [
"amount" => [
"value" => "10.00",
"currency" => "EUR",
],
"description" => "Order #12345",
],
"method" => "paypal",
"methodDetails" => [
"checkoutFlow" => "express",
],
"returnUrl" => "{$protocol}://{$hostname}{$path}/shippingSelection.php?order_id={$sessionId}",
"cancelUrl" => "{$protocol}://{$hostname}{$path}/cancel.php?order_id={$sessionId}",
]);

/*
* Send the customer off to complete the payment.
* This request should always be a GET, thus we enforce 303 http response code
*/
header("Location: " . $session->getRedirectUrl(), true, 303);
} catch (\Mollie\Api\Exceptions\ApiException $e) {
echo "API call failed: " . htmlspecialchars($e->getMessage());
}
48 changes: 48 additions & 0 deletions examples/sessions/list-sessions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/*
* List sessions using the Mollie API.
*/


try {
/*
* Initialize the Mollie API library with your API key or OAuth access token.
*/
require "../initialize.php";

/*
* List the most recent sessions
*
* See: https://docs.mollie.com/reference/v2/sessions-api/list-sessions
*/
echo '<ul>';
$latestSessions = $mollie->sessions->page();
printSessions($latestSessions);

$previousSessions = $latestSessions->next();
printSessions($previousSessions);
echo '</ul>';
} catch (\Mollie\Api\Exceptions\ApiException $e) {
echo "API call failed: " . htmlspecialchars($e->getMessage());
}

function printSessions($sessions)
{
if (empty($sessions)) {
return;
}

foreach ($sessions as $session) {
echo '<li><b>Session ' . htmlspecialchars($session->id) . ':</b> (' . htmlspecialchars($session->failedAt) . ')';
echo '<br>Status: <b>' . htmlspecialchars($session->status);
echo '<table border="1"><tr><th>Billed to</th><th>Shipped to</th><th>Total amount</th></tr>';
echo '<tr>';
echo '<td>' . htmlspecialchars($session->shippingAddress->givenName) . ' ' . htmlspecialchars($session->shippingAddress->familyName) . '</td>';
echo '<td>' . htmlspecialchars($session->billingAddress->givenName) . ' ' . htmlspecialchars($session->billingAddress->familyName) . '</td>';
echo '<td>' . htmlspecialchars($session->amount->currency) . str_replace('.', ',', htmlspecialchars($session->amount->value)) . '</td>';
echo '</tr>';
echo '</table>';
echo '<a href="' . $session->getRedirectUrl() . '" target="_blank">Click here to pay</a>';
echo '</li>';
}
}
35 changes: 35 additions & 0 deletions examples/sessions/update-session.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
/*
* How to update an session with the Mollie API
*/

try {
/*
* Initialize the Mollie API library with your API key.
*
* See: https://www.mollie.com/dashboard/developers/api-keys
*/
require "../initialize.php";

$session = $mollie->sessions->get("sess_dfsklg13jO");
$session->billingAddress->organizationName = "Mollie B.V.";
$session->billingAddress->streetAndNumber = "Keizersgracht 126";
$session->billingAddress->city = "Amsterdam";
$session->billingAddress->region = "Noord-Holland";
$session->billingAddress->postalCode = "1234AB";
$session->billingAddress->country = "NL";
$session->billingAddress->title = "Dhr";
$session->billingAddress->givenName = "Piet";
$session->billingAddress->familyName = "Mondriaan";
$session->billingAddress->email = "[email protected]";
$session->billingAddress->phone = "+31208202070";
$session->update();

/*
* Send the customer off to complete the order payment.
* This request should always be a GET, thus we enforce 303 http response code
*/
header("Location: " . $session->getRedirectUrl(), true, 303);
} catch (\Mollie\Api\Exceptions\ApiException $e) {
echo "API call failed: " . htmlspecialchars($e->getMessage());
}
20 changes: 20 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,26 @@ parameters:
count: 1
path: examples/profiles/update-profile.php

-
message: "#^Variable \\$mollie might not be defined\\.$#"
count: 1
path: examples/sessions/cancel-session.php

-
message: "#^Variable \\$mollie might not be defined\\.$#"
count: 1
path: examples/sessions/create-session.php

-
message: "#^Variable \\$mollie might not be defined\\.$#"
count: 1
path: examples/sessions/list-sessions.php

-
message: "#^Variable \\$mollie might not be defined\\.$#"
count: 1
path: examples/sessions/update-session.php

-
message: "#^Variable \\$mollie might not be defined\\.$#"
count: 1
Expand Down
139 changes: 139 additions & 0 deletions src/Endpoints/SessionEndpoint.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php

namespace Mollie\Api\Endpoints;

use Mollie\Api\Exceptions\ApiException;
use Mollie\Api\Resources\LazyCollection;
use Mollie\Api\Resources\Session;
use Mollie\Api\Resources\SessionCollection;

class SessionEndpoint extends CollectionEndpointAbstract
{
protected $resourcePath = "sessions";

/**
* @var string
*/
public const RESOURCE_ID_PREFIX = 'sess_';

/**
* Get the object that is used by this API endpoint. Every API endpoint uses one
* type of object.
*
* @return Session
*/
protected function getResourceObject()
{
return new Session($this->client);
}

/**
* Get the collection object that is used by this API endpoint. Every API
* endpoint uses one type of collection object.
*
* @param int $count
* @param \stdClass $_links
*
* @return SessionCollection
*/
protected function getResourceCollectionObject($count, $_links)
{
return new SessionCollection($this->client, $count, $_links);
}

/**
* Creates a session in Mollie.
*
* @param array $data An array containing details on the session.
* @param array $filters
*
* @return Session
* @throws ApiException
*/
public function create(array $data = [], array $filters = [])
{
return $this->rest_create($data, $filters);
}

/**
* Update a specific Session resource
*
* Will throw a ApiException if the resource id is invalid or the resource cannot be found.
*
* @param string $resourceId
*
* @param array $data
* @return Session
* @throws ApiException
*/
public function update($resourceId, array $data = [])
{
if (empty($resourceId) || strpos($resourceId, self::RESOURCE_ID_PREFIX) !== 0) {
throw new ApiException("Invalid session ID: '{$resourceId}'. A session ID should start with '" . self::RESOURCE_ID_PREFIX . "'.");
}

return parent::rest_update($resourceId, $data);
}

/**
* Retrieve a single session from Mollie.
*
* Will throw a ApiException if the resource id is invalid or the resource cannot
* be found.
*
* @param array $parameters
* @return Session
* @throws ApiException
*/
public function get($resourceId, array $parameters = [])
{
if (empty($resourceId) || strpos($resourceId, self::RESOURCE_ID_PREFIX) !== 0) {
throw new ApiException("Invalid session ID: '{$resourceId}'. A session ID should start with '" . self::RESOURCE_ID_PREFIX . "'.");
}

return parent::rest_read($resourceId, $parameters);
}

/**
* Cancel the given Session.
*
* @param string $resourceId
* @param array $parameters
* @return Session
* @throws ApiException
*/
public function cancel($resourceId, $parameters = [])
{
return $this->rest_delete($resourceId, $parameters);
}

/**
* Retrieves a collection of Sessions from Mollie.
*
* @param string $from The first resource ID you want to include in your list.
* @param int $limit
* @param array $parameters
*
* @return SessionCollection
* @throws ApiException
*/
public function page(?string $from = null, ?int $limit = null, array $parameters = [])
{
return $this->rest_list($from, $limit, $parameters);
}

/**
* Create an iterator for iterating over sessions retrieved from Mollie.
*
* @param string $from The first resource ID you want to include in your list.
* @param int $limit
* @param array $parameters
* @param bool $iterateBackwards Set to true for reverse resource iteration (default is false).
*
* @return LazyCollection
*/
public function iterator(?string $from = null, ?int $limit = null, array $parameters = [], bool $iterateBackwards = false): LazyCollection
{
return $this->rest_iterator($from, $limit, $parameters, $iterateBackwards);
}
}
Loading

0 comments on commit 0a26175

Please sign in to comment.