Add Stripe payment intents support and product subscription flag

Introduced functionality for handling Stripe payment intents, including creation, retrieval, and cancellation. Added a subscription_allowed flag to products for enabling subscription-specific operations. Integrated the necessary backend endpoints, object property updates, and route handling logic.
This commit is contained in:
Jepp9350
2025-04-08 14:11:11 +02:00
parent d76bf03e95
commit e4ec92d66c
9 changed files with 539 additions and 0 deletions
+9
View File
@@ -139,6 +139,7 @@ class response implements response_i
public function getRequestParameter(string $key): mixed
{
$data = [];
// Get the request data if the method is POST, PUT or PATCH
if ($_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'PUT' || $_SERVER['REQUEST_METHOD'] === 'PATCH') {
$data = json_decode(file_get_contents('php://input'), true);
@@ -147,6 +148,14 @@ class response implements response_i
if ($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'DELETE' || $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$data = $_GET;
}
// If the data key is not set, try to get it from the opposite method
if (!array_key_exists($key, $data)) {
if ($_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'PUT' || $_SERVER['REQUEST_METHOD'] === 'PATCH') {
$data = $_GET;
} else {
$data = json_decode(file_get_contents('php://input'), true);
}
}
// Return the data
return $data[$key] ?? null;
}
+8
View File
@@ -9,6 +9,7 @@ require_once WD . '/modules/stripe/endpoints/stripe_endpoint_product.php';
require_once WD . '/modules/stripe/endpoints/stripe_endpoint_prices.php';
require_once WD . '/modules/stripe/endpoints/stripe_endpoint_invoice.php';
require_once WD . '/modules/stripe/endpoints/stripe_endpoint_readers.php';
require_once WD . '/modules/stripe/endpoints/stripe_endpoint_payment_intents.php';
// Require all helper classes
@@ -22,6 +23,7 @@ use Exception;
use interfaces\stripe_i;
use stripe\endpoints\stripe_endpoint_customers;
use stripe\endpoints\stripe_endpoint_invoice;
use stripe\endpoints\stripe_endpoint_payment_intents;
use stripe\endpoints\stripe_endpoint_payment_link;
use stripe\endpoints\stripe_endpoint_prices;
use stripe\endpoints\stripe_endpoint_product;
@@ -70,6 +72,11 @@ class stripe implements stripe_i
* @var stripe_endpoint_readers
*/
public stripe_endpoint_readers $readers;
/**
* Payment intents endpoint
* @var stripe_endpoint_payment_intents
*/
public stripe_endpoint_payment_intents $payment_intents;
/**
* Stripe client
* @var StripeClient
@@ -86,6 +93,7 @@ class stripe implements stripe_i
$this->prices = new stripe_endpoint_prices();
$this->invoice = new stripe_endpoint_invoice();
$this->readers = new stripe_endpoint_readers();
$this->payment_intents = new stripe_endpoint_payment_intents();
}
/**
@@ -0,0 +1,132 @@
<?php
namespace stripe\endpoints;
use Exception;
use Stripe\Collection;
use Stripe\Exception\ApiErrorException;
use Stripe\PaymentIntent;
use traits\stripe_endpoint_t;
class stripe_endpoint_payment_intents
{
use stripe_endpoint_t;
/**
* Get all readers
* @return Collection
* @throws ApiErrorException
* @throws Exception
*/
public function list(): Collection
{
return self::getClient()->paymentIntents->all();
}
/**
* Get a payment intent by ID
* @param string $id
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function get(string $id): PaymentIntent
{
return self::getClient()->paymentIntents->retrieve($id);
}
/**
* Create a payment intent
* @param float $total_net_amount
* @param array $data
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function create(float $total_net_amount, array $data = []): PaymentIntent
{
$default_data = [
'amount' => $total_net_amount,
'currency' => 'dkk',
'payment_method_types' => ['card_present'],
'capture_method' => 'manual',
];
$data = array_merge($default_data, $data);
return self::getClient()->paymentIntents->create($data);
}
/**
* Update a payment intent
* @param string $id
* @param array $data
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function update(string $id, array $data): PaymentIntent
{
return self::getClient()->paymentIntents->update($id, $data);
}
/**
* Cancel a payment intent
* @param string $id
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function cancel(string $id): PaymentIntent
{
return self::getClient()->paymentIntents->cancel($id);
}
/**
* Process a payment intent
* @param string $id
* @param array $data
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function process(string $id, array $data): PaymentIntent
{
$payment_intent = self::getClient()->paymentIntents->retrieve($id);
if ($payment_intent->status == 'requires_confirmation') {
return self::confirm($id, $data);
} elseif ($payment_intent->status == 'requires_capture') {
return self::capture($id, $data);
} elseif ($payment_intent->status == 'requires_action') {
return self::confirm($id, $data);
} else {
throw new Exception('Payment intent is not in a state to be processed');
}
}
/**
* Confirm a payment intent
* @param string $id
* @param array $data
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function confirm(string $id, array $data): PaymentIntent
{
return self::getClient()->paymentIntents->confirm($id, $data);
}
/**
* Capture a payment intent
* @param string $id
* @param array $data
* @return PaymentIntent
* @throws ApiErrorException
* @throws Exception
*/
public function capture(string $id, array $data): PaymentIntent
{
return self::getClient()->paymentIntents->capture($id, $data);
}
}
@@ -155,4 +155,33 @@ class stripe_endpoint_readers
return self::getClient()->terminal->readers->delete($reader_id);
}
/**
* Send a payment intent to a reader
* @param string $reader
* @param string $id
* @return Reader
* @throws Exception
*/
public function sendPaymentIntent(string $reader, string $id): Reader
{
return self::getClient()->terminal->readers->processPaymentIntent(
$reader,
[
'payment_intent' => $id
]
);
}
/**
* Send a cancel action to a reader
* @throws ApiErrorException
* @throws Exception
*/
public function sendCancelPaymentIntent(string $reader): Reader
{
return self::getClient()->terminal->readers->cancelAction(
$reader
);
}
}
@@ -305,4 +305,19 @@ class departments_o extends db
}
return $tmp;
}
/**
* Check if the Stripe is configured for the department
* @note This is a link to the department_variables_o::isSet(stripe_terminal_location) method
* @return bool true If the Stripe is configured
* @throws Exception If the department is not selected
*/
public function isStripeConfigured(): bool
{
self::requireSelected();
if ($this->variables->isSet('stripe_terminal_location')) {
return true;
}
return false;
}
}
@@ -25,6 +25,11 @@ class products_o extends db
* @var object_property
*/
public object_property $price;
/**
* Whether the product is allowed for subscription
* @var object_property $subscription_allowed
*/
public object_property $subscription_allowed;
/**
* The category the product belongs to
* @var object_property
@@ -89,6 +94,7 @@ class products_o extends db
$this->name = new object_property($this->table, $this->id, 'name', 'string', true);
$this->description = new object_property($this->table, $this->id, 'description', 'string', false);
$this->price = new object_property($this->table, $this->id, 'price', 'int', true);
$this->subscription_allowed = new object_property($this->table, $this->id, 'subscription_allowed', 'bool', false);
$this->category = new object_property($this->table, $this->id, 'category', 'string', true);
$this->piktogram = new object_property($this->table, $this->id, 'piktogram', 'string', false);
$this->economic_product_id = new object_property($this->table, $this->id, 'economic_product_id', 'int', false);
@@ -177,6 +183,7 @@ class products_o extends db
'name' => (string)$this->name->value(),
'description' => (string)$this->description->value(),
'price' => (int)$this->price->value(),
'subscription_allowed' => (int)$this->subscription_allowed->value(),
'category' => $this->category->value(),
'piktogram' => $this->piktogram->value(),
'economic_product_id' => $this->economic_product_id->value(),
@@ -0,0 +1,132 @@
<?php
namespace objects;
use classes\db;
use classes\object_property;
use classes\stripe;
use Exception;
use traits\db_object_t;
class stripe_payment_intents_o extends db
{
use db_object_t;
public object_property $order_id;
public object_property $payment_intent_id;
public object_property $client_secret;
public object_property $data;
public object_property $reader_id;
public object_property $tax_percentage;
public function structure(): void
{
$this->setTable('stripe_payment_intents');
}
/**
* Add a new payment intent
* @param int $order_id The id of the order
* @param string $payment_intent_id The id of the payment intent
* @param string $client_secret The client secret of the payment intent
* @param mixed $data The data to be added
* @param int|null $tax_percentage The tax percentage to be added
* @return void
* @throws Exception If the object was not created successfully
*/
public function add(int $order_id, string $payment_intent_id, string $client_secret, mixed $data = null, int $tax_percentage = null): void
{
// Convert the data to a JSON string (If it's an object or array)
if (is_object($data) || is_array($data)) {
$data = json_encode($data);
}
$tmp_id = self::add_object([
'order_id' => $order_id,
'payment_intent_id' => $payment_intent_id,
'client_secret' => $client_secret,
'data' => $data,
'tax_percentage' => ($tax_percentage !== null) ? (int)$tax_percentage : 0,
]);
$this->id = $tmp_id;
self::getObjectProperties();
self::objectChanged();
}
public function getObjectProperties(): void
{
$this->order_id = new object_property($this->table, $this->id, 'order_id', 'int', false);
$this->payment_intent_id = new object_property($this->table, $this->id, 'payment_intent_id', 'string', false);
$this->client_secret = new object_property($this->table, $this->id, 'client_secret', 'string', false);
$this->data = new object_property($this->table, $this->id, 'data', 'string', false);
$this->reader_id = new object_property($this->table, $this->id, 'reader_id', 'int', false);
$this->tax_percentage = new object_property($this->table, $this->id, 'tax_percentage', 'int', false);
}
public function objectChanged(): void
{
//TODO: Add cache invalidation
}
/**
* Check if an order has a payment intent
* @param int $order_id The id of the order
* @return bool True if the order has a payment intent, false otherwise
*/
public function doesOrderHavePaymentIntent(int $order_id): bool
{
return self::countRowsWhere([
'order_id' => $order_id,
]) > 0;
}
/**
* Get the payment intent id of an order
* @param int $order_id The id of the order
* @return self
* @throws Exception If the object was not selected
*/
public function selectOrderPaymentIntent(int $order_id): self
{
$tmp = self::getFieldsWhere([
'order_id' => $order_id,
],
['id']);
if (count($tmp) > 0) {
$this->id = $tmp[0]['id'];
self::getObjectProperties();
return $this;
} else {
throw new Exception('No payment intent found for order id: ' . $order_id);
}
}
/**
* There's no need to keep track of when the payment intent was created
* so we just forcefully delete it.
* @throws Exception If the object was not selected
* @throws Exception If the object was not deleted successfully
*/
public function delete(): void
{
self::requireSelected();
self::cancelPaymentIntent();
self::deletePermanently();
}
/**
* Cancel the payment intent on the reader
* @throws Exception If the object was not selected
* @throws Exception If the object was not deleted successfully
*/
public function cancelPaymentIntent(): void
{
self::requireSelected();
// If a reader id is set, cancel the payment intent on the reader
if (!empty($this->reader_id->value())) {
$stripe = new stripe();
$stripe->readers->sendCancelPaymentIntent($this->reader_id->value(), $this->payment_intent_id->value());
$this->reader_id->nullify();
self::objectChanged();
}
}
}
+203
View File
@@ -4,12 +4,14 @@ namespace routes;
use classes\authentication;
use classes\response;
use classes\stripe;
use objects\collected_order_invoices_o;
use objects\departments_o;
use objects\economic_module_orders;
use objects\logs_o;
use objects\orders_o;
use objects\stripe_module_orders_o;
use objects\stripe_payment_intents_o;
use objects\users_o;
use traits\route_t;
@@ -261,6 +263,207 @@ class ordersRoute
'mark_order_as_completed' => 'Mark an order as completed'
]
);
$this->post('/orders/module/stripe/payment_intent', function () {
// Require the user to be logged in
global $response;
$this->requirePermission('charge_order_stripe');
// Get the user object
$user = (new authentication())->get_user();
// Check if the request was successful
if ($user) {
// Get the post data
$data = json_decode(file_get_contents('php://input'), true);
// Check if the required fields are set
if (!isset($data['id'])) {
$response->error('ID is required', 400);
}
// Get the current order
$order = (new orders_o())->getOrderById((int)$data['id']);
// Check if the order exists
if (!$order->exists()) {
$response->error('Order not found', 400);
}
// Get the department
$department = (new departments_o())->selectId((int)$order->department_id->value());
// Check if the department is configured for Stripe payments
if (!$department->isStripeConfigured()) {
$response->error('Department is not configured for Stripe payments', 400);
}
// Check if the reader is set
if (!isset($data['reader'])) {
$response->error('Reader ID is required', 400);
}
// Get the tax percentage (if any)
$tax_percentage = (isset($data['tax_percentage'])) ? (int)$data['tax_percentage'] : null;
// Check if the tax percentage is valid
if ($tax_percentage !== null && ($tax_percentage < 0 || $tax_percentage > 100)) {
$response->error('Invalid tax percentage', 400);
}
function addTaxNetAmount($net_amount, $tax_percentage): float
{
// Check if the tax percentage is above 0
if (empty($tax_percentage) || $tax_percentage <= 0) {
return $net_amount;
}
return $net_amount + ($net_amount * ($tax_percentage / 100));
}
// Get the Stripe payment intent
$stripe = new stripe();
$paymentIntent = $stripe->payment_intents->create(
addTaxNetAmount(
(float)$order->getNetAmount() * 100,
$tax_percentage ?? 0
),
[
'description' => 'Order ID: ' . $order->id,
'metadata' => [
'order_id' => $order->id,
'customer_id' => $order->customer_id->value(),
'department_id' => $order->department_id->value(),
'tax_percentage' => $tax_percentage ?? 0,
],
'payment_method_types' => ['card_present'],
'capture_method' => 'manual',
]
);
// Validate the payment intent
try {
$stripe->payment_intents->get($paymentIntent->id);
} catch (\Stripe\Exception\InvalidRequestException $e) {
$response->error('Payment intent not found', 400);
}
// Set the payment intent ID in the order
$stripe_payment_intents = new stripe_payment_intents_o();
$stripe_payment_intents->add(
(int)$order->id,
$paymentIntent->id,
$paymentIntent->client_secret,
$paymentIntent->toJSON()
);
// Send the payment intent to the reader
$stripe->readers->sendPaymentIntent(
$data['reader'],
$paymentIntent->id,
);
// Set the reader on the stripe payment intent
$stripe_payment_intents->reader_id->set($data['reader']);
// Log the incident
(new logs_o())->add('orders', $order->department_id->value(), 1, $user->id, 'CHARGE_ORDER', 'Successfully charged an order (ID: ' . $data['id'] . ')');
$response->success([
'payment_intent' => $paymentIntent->id,
'client_secret' => $paymentIntent->client_secret,
]);
} else {
// Log the incident
(new logs_o())->add('orders', 'global', 1, 0, 'CHARGE_ORDER', 'No user found, or invalid session');
// Return an error
$response->error('Invalid session', 400);
}
},
[
'charge_order' => 'Charge an order'
]
);
$this->get('/orders/module/stripe/payment_intent', function () {
// Require the user to be logged in
global $response;
$this->requirePermission('get_payment_intent');
// Get the user object
$user = (new authentication())->get_user();
// Check if the request was successful
if ($user) {
// Get the post data
self::requireParameters([
'id'
]);
// Check if the required fields are set
$id = self::getParameter('id');
if (!isset($id)) {
$response->error('ID is required', 400);
}
// Get the current order
$order = (new orders_o())->getOrderById((int)$id);
// Check if the order exists
if (!$order->exists()) {
$response->error('Order not found', 400);
}
// Check if the order has a payment intent
$stripe_payment_intents = new stripe_payment_intents_o();
if (!$stripe_payment_intents->doesOrderHavePaymentIntent((int)$order->id)) {
$response->error('Order does not have a payment intent', 400);
}
$stripe_payment_intents->selectOrderPaymentIntent((int)$order->id);
// Get the Stripe payment intent
$stripe = new stripe();
try {
$payment_intent = $stripe->payment_intents->get(
$stripe_payment_intents->payment_intent_id->value()
);
} catch (\Stripe\Exception\InvalidRequestException $e) {
$response->error('Payment intent not found', 400);
}
$response->success(
$payment_intent->toJSON()
);
} else {
// Log the incident
(new logs_o())->add('orders', 'global', 1, 0, 'GET_PAYMENT_INTENT', 'No user found, or invalid session');
// Return an error
$response->error('Invalid session', 400);
}
},
[
'get_payment_intent' => 'Get a payment intent'
]
);
$this->delete('/orders/module/stripe/payment_intent', function () {
// Require the user to be logged in
global $response;
$this->requirePermission('delete_payment_intent');
// Get the user object
$user = (new authentication())->get_user();
// Check if the request was successful
if ($user) {
// Get the data
self::requireParameters([
'id'
]);
$id = self::fromRequest('id');
// Get the current order
$order = (new orders_o())->getOrderById((int)$id);
// Check if the order exists
if (!$order->exists()) {
$response->error('Order not found', 400);
}
// Check if the order has a payment intent
$stripe_payment_intents = new stripe_payment_intents_o();
if (!$stripe_payment_intents->doesOrderHavePaymentIntent((int)$order->id)) {
$response->error('Order does not have a payment intent', 400);
}
$stripe_payment_intents->selectOrderPaymentIntent((int)$order->id);
try {
$stripe_payment_intents->delete();
// Log the incident
(new logs_o())->add('orders', $order->department_id->value(), 1, $user->id, 'DELETE_PAYMENT_INTENT', 'Successfully deleted a payment intent (ID: ' . $id . ')');
// Return a success message
$response->success(['message' => 'Payment intent deleted successfully']);
} catch (\Stripe\Exception\InvalidRequestException $e) {
$response->error('Payment intent not found', 400);
}
} else {
// Log the incident
(new logs_o())->add('orders', 'global', 1, 0, 'DELETE_PAYMENT_INTENT', 'No user found, or invalid session');
// Return an error
$response->error('Invalid session', 400);
}
});
}
/**
@@ -22,6 +22,7 @@ class productsRoute
'name' => (string)$product['name'],
'description' => (string)$product['description'],
'price' => (int)$product['price'],
'subscription_allowed' => (boolean)$product['subscription_allowed'],
'category' => (int)$product['category'],
'piktogram' => (string)$product['piktogram'],
'economic_product_id' => (int)$product['economic_product_id'],
@@ -174,6 +175,9 @@ class productsRoute
if (self::isParametersSet(['price'])) {
$product->price->set($response->getRequestParameter('price'));
}
if (self::isParametersSet(['subscription_allowed'])) {
$product->subscription_allowed->set($response->getRequestParameter('subscription_allowed') ? 1 : 0);
}
if (self::isParametersSet(['category'])) {
$product->category->set($response->getRequestParameter('category') ?? '');
}