Auto commit: 2025-12-18T10:12:51.762Z

This commit is contained in:
Flatlogic Bot 2025-12-18 10:12:51 +00:00
parent fda8a0a84a
commit 840b2b94ca
81 changed files with 8050 additions and 0 deletions

7
admin/dashboard.php Normal file
View File

@ -0,0 +1,7 @@
<?php require_once 'includes/header.php'; ?>
<h2>Dashboard</h2>
<p>Welcome, <?php echo htmlspecialchars($_SESSION['admin_email']); ?>!</p>
<p>This is the protected admin area. From here you can manage products, content, and settings.</p>
<?php require_once 'includes/footer.php'; ?>

View File

@ -0,0 +1,4 @@
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

45
admin/includes/header.php Normal file
View File

@ -0,0 +1,45 @@
<?php
session_start();
// If user is not logged in, redirect to the login page
if (!isset($_SESSION['admin_id'])) {
header('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Verras Portal - Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/admin/dashboard.php">Verras Portal</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="/admin/dashboard.php">Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/admin/products/index.php">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/admin/settings/index.php">Settings</a>
</li>
</ul>
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="/admin/logout.php">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container mt-4">

90
admin/index.php Normal file
View File

@ -0,0 +1,90 @@
<?php
session_start();
// If user is already logged in, redirect to the dashboard
if (isset($_SESSION['admin_id'])) {
header('Location: dashboard.php');
exit;
}
require_once '../includes/Database.php';
$error_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
$error_message = 'Please enter both email and password.';
} else {
try {
$db = Database::getInstance();
$conn = $db->getConnection();
$stmt = $conn->prepare("SELECT * FROM admins WHERE email = :email");
$stmt->bindParam(':email', $email);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
if ($admin && password_verify($password, $admin['password_hash'])) {
// Password is correct, start a new session
session_regenerate_id();
$_SESSION['admin_id'] = $admin['id'];
$_SESSION['admin_email'] = $admin['email'];
header('Location: dashboard.php');
exit;
} else {
$error_message = 'Invalid email or password.';
}
} catch (PDOException $e) {
$error_message = 'Database error: ' . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Verras Portal - Admin Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f8f9fa;
}
.login-container {
max-width: 400px;
padding: 2rem;
border: 1px solid #dee2e6;
border-radius: 0.5rem;
background-color: #fff;
}
</style>
</head>
<body>
<div class="login-container">
<h2 class="text-center mb-4">Admin Login</h2>
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<form action="index.php" method="POST">
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary w-100">Login</button>
</form>
</div>
</body>
</html>

6
admin/logout.php Normal file
View File

@ -0,0 +1,6 @@
<?php
session_start();
session_unset();
session_destroy();
header('Location: index.php');
exit;

107
admin/products/edit.php Normal file
View File

@ -0,0 +1,107 @@
<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
header('Location: /admin/index.php');
exit;
}
require_once __DIR__ . '../../../includes/Database.php';
require_once __DIR__ . '../includes/header.php';
$db = Database::getInstance();
$conn = $db->getConnection();
$product_id = $_GET['id'] ?? null;
$product = null;
$name_translations = ['en' => '', 'es' => ''];
$description_translations = ['en' => '', 'es' => ''];
if ($product_id) {
$stmt = $conn->prepare("SELECT * FROM products WHERE id = :id");
$stmt->bindParam(':id', $product_id);
$stmt->execute();
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if ($product) {
$name_translations = json_decode($product['name_translations'], true);
$description_translations = json_decode($product['description_translations'], true);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sku = $_POST['sku'];
$price = $_POST['price'];
$image_url = $_POST['image_url'];
$name_translations_json = json_encode($_POST['name_translations']);
$description_translations_json = json_encode($_POST['description_translations']);
if ($product_id) {
// Update existing product
$stmt = $conn->prepare("UPDATE products SET sku = :sku, name_translations = :name, description_translations = :description, price = :price, image_url = :image_url WHERE id = :id");
$stmt->bindParam(':id', $product_id);
} else {
// Insert new product
$stmt = $conn->prepare("INSERT INTO products (sku, name_translations, description_translations, price, image_url) VALUES (:sku, :name, :description, :price, :image_url)");
}
$stmt->bindParam(':sku', $sku);
$stmt->bindParam(':name', $name_translations_json);
$stmt->bindParam(':description', $description_translations_json);
$stmt->bindParam(':price', $price);
$stmt->bindParam(':image_url', $image_url);
if ($stmt->execute()) {
header('Location: index.php');
exit;
} else {
$error = "Error saving product.";
}
}
?>
<div class="container mt-4">
<h1><?php echo $product_id ? 'Edit Product' : 'Add New Product'; ?></h1>
<?php if (isset($error)): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<form action="edit.php<?php echo $product_id ? '?id=' . $product_id : ''; ?>" method="POST">
<div class="mb-3">
<label for="sku" class="form-label">SKU</label>
<input type="text" class="form-control" id="sku" name="sku" value="<?php echo htmlspecialchars($product['sku'] ?? ''); ?>" required>
</div>
<div class="mb-3">
<label for="name_en" class="form-label">Name (English)</label>
<input type="text" class="form-control" id="name_en" name="name_translations[en]" value="<?php echo htmlspecialchars($name_translations['en'] ?? ''); ?>" required>
</div>
<div class="mb-3">
<label for="name_es" class="form-label">Name (Spanish)</label>
<input type="text" class="form-control" id="name_es" name="name_translations[es]" value="<?php echo htmlspecialchars($name_translations['es'] ?? ''); ?>">
</div>
<div class="mb-3">
<label for="desc_en" class="form-label">Description (English)</label>
<textarea class="form-control" id="desc_en" name="description_translations[en]" rows="3"><?php echo htmlspecialchars($description_translations['en'] ?? ''); ?></textarea>
</div>
<div class="mb-3">
<label for="desc_es" class="form-label">Description (Spanish)</label>
<textarea class="form-control" id="desc_es" name="description_translations[es]" rows="3"><?php echo htmlspecialchars($description_translations['es'] ?? ''); ?></textarea>
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" step="0.01" class="form-control" id="price" name="price" value="<?php echo htmlspecialchars($product['price'] ?? '0.00'); ?>" required>
</div>
<div class="mb-3">
<label for="image_url" class="form-label">Image URL</label>
<input type="text" class="form-control" id="image_url" name="image_url" value="<?php echo htmlspecialchars($product['image_url'] ?? ''); ?>">
</div>
<button type="submit" class="btn btn-primary">Save Product</button>
<a href="index.php" class="btn btn-secondary">Cancel</a>
</form>
</div>
<?php
require_once __DIR__ . '../includes/footer.php';
?>

74
admin/products/index.php Normal file
View File

@ -0,0 +1,74 @@
<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
header('Location: /admin/index.php');
exit;
}
require_once __DIR__ . '../../../includes/Database.php';
require_once __DIR__ . '../includes/header.php';
$db = Database::getInstance();
$conn = $db->getConnection();
// Handle Delete
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
$stmt = $conn->prepare("DELETE FROM products WHERE id = :id");
$stmt->bindParam(':id', $_GET['id']);
$stmt->execute();
echo '<div class="alert alert-success">Product deleted successfully!</div>';
}
// Fetch all products
$products_stmt = $conn->query("SELECT * FROM products ORDER BY created_at DESC");
$products = $products_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="container mt-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1>Product Management</h1>
<a href="edit.php" class="btn btn-primary">Add New Product</a>
</div>
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>SKU</th>
<th>Name</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if (count($products) > 0): ?>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo htmlspecialchars($product['id']); ?></td>
<td><?php echo htmlspecialchars($product['sku']); ?></td>
<td>
<?php
$name_translations = json_decode($product['name_translations'], true);
echo htmlspecialchars($name_translations['en'] ?? 'N/A');
?>
</td>
<td>$<?php echo htmlspecialchars(number_format($product['price'], 2)); ?></td>
<td>
<a href="edit.php?id=<?php echo $product['id']; ?>" class="btn btn-sm btn-warning">Edit</a>
<a href="index.php?action=delete&id=<?php echo $product['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?');">Delete</a>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="5" class="text-center">No products found.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<?php
require_once __DIR__ . '../includes/footer.php';
?>

60
admin/settings/index.php Normal file
View File

@ -0,0 +1,60 @@
<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
header('Location: /admin/index.php');
exit;
}
require_once __DIR__ . '/../../includes/Database.php';
$db = Database::getInstance();
$connection = $db->getConnection();
$settings = [];
$result = $connection->query("SELECT * FROM settings");
while ($row = $result->fetch_assoc()) {
$settings[$row['key_name']] = $row['key_value'];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$stripe_secret_key = $_POST['stripe_secret_key'] ?? '';
$stripe_publishable_key = $_POST['stripe_publishable_key'] ?? '';
$stmt = $connection->prepare("INSERT INTO settings (key_name, key_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE key_value = VALUES(key_value)");
$key_name_secret = 'stripe_secret_key';
$stmt->bind_param("ss", $key_name_secret, $stripe_secret_key);
$stmt->execute();
$key_name_publishable = 'stripe_publishable_key';
$stmt->bind_param("ss", $key_name_publishable, $stripe_publishable_key);
$stmt->execute();
$stmt->close();
header('Location: /admin/settings/index.php?success=1');
exit;
}
include __DIR__ . '/../includes/header.php';
?>
<div class="container mt-4">
<h2>Settings</h2>
<?php if (isset($_GET['success'])): ?>
<div class="alert alert-success">Settings saved successfully.</div>
<?php endif; ?>
<form method="POST">
<div class="form-group">
<label for="stripe_secret_key">Stripe Secret Key</label>
<input type="text" class="form-control" id="stripe_secret_key" name="stripe_secret_key" value="<?php echo htmlspecialchars($settings['stripe_secret_key'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="stripe_publishable_key">Stripe Publishable Key</label>
<input type="text" class="form-control" id="stripe_publishable_key" name="stripe_publishable_key" value="<?php echo htmlspecialchars($settings['stripe_publishable_key'] ?? ''); ?>">
</div>
<button type="submit" class="btn btn-primary">Save Settings</button>
</form>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>

View File

@ -0,0 +1,92 @@
<?php
header('Content-Type: application/json');
// Check for Composer autoloader
if (!file_exists(__DIR__ . '/../../vendor/autoload.php')) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Error: Stripe SDK not found. Please install it by running "composer require stripe/stripe-php" in your terminal.'
]);
exit;
}
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../includes/Database.php';
// Get DB connection
$db = Database::getInstance();
$connection = $db->getConnection();
// Fetch Stripe secret key from settings
$stripe_secret_key = '';
$result = $connection->query("SELECT key_value FROM settings WHERE key_name = 'stripe_secret_key'");
if ($row = $result->fetch_assoc()) {
$stripe_secret_key = $row['key_value'];
}
if (empty($stripe_secret_key)) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Stripe secret key is not configured. Please set it in the admin settings.'
]);
exit;
}
\Stripe\Stripe::setApiKey($stripe_secret_key);
// Get the request body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if (!$json_obj || !isset($json_obj->product_id)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Invalid request. Product ID is missing.']);
exit;
}
$product_id = filter_var($json_obj->product_id, FILTER_VALIDATE_INT);
if ($product_id === false) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Invalid Product ID.']);
exit;
}
// Fetch product price from the database
$stmt = $connection->prepare("SELECT price FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
http_response_code(404);
echo json_encode(['success' => false, 'message' => 'Product not found.']);
exit;
}
$product = $result->fetch_assoc();
$price = $product['price'];
// Create a PaymentIntent
try {
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $price * 100, // Amount in cents
'currency' => 'usd', // or get from settings/request
]);
echo json_encode([
'success' => true,
'clientSecret' => $paymentIntent->client_secret
]);
} catch (\Stripe\Exception\ApiErrorException $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Failed to create Payment Intent.',
'error' => $e->getMessage()
]);
}

58
api/products/index.php Normal file
View File

@ -0,0 +1,58 @@
<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../db/config.php';
try {
$db = Database::getInstance();
$pdoconn = $db->getConnection();
// Fetch all products with their translations
$stmt = $pdoconn->prepare("
SELECT
p.id,
p.sku,
p.price,
p.stock,
p.created_at,
p.updated_at,
pt.language_code,
l.name as language_name,
pt.name,
pt.description
FROM products p
JOIN product_translations pt ON p.id = pt.product_id
JOIN languages l ON pt.language_code = l.code
ORDER BY p.id, l.id
");
$stmt->execute();
$productsData = $stmt->fetchAll(PDO::FETCH_ASSOC);
$products = [];
foreach ($productsData as $row) {
$productId = $row['id'];
if (!isset($products[$productId])) {
$products[$productId] = [
'id' => (int)$productId,
'sku' => $row['sku'],
'price' => (float)$row['price'],
'stock' => (int)$row['stock'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
'translations' => []
];
}
$products[$productId]['translations'][] = [
'language_code' => $row['language_code'],
'language_name' => $row['language_name'],
'name' => $row['name'],
'description' => $row['description']
];
}
echo json_encode(['success' => true, 'data' => array_values($products)]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'An internal server error occurred.']);
}

5
composer.json Normal file
View File

@ -0,0 +1,5 @@
{
"require": {
"stripe/stripe-php": "^1.8"
}
}

69
composer.lock generated Normal file
View File

@ -0,0 +1,69 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "7ddc6309b099a518705cc62a6091e848",
"packages": [
{
"name": "stripe/stripe-php",
"version": "v1.8.0",
"source": {
"type": "git",
"url": "https://github.com/stripe/stripe-php.git",
"reference": "5eba614baf4adefffdd59d196679a16d7baf70da"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/stripe/stripe-php/zipball/5eba614baf4adefffdd59d196679a16d7baf70da",
"reference": "5eba614baf4adefffdd59d196679a16d7baf70da",
"shasum": ""
},
"require": {
"ext-curl": "*",
"php": ">=5.2"
},
"require-dev": {
"vierbergenlars/simpletest": "*"
},
"type": "library",
"autoload": {
"classmap": [
"lib/Stripe/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Stripe and contributors",
"homepage": "https://github.com/stripe/stripe-php/contributors"
}
],
"description": "Stripe PHP Library",
"homepage": "https://stripe.com/",
"keywords": [
"api",
"payment processing",
"stripe"
],
"support": {
"issues": "https://github.com/stripe/stripe-php/issues",
"source": "https://github.com/stripe/stripe-php/tree/transfers-recipients"
},
"time": "2013-04-12T18:56:41+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {},
"platform-dev": {},
"plugin-api-version": "2.9.0"
}

BIN
composer.phar Executable file

Binary file not shown.

108
db/schema.sql Normal file
View File

@ -0,0 +1,108 @@
-- Verras Portal SQL Schema
-- All tables use InnoDB engine for transaction support and foreign key constraints.
-- Table for admin users
CREATE TABLE IF NOT EXISTS `admins` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`email` VARCHAR(255) NOT NULL UNIQUE,
`password_hash` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- Insert default admin user (password: admin)
INSERT INTO `admins` (`email`, `password_hash`) VALUES ('admin@example.com', '$2y$10$9JERAeTYWKsOhAujmqRqHOOxGZBwVFWRgj8kMIGXs4wEVxW.ogr5C')
ON DUPLICATE KEY UPDATE `password_hash`=`password_hash`;
-- Table for external stores and their API keys
CREATE TABLE IF NOT EXISTS `stores` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`api_key` VARCHAR(255) NOT NULL UNIQUE,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- Table for supported languages
CREATE TABLE IF NOT EXISTS `languages` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`code` VARCHAR(10) NOT NULL UNIQUE,
`name` VARCHAR(50) NOT NULL
) ENGINE=InnoDB;
-- Table for products
CREATE TABLE IF NOT EXISTS `products` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`sku` VARCHAR(100) NOT NULL UNIQUE,
`price` DECIMAL(10, 2) NOT NULL,
`image_url` VARCHAR(2048),
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- Table for product translations
CREATE TABLE IF NOT EXISTS `product_translations` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`product_id` INT NOT NULL,
`language_code` VARCHAR(10) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`description` TEXT,
UNIQUE KEY `product_lang_unique` (`product_id`, `language_code`),
FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`language_code`) REFERENCES `languages`(`code`) ON DELETE CASCADE
) ENGINE=InnoDB;
-- Table for general content (banners, about us, etc.)
CREATE TABLE IF NOT EXISTS `content` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`slug` VARCHAR(100) NOT NULL UNIQUE,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- Table for content translations
CREATE TABLE IF NOT EXISTS `content_translations` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`content_id` INT NOT NULL,
`language_code` VARCHAR(10) NOT NULL,
`content_text` TEXT,
UNIQUE KEY `content_lang_unique` (`content_id`, `language_code`),
FOREIGN KEY (`content_id`) REFERENCES `content`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`language_code`) REFERENCES `languages`(`code`) ON DELETE CASCADE
) ENGINE=InnoDB;
-- Table for orders
CREATE TABLE IF NOT EXISTS `orders` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`store_id` INT NOT NULL,
`status` ENUM('pending', 'succeeded', 'failed') NOT NULL DEFAULT 'pending',
`stripe_payment_intent_id` VARCHAR(255) UNIQUE,
`total_amount` DECIMAL(10, 2) NOT NULL,
`currency` VARCHAR(10) NOT NULL,
`customer_details` JSON,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (`store_id`) REFERENCES `stores`(`id`) ON DELETE RESTRICT
) ENGINE=InnoDB;
-- Table for items within an order
CREATE TABLE IF NOT EXISTS `order_items` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`order_id` INT NOT NULL,
`product_id` INT NOT NULL,
`quantity` INT NOT NULL,
`price_at_purchase` DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (`order_id`) REFERENCES `orders`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE RESTRICT
) ENGINE=InnoDB;
-- Table for application settings (e.g., Stripe keys)
CREATE TABLE IF NOT EXISTS `settings` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`key_name` VARCHAR(255) NOT NULL UNIQUE,
`key_value` TEXT,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- Insert default languages
INSERT INTO `languages` (`code`, `name`) VALUES ('en', 'English'), ('es', 'Spanish')
ON DUPLICATE KEY UPDATE `name`=`name`;

47
includes/Database.php Normal file
View File

@ -0,0 +1,47 @@
<?php
class Database {
private static $instance = null;
private $conn;
private function __construct() {
// Database configuration is loaded from db/config.php
require_once __DIR__ . '/../db/config.php';
$host = getenv('DB_HOST') ?: '127.0.0.1';
$db = getenv('DB_NAME');
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->conn = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
// In a real app, you'd log this error and show a generic message
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->conn;
}
// Prevent cloning and unserialization
private function __clone() { }
public function __wakeup() { }
}

22
vendor/autoload.php vendored Normal file
View File

@ -0,0 +1,22 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
throw new RuntimeException($err);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit40aa654f2e66c20881ae0572fe987a10::getLoader();

579
vendor/composer/ClassLoader.php vendored Normal file
View File

@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}

396
vendor/composer/InstalledVersions.php vendored Normal file
View File

@ -0,0 +1,396 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to
* @internal
*/
private static $selfDir = null;
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool
*/
private static $installedIsLocalDir;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
// so we have to assume it does not, and that may result in duplicate data being returned when listing
// all installed packages for example
self::$installedIsLocalDir = false;
}
/**
* @return string
*/
private static function getSelfDir()
{
if (self::$selfDir === null) {
self::$selfDir = strtr(__DIR__, '\\', '/');
}
return self::$selfDir;
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
$copiedLocalDir = false;
if (self::$canGetVendors) {
$selfDir = self::getSelfDir();
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
$vendorDir = strtr($vendorDir, '\\', '/');
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
self::$installedByVendor[$vendorDir] = $required;
$installed[] = $required;
if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
self::$installed = $required;
self::$installedIsLocalDir = true;
}
}
if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
$copiedLocalDir = true;
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array() && !$copiedLocalDir) {
$installed[] = self::$installed;
}
return $installed;
}
}

21
vendor/composer/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

35
vendor/composer/autoload_classmap.php vendored Normal file
View File

@ -0,0 +1,35 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'Stripe' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Stripe.php',
'Stripe_Account' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Account.php',
'Stripe_ApiConnectionError' => $vendorDir . '/stripe/stripe-php/lib/Stripe/ApiConnectionError.php',
'Stripe_ApiError' => $vendorDir . '/stripe/stripe-php/lib/Stripe/ApiError.php',
'Stripe_ApiRequestor' => $vendorDir . '/stripe/stripe-php/lib/Stripe/ApiRequestor.php',
'Stripe_ApiResource' => $vendorDir . '/stripe/stripe-php/lib/Stripe/ApiResource.php',
'Stripe_AuthenticationError' => $vendorDir . '/stripe/stripe-php/lib/Stripe/AuthenticationError.php',
'Stripe_CardError' => $vendorDir . '/stripe/stripe-php/lib/Stripe/CardError.php',
'Stripe_Charge' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Charge.php',
'Stripe_Coupon' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Coupon.php',
'Stripe_Customer' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Customer.php',
'Stripe_Error' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Error.php',
'Stripe_Event' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Event.php',
'Stripe_InvalidRequestError' => $vendorDir . '/stripe/stripe-php/lib/Stripe/InvalidRequestError.php',
'Stripe_Invoice' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Invoice.php',
'Stripe_InvoiceItem' => $vendorDir . '/stripe/stripe-php/lib/Stripe/InvoiceItem.php',
'Stripe_List' => $vendorDir . '/stripe/stripe-php/lib/Stripe/List.php',
'Stripe_Object' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Object.php',
'Stripe_Plan' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Plan.php',
'Stripe_Recipient' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Recipient.php',
'Stripe_SingletonApiResource' => $vendorDir . '/stripe/stripe-php/lib/Stripe/SingletonApiResource.php',
'Stripe_Token' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Token.php',
'Stripe_Transfer' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Transfer.php',
'Stripe_Util' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Util.php',
'Stripe_Util_Set' => $vendorDir . '/stripe/stripe-php/lib/Stripe/Util/Set.php',
);

View File

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);

9
vendor/composer/autoload_psr4.php vendored Normal file
View File

@ -0,0 +1,9 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);

38
vendor/composer/autoload_real.php vendored Normal file
View File

@ -0,0 +1,38 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit40aa654f2e66c20881ae0572fe987a10
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit40aa654f2e66c20881ae0572fe987a10', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit40aa654f2e66c20881ae0572fe987a10', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit40aa654f2e66c20881ae0572fe987a10::getInitializer($loader));
$loader->register(true);
return $loader;
}
}

45
vendor/composer/autoload_static.php vendored Normal file
View File

@ -0,0 +1,45 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit40aa654f2e66c20881ae0572fe987a10
{
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'Stripe' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Stripe.php',
'Stripe_Account' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Account.php',
'Stripe_ApiConnectionError' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/ApiConnectionError.php',
'Stripe_ApiError' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/ApiError.php',
'Stripe_ApiRequestor' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/ApiRequestor.php',
'Stripe_ApiResource' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/ApiResource.php',
'Stripe_AuthenticationError' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/AuthenticationError.php',
'Stripe_CardError' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/CardError.php',
'Stripe_Charge' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Charge.php',
'Stripe_Coupon' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Coupon.php',
'Stripe_Customer' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Customer.php',
'Stripe_Error' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Error.php',
'Stripe_Event' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Event.php',
'Stripe_InvalidRequestError' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/InvalidRequestError.php',
'Stripe_Invoice' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Invoice.php',
'Stripe_InvoiceItem' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/InvoiceItem.php',
'Stripe_List' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/List.php',
'Stripe_Object' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Object.php',
'Stripe_Plan' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Plan.php',
'Stripe_Recipient' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Recipient.php',
'Stripe_SingletonApiResource' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/SingletonApiResource.php',
'Stripe_Token' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Token.php',
'Stripe_Transfer' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Transfer.php',
'Stripe_Util' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Util.php',
'Stripe_Util_Set' => __DIR__ . '/..' . '/stripe/stripe-php/lib/Stripe/Util/Set.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->classMap = ComposerStaticInit40aa654f2e66c20881ae0572fe987a10::$classMap;
}, null, ClassLoader::class);
}
}

59
vendor/composer/installed.json vendored Normal file
View File

@ -0,0 +1,59 @@
{
"packages": [
{
"name": "stripe/stripe-php",
"version": "v1.8.0",
"version_normalized": "1.8.0.0",
"source": {
"type": "git",
"url": "https://github.com/stripe/stripe-php.git",
"reference": "5eba614baf4adefffdd59d196679a16d7baf70da"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/stripe/stripe-php/zipball/5eba614baf4adefffdd59d196679a16d7baf70da",
"reference": "5eba614baf4adefffdd59d196679a16d7baf70da",
"shasum": ""
},
"require": {
"ext-curl": "*",
"php": ">=5.2"
},
"require-dev": {
"vierbergenlars/simpletest": "*"
},
"time": "2013-04-12T18:56:41+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"classmap": [
"lib/Stripe/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Stripe and contributors",
"homepage": "https://github.com/stripe/stripe-php/contributors"
}
],
"description": "Stripe PHP Library",
"homepage": "https://stripe.com/",
"keywords": [
"api",
"payment processing",
"stripe"
],
"support": {
"issues": "https://github.com/stripe/stripe-php/issues",
"source": "https://github.com/stripe/stripe-php/tree/transfers-recipients"
},
"install-path": "../stripe/stripe-php"
}
],
"dev": true,
"dev-package-names": []
}

32
vendor/composer/installed.php vendored Normal file
View File

@ -0,0 +1,32 @@
<?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => 'fda8a0a84a376bd3779a5a8cc7695c2ee7d20b6a',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => 'fda8a0a84a376bd3779a5a8cc7695c2ee7d20b6a',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'stripe/stripe-php' => array(
'pretty_version' => 'v1.8.0',
'version' => '1.8.0.0',
'reference' => '5eba614baf4adefffdd59d196679a16d7baf70da',
'type' => 'library',
'install_path' => __DIR__ . '/../stripe/stripe-php',
'aliases' => array(),
'dev_requirement' => false,
),
),
);

25
vendor/composer/platform_check.php vendored Normal file
View File

@ -0,0 +1,25 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 50200)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 5.2.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
throw new \RuntimeException(
'Composer detected issues in your platform: ' . implode(' ', $issues)
);
}

11
vendor/stripe/stripe-php/.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
# Mac OS X dumps these all over the place.
.DS_Store
# Ignore the SimpleTest library if it is installed to /test/.
/test/simpletest/
# Ignore the /vendor/ directory for people using composer
/vendor/
# If the vendor directory isn't being commited the composer.lock file should also be ignored
composer.lock

9
vendor/stripe/stripe-php/.travis.yml vendored Normal file
View File

@ -0,0 +1,9 @@
language: php
php:
- 5.2
- 5.3
- 5.4
before_script:
- wget http://voxel.dl.sourceforge.net/project/simpletest/simpletest/simpletest_1.1/simpletest_1.1.0.tar.gz
- tar xf simpletest_1.1.0.tar.gz -C test
script: php test/Stripe.php

96
vendor/stripe/stripe-php/CHANGELOG vendored Normal file
View File

@ -0,0 +1,96 @@
=== 1.8.0 2013-04-11
* Allow Transfers to be creatable
* Add new Recipient resource
=== 1.7.15 2013-02-21
* Add 'id' to the list of permanent object attributes
=== 1.7.14 2013-02-20
* Don't re-encode strings that are already encoded in UTF-8. If you
were previously using plan or coupon objects with UTF-8 IDs, they
may have been treated as ISO-8859-1 (Latin-1) and encoded to UTF-8 a
2nd time. You may now need to pass the IDs to utf8_encode before
passing them to Stripe_Plan::retrieve or Stripe_Coupon::retrieve.
* Ensure that all input is encoded in UTF-8 before submitting it to
Stripe's servers. (github issue #27)
=== 1.7.13 2013-02-01
* Add support for passing options when retrieving Stripe objects
e.g., Stripe_Charge::retrieve(array("id"=>"foo", "expand" => array("customer")))
Stripe_Charge::retrieve("foo") will continue to work
=== 1.7.12 2013-01-15
* Add support for setting a Stripe API version override
=== 1.7.11 2012-12-30
* Version bump to cleanup constants and such (github issue #26)
=== 1.7.10 2012-11-08
* Add support for updating charge disputes.
* Fix bug preventing retrieval of null attributes
=== 1.7.9 2012-11-08
* Fix usage under autoloaders such as the one generated by composer
(github issue #22)
=== 1.7.8 2012-10-30
* Add support for creating invoices.
* Add support for new invoice lines return format
* Add support for new list objects
=== 1.7.7 2012-09-14
* Get all of the various version numbers in the repo in sync (no other
changes)
=== 1.7.6 2012-08-31
* Add update and pay methods to Invoice resource
=== 1.7.5 2012-08-23
* Change internal function names so that Stripe_SingletonApiRequst is
E_STRICT-clean (github issue #16)
=== 1.7.4 2012-08-21
* Bugfix so that Stripe objects (e.g. Customer, Charge objects) used
in API calls are transparently converted to their object IDs
=== 1.7.3 2012-08-15
* Add new Account resource
=== 1.7.2 2012-06-26
* Make clearer that you should be including lib/Stripe.php, not
test/Stripe.php (github issue #14)
=== 1.7.1 2012-05-24
* Add missing argument to Stripe_InvalidRequestError constructor in
Stripe_ApiResource::instanceUrl. Fixes a warning when
Stripe_ApiResource::instanceUrl is called on a resouce with no ID
(github issue #12)
=== 1.7.0 2012-05-17
* Support Composer and Packagist (github issue #9)
* Add new deleteDiscount method to Stripe_Customer
* Add new Transfer resource
* Switch from using HTTP Basic auth to Bearer auth. (Note: Stripe will
support Basic auth for the indefinite future, but recommends Bearer
auth when possible going forward)
* Numerous test suite improvements

21
vendor/stripe/stripe-php/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2010 Stripe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

30
vendor/stripe/stripe-php/README.rdoc vendored Normal file
View File

@ -0,0 +1,30 @@
= Installation
Obtain the latest version of the Stripe PHP bindings with:
git clone https://github.com/stripe/stripe-php
To get started, add the following to your PHP script:
require_once("/path/to/stripe-php/lib/Stripe.php");
Simple usage looks like:
Stripe::setApiKey('d8e8fca2dc0f896fd7cb4cb0031ba249');
$myCard = array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015);
$charge = Stripe_Charge::create(array('card' => $myCard, 'amount' => 2000, 'currency' => 'usd'));
echo $charge;
= Documentation
Please see https://stripe.com/api for up-to-date documentation.
= Tests
In order to run tests you have to install SimpleTest (http://packagist.org/packages/vierbergenlars/simpletest) via Composer (http://getcomposer.org/) (recommended way):
composer.phar update --dev
Run test suite:
php ./test/Stripe.php

1
vendor/stripe/stripe-php/VERSION vendored Normal file
View File

@ -0,0 +1 @@
1.8.0

27
vendor/stripe/stripe-php/composer.json vendored Normal file
View File

@ -0,0 +1,27 @@
{
"name": "stripe/stripe-php",
"description": "Stripe PHP Library",
"keywords": [
"stripe",
"payment processing",
"api"
],
"homepage": "https://stripe.com/",
"license": "MIT",
"authors": [
{
"name": "Stripe and contributors",
"homepage": "https://github.com/stripe/stripe-php/contributors"
}
],
"require": {
"php": ">=5.2",
"ext-curl": "*"
},
"require-dev": {
"vierbergenlars/simpletest": "*"
},
"autoload": {
"classmap": ["lib/Stripe/"]
}
}

46
vendor/stripe/stripe-php/lib/Stripe.php vendored Normal file
View File

@ -0,0 +1,46 @@
<?php
// Tested on PHP 5.2, 5.3
// This snippet (and some of the curl code) due to the Facebook SDK.
if (!function_exists('curl_init')) {
throw new Exception('Stripe needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Stripe needs the JSON PHP extension.');
}
// Stripe singleton
require(dirname(__FILE__) . '/Stripe/Stripe.php');
// Utilities
require(dirname(__FILE__) . '/Stripe/Util.php');
require(dirname(__FILE__) . '/Stripe/Util/Set.php');
// Errors
require(dirname(__FILE__) . '/Stripe/Error.php');
require(dirname(__FILE__) . '/Stripe/ApiError.php');
require(dirname(__FILE__) . '/Stripe/ApiConnectionError.php');
require(dirname(__FILE__) . '/Stripe/AuthenticationError.php');
require(dirname(__FILE__) . '/Stripe/CardError.php');
require(dirname(__FILE__) . '/Stripe/InvalidRequestError.php');
// Plumbing
require(dirname(__FILE__) . '/Stripe/Object.php');
require(dirname(__FILE__) . '/Stripe/ApiRequestor.php');
require(dirname(__FILE__) . '/Stripe/ApiResource.php');
require(dirname(__FILE__) . '/Stripe/SingletonApiResource.php');
require(dirname(__FILE__) . '/Stripe/List.php');
// Stripe API Resources
require(dirname(__FILE__) . '/Stripe/Account.php');
require(dirname(__FILE__) . '/Stripe/Charge.php');
require(dirname(__FILE__) . '/Stripe/Customer.php');
require(dirname(__FILE__) . '/Stripe/Invoice.php');
require(dirname(__FILE__) . '/Stripe/InvoiceItem.php');
require(dirname(__FILE__) . '/Stripe/Plan.php');
require(dirname(__FILE__) . '/Stripe/Token.php');
require(dirname(__FILE__) . '/Stripe/Coupon.php');
require(dirname(__FILE__) . '/Stripe/Event.php');
require(dirname(__FILE__) . '/Stripe/Transfer.php');
require(dirname(__FILE__) . '/Stripe/Recipient.php');

View File

@ -0,0 +1,16 @@
<?php
class Stripe_Account extends Stripe_SingletonApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($apiKey=null)
{
$class = get_class();
return self::_scopedSingletonRetrieve($class, $apiKey);
}
}

View File

@ -0,0 +1,5 @@
<?php
class Stripe_ApiConnectionError extends Stripe_Error
{
}

View File

@ -0,0 +1,5 @@
<?php
class Stripe_ApiError extends Stripe_Error
{
}

View File

@ -0,0 +1,222 @@
<?php
class Stripe_ApiRequestor
{
public $apiKey;
public function __construct($apiKey=null)
{
$this->_apiKey = $apiKey;
}
public static function apiUrl($url='')
{
$apiBase = Stripe::$apiBase;
return "$apiBase$url";
}
public static function utf8($value)
{
if (is_string($value) && mb_detect_encoding($value, "UTF-8", TRUE) != "UTF-8")
return utf8_encode($value);
else
return $value;
}
private static function _encodeObjects($d)
{
if ($d instanceof Stripe_ApiResource) {
return self::utf8($d->id);
} else if ($d === true) {
return 'true';
} else if ($d === false) {
return 'false';
} else if (is_array($d)) {
$res = array();
foreach ($d as $k => $v)
$res[$k] = self::_encodeObjects($v);
return $res;
} else {
return self::utf8($d);
}
}
public static function encode($arr, $prefix=null)
{
if (!is_array($arr))
return $arr;
$r = array();
foreach ($arr as $k => $v) {
if (is_null($v))
continue;
if ($prefix && $k && !is_int($k))
$k = $prefix."[".$k."]";
else if ($prefix)
$k = $prefix."[]";
if (is_array($v)) {
$r[] = self::encode($v, $k, true);
} else {
$r[] = urlencode($k)."=".urlencode($v);
}
}
return implode("&", $r);
}
public function request($meth, $url, $params=null)
{
if (!$params)
$params = array();
list($rbody, $rcode, $myApiKey) = $this->_requestRaw($meth, $url, $params);
$resp = $this->_interpretResponse($rbody, $rcode);
return array($resp, $myApiKey);
}
public function handleApiError($rbody, $rcode, $resp)
{
if (!is_array($resp) || !isset($resp['error']))
throw new Stripe_ApiError("Invalid response object from API: $rbody (HTTP response code was $rcode)", $rcode, $rbody, $resp);
$error = $resp['error'];
switch ($rcode) {
case 400:
case 404:
throw new Stripe_InvalidRequestError(isset($error['message']) ? $error['message'] : null,
isset($error['param']) ? $error['param'] : null,
$rcode, $rbody, $resp);
case 401:
throw new Stripe_AuthenticationError(isset($error['message']) ? $error['message'] : null, $rcode, $rbody, $resp);
case 402:
throw new Stripe_CardError(isset($error['message']) ? $error['message'] : null,
isset($error['param']) ? $error['param'] : null,
isset($error['code']) ? $error['code'] : null,
$rcode, $rbody, $resp);
default:
throw new Stripe_ApiError(isset($error['message']) ? $error['message'] : null, $rcode, $rbody, $resp);
}
}
private function _requestRaw($meth, $url, $params)
{
$myApiKey = $this->_apiKey;
if (!$myApiKey)
$myApiKey = Stripe::$apiKey;
if (!$myApiKey)
throw new Stripe_AuthenticationError('No API key provided. (HINT: set your API key using "Stripe::setApiKey(<API-KEY>)". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.');
$absUrl = $this->apiUrl($url);
$params = self::_encodeObjects($params);
$langVersion = phpversion();
$uname = php_uname();
$ua = array('bindings_version' => Stripe::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'stripe',
'uname' => $uname);
$headers = array('X-Stripe-Client-User-Agent: ' . json_encode($ua),
'User-Agent: Stripe/v1 PhpBindings/' . Stripe::VERSION,
'Authorization: Bearer ' . $myApiKey);
if (Stripe::$apiVersion)
$headers[] = 'Stripe-Version: ' . Stripe::$apiVersion;
list($rbody, $rcode) = $this->_curlRequest($meth, $absUrl, $headers, $params);
return array($rbody, $rcode, $myApiKey);
}
private function _interpretResponse($rbody, $rcode)
{
try {
$resp = json_decode($rbody, true);
} catch (Exception $e) {
throw new Stripe_ApiError("Invalid response body from API: $rbody (HTTP response code was $rcode)", $rcode, $rbody);
}
if ($rcode < 200 || $rcode >= 300) {
$this->handleApiError($rbody, $rcode, $resp);
}
return $resp;
}
private function _curlRequest($meth, $absUrl, $headers, $params)
{
$curl = curl_init();
$meth = strtolower($meth);
$opts = array();
if ($meth == 'get') {
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else if ($meth == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = self::encode($params);
} else if ($meth == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Stripe_ApiError("Unrecognized method $meth");
}
$absUrl = self::utf8($absUrl);
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 30;
$opts[CURLOPT_TIMEOUT] = 80;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_HTTPHEADER] = $headers;
if (!Stripe::$verifySslCerts)
$opts[CURLOPT_SSL_VERIFYPEER] = false;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
$errno = curl_errno($curl);
if ($errno == CURLE_SSL_CACERT ||
$errno == CURLE_SSL_PEER_CERTIFICATE ||
$errno == 77 // CURLE_SSL_CACERT_BADFILE (constant not defined in PHP though)
) {
array_push($headers, 'X-Stripe-Client-Info: {"ca":"using Stripe-supplied CA bundle"}');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CAINFO,
dirname(__FILE__) . '/../data/ca-certificates.crt');
$rbody = curl_exec($curl);
}
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array($rbody, $rcode);
}
public function handleCurlError($errno, $message)
{
$apiBase = Stripe::$apiBase;
switch ($errno) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED:
$msg = "Could not connect to Stripe ($apiBase). Please check your internet connection and try again. If this problem persists, you should check Stripe's service status at https://twitter.com/stripestatus, or let us know at support@stripe.com.";
break;
case CURLE_SSL_CACERT:
case CURLE_SSL_PEER_CERTIFICATE:
$msg = "Could not verify Stripe's SSL certificate. Please make sure that your network is not intercepting certificates. (Try going to $apiBase in your browser.) If this problem persists, let us know at support@stripe.com.";
break;
default:
$msg = "Unexpected error communicating with Stripe. If this problem persists, let us know at support@stripe.com.";
}
$msg .= "\n\n(Network error [errno $errno]: $message)";
throw new Stripe_ApiConnectionError($msg);
}
}

View File

@ -0,0 +1,104 @@
<?php
abstract class Stripe_ApiResource extends Stripe_Object
{
protected static function _scopedRetrieve($class, $id, $apiKey=null)
{
$instance = new $class($id, $apiKey);
$instance->refresh();
return $instance;
}
public function refresh()
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl();
list($response, $apiKey) = $requestor->request('get', $url, $this->_retrieveOptions);
$this->refreshFrom($response, $apiKey);
return $this;
}
public static function className($class)
{
// Useful for namespaces: Foo\Stripe_Charge
if ($postfix = strrchr($class, '\\'))
$class = substr($postfix, 1);
if (substr($class, 0, strlen('Stripe')) == 'Stripe')
$class = substr($class, strlen('Stripe'));
$class = str_replace('_', '', $class);
$name = urlencode($class);
$name = strtolower($name);
return $name;
}
public static function classUrl($class)
{
$base = self::className($class);
return "/v1/${base}s";
}
public function instanceUrl()
{
$id = $this['id'];
$class = get_class($this);
if (!$id) {
throw new Stripe_InvalidRequestError("Could not determine which URL to request: $class instance has invalid ID: $id", null);
}
$id = Stripe_ApiRequestor::utf8($id);
$base = self::classUrl($class);
$extn = urlencode($id);
return "$base/$extn";
}
private static function _validateCall($method, $params=null, $apiKey=null)
{
if ($params && !is_array($params))
throw new Stripe_Error("You must pass an array as the first argument to Stripe API method calls. (HINT: an example call to create a charge would be: \"StripeCharge::create(array('amount' => 100, 'currency' => 'usd', 'card' => array('number' => 4242424242424242, 'exp_month' => 5, 'exp_year' => 2015)))\")");
if ($apiKey && !is_string($apiKey))
throw new Stripe_Error('The second argument to Stripe API method calls is an optional per-request apiKey, which must be a string. (HINT: you can set a global apiKey by "Stripe::setApiKey(<apiKey>)")');
}
protected static function _scopedAll($class, $params=null, $apiKey=null)
{
self::_validateCall('all', $params, $apiKey);
$requestor = new Stripe_ApiRequestor($apiKey);
$url = self::classUrl($class);
list($response, $apiKey) = $requestor->request('get', $url, $params);
return Stripe_Util::convertToStripeObject($response, $apiKey);
}
protected static function _scopedCreate($class, $params=null, $apiKey=null)
{
self::_validateCall('create', $params, $apiKey);
$requestor = new Stripe_ApiRequestor($apiKey);
$url = self::classUrl($class);
list($response, $apiKey) = $requestor->request('post', $url, $params);
return Stripe_Util::convertToStripeObject($response, $apiKey);
}
protected function _scopedSave($class)
{
self::_validateCall('save');
if ($this->_unsavedValues) {
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$params = array();
foreach ($this->_unsavedValues->toArray() as $k)
$params[$k] = $this->$k;
$url = $this->instanceUrl();
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom($response, $apiKey);
}
return $this;
}
protected function _scopedDelete($class, $params=null)
{
self::_validateCall('delete');
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl();
list($response, $apiKey) = $requestor->request('delete', $url, $params);
$this->refreshFrom($response, $apiKey);
return $this;
}
}

View File

@ -0,0 +1,5 @@
<?php
class Stripe_AuthenticationError extends Stripe_Error
{
}

View File

@ -0,0 +1,11 @@
<?php
class Stripe_CardError extends Stripe_Error
{
public function __construct($message, $param, $code, $http_status=null, $http_body=null, $json_body=null)
{
parent::__construct($message, $http_status, $http_body, $json_body);
$this->param = $param;
$this->code = $code;
}
}

View File

@ -0,0 +1,61 @@
<?php
class Stripe_Charge extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public function refund($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/refund';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom($response, $apiKey);
return $this;
}
public function capture($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/capture';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom($response, $apiKey);
return $this;
}
public function updateDispute($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/dispute';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom(array('dispute' => $response), $apiKey, true);
return $this->dispute;
}
}

View File

@ -0,0 +1,34 @@
<?php
class Stripe_Coupon extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function delete($params=null)
{
$class = get_class();
return self::_scopedDelete($class, $params);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
}

View File

@ -0,0 +1,102 @@
<?php
class Stripe_Customer extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public function delete($params=null)
{
$class = get_class();
return self::_scopedDelete($class, $params);
}
public function addInvoiceItem($params=null)
{
if (!$params)
$params = array();
$params['customer'] = $this->id;
$ii = Stripe_InvoiceItem::create($params, $this->_apiKey);
return $ii;
}
public function invoices($params=null)
{
if (!$params)
$params = array();
$params['customer'] = $this->id;
$invoices = Stripe_Invoice::all($params, $this->_apiKey);
return $invoices;
}
public function invoiceItems($params=null)
{
if (!$params)
$params = array();
$params['customer'] = $this->id;
$iis = Stripe_InvoiceItem::all($params, $this->_apiKey);
return $iis;
}
public function charges($params=null)
{
if (!$params)
$params = array();
$params['customer'] = $this->id;
$charges = Stripe_Charge::all($params, $this->_apiKey);
return $charges;
}
public function updateSubscription($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/subscription';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom(array('subscription' => $response), $apiKey, true);
return $this->subscription;
}
public function cancelSubscription($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/subscription';
list($response, $apiKey) = $requestor->request('delete', $url, $params);
$this->refreshFrom(array('subscription' => $response), $apiKey, true);
return $this->subscription;
}
public function deleteDiscount()
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/discount';
list($response, $apiKey) = $requestor->request('delete', $url);
$this->refreshFrom(array('discount' => null), $apiKey, true);
}
}

View File

@ -0,0 +1,27 @@
<?php
class Stripe_Error extends Exception
{
public function __construct($message=null, $http_status=null, $http_body=null, $json_body=null)
{
parent::__construct($message);
$this->http_status = $http_status;
$this->http_body = $http_body;
$this->json_body = $json_body;
}
public function getHttpStatus()
{
return $this->http_status;
}
public function getHttpBody()
{
return $this->http_body;
}
public function getJsonBody()
{
return $this->json_body;
}
}

View File

@ -0,0 +1,22 @@
<?php
class Stripe_Event extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
}

View File

@ -0,0 +1,10 @@
<?php
class Stripe_InvalidRequestError extends Stripe_Error
{
public function __construct($message, $param, $http_status=null, $http_body=null, $json_body=null)
{
parent::__construct($message, $http_status, $http_body, $json_body);
$this->param = $param;
}
}

View File

@ -0,0 +1,51 @@
<?php
class Stripe_Invoice extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function upcoming($params=null, $apiKey=null)
{
$requestor = new Stripe_ApiRequestor($apiKey);
$url = self::classUrl(get_class()) . '/upcoming';
list($response, $apiKey) = $requestor->request('get', $url, $params);
return Stripe_Util::convertToStripeObject($response, $apiKey);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public function pay()
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/pay';
list($response, $apiKey) = $requestor->request('post', $url);
$this->refreshFrom($response, $apiKey);
return $this;
}
}

View File

@ -0,0 +1,40 @@
<?php
class Stripe_InvoiceItem extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public function delete($params=null)
{
$class = get_class();
return self::_scopedDelete($class, $params);
}
}

View File

@ -0,0 +1,17 @@
<?php
class Stripe_List extends Stripe_Object
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public function all($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
list($response, $apiKey) = $requestor->request('get', $this['url'], $params);
return Stripe_Util::convertToStripeObject($response, $apiKey);
}
}

View File

@ -0,0 +1,155 @@
<?php
class Stripe_Object implements ArrayAccess
{
public static $_permanentAttributes;
public static function init()
{
self::$_permanentAttributes = new Stripe_Util_Set(array('_apiKey', 'id'));
}
protected $_apiKey;
protected $_values;
protected $_unsavedValues;
protected $_transientValues;
protected $_retrieveOptions;
public function __construct($id=null, $apiKey=null)
{
$this->_apiKey = $apiKey;
$this->_values = array();
$this->_unsavedValues = new Stripe_Util_Set();
$this->_transientValues = new Stripe_Util_Set();
$this->_retrieveOptions = array();
if (is_array($id)) {
foreach($id as $key => $value) {
if ($key != 'id')
$this->_retrieveOptions[$key] = $value;
}
$id = $id['id'];
}
if ($id)
$this->id = $id;
}
// Standard accessor magic methods
public function __set($k, $v)
{
// TODO: may want to clear from $_transientValues. (Won't be user-visible.)
$this->_values[$k] = $v;
if (!self::$_permanentAttributes->includes($k))
$this->_unsavedValues->add($k);
}
public function __isset($k)
{
return isset($this->_values[$k]);
}
public function __unset($k)
{
unset($this->_values[$k]);
$this->_transientValues->add($k);
$this->_unsavedValues->discard($k);
}
public function __get($k)
{
if (array_key_exists($k, $this->_values)) {
return $this->_values[$k];
} else if ($this->_transientValues->includes($k)) {
$class = get_class($this);
$attrs = join(', ', array_keys($this->_values));
error_log("Stripe Notice: Undefined property of $class instance: $k. HINT: The $k attribute was set in the past, however. It was then wiped when refreshing the object with the result returned by Stripe's API, probably as a result of a save(). The attributes currently available on this object are: $attrs");
return null;
} else {
$class = get_class($this);
error_log("Stripe Notice: Undefined property of $class instance: $k");
return null;
}
}
// ArrayAccess methods
public function offsetSet($k, $v)
{
$this->$k = $v;
}
public function offsetExists($k)
{
return array_key_exists($k, $this->_values);
}
public function offsetUnset($k)
{
unset($this->$k);
}
public function offsetGet($k)
{
return array_key_exists($k, $this->_values) ? $this->_values[$k] : null;
}
// This unfortunately needs to be public to be used in Util.php
public static function scopedConstructFrom($class, $values, $apiKey=null)
{
$obj = new $class(isset($values['id']) ? $values['id'] : null, $apiKey);
$obj->refreshFrom($values, $apiKey);
return $obj;
}
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public function refreshFrom($values, $apiKey, $partial=false)
{
$this->_apiKey = $apiKey;
// Wipe old state before setting new. This is useful for e.g. updating a
// customer, where there is no persistent card parameter. Mark those values
// which don't persist as transient
if ($partial)
$removed = new Stripe_Util_Set();
else
$removed = array_diff(array_keys($this->_values), array_keys($values));
foreach ($removed as $k) {
if (self::$_permanentAttributes->includes($k))
continue;
unset($this->$k);
}
foreach ($values as $k => $v) {
if (self::$_permanentAttributes->includes($k))
continue;
$this->_values[$k] = Stripe_Util::convertToStripeObject($v, $apiKey);
$this->_transientValues->discard($k);
$this->_unsavedValues->discard($k);
}
}
public function __toJSON()
{
if (defined('JSON_PRETTY_PRINT'))
return json_encode($this->__toArray(true), JSON_PRETTY_PRINT);
else
return json_encode($this->__toArray(true));
}
public function __toString()
{
return $this->__toJSON();
}
public function __toArray($recursive=false)
{
if ($recursive)
return Stripe_Util::convertStripeObjectToArray($this->_values);
else
return $this->_values;
}
}
Stripe_Object::init();

View File

@ -0,0 +1,40 @@
<?php
class Stripe_Plan extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function delete($params=null)
{
$class = get_class();
return self::_scopedDelete($class, $params);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
}

View File

@ -0,0 +1,50 @@
<?php
class Stripe_Recipient extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public function delete($params=null)
{
$class = get_class();
return self::_scopedDelete($class, $params);
}
public function transfers($params=null)
{
if (!$params)
$params = array();
$params['recipient'] = $this->id;
$transfers = Stripe_Transfer::all($params, $this->_apiKey);
return $transfers;
}
}

View File

@ -0,0 +1,24 @@
<?php
abstract class Stripe_SingletonApiResource extends Stripe_ApiResource
{
protected static function _scopedSingletonRetrieve($class, $apiKey=null)
{
$instance = new $class(null, $apiKey);
$instance->refresh();
return $instance;
}
public static function classUrl($class)
{
$base = self::className($class);
return "/v1/${base}";
}
public function instanceUrl()
{
$class = get_class($this);
$base = self::classUrl($class);
return "$base";
}
}

View File

@ -0,0 +1,38 @@
<?php
abstract class Stripe
{
public static $apiKey;
public static $apiBase = 'https://api.stripe.com';
public static $apiVersion = null;
public static $verifySslCerts = true;
const VERSION = '1.8.0';
public static function getApiKey()
{
return self::$apiKey;
}
public static function setApiKey($apiKey)
{
self::$apiKey = $apiKey;
}
public static function getApiVersion()
{
return self::$apiVersion;
}
public static function setApiVersion($apiVersion)
{
self::$apiVersion = $apiVersion;
}
public static function getVerifySslCerts() {
return self::$verifySslCerts;
}
public static function setVerifySslCerts($verify) {
self::$verifySslCerts = $verify;
}
}

View File

@ -0,0 +1,22 @@
<?php
class Stripe_Token extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
}

View File

@ -0,0 +1,30 @@
<?php
class Stripe_Transfer extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
}

View File

@ -0,0 +1,66 @@
<?php
abstract class Stripe_Util
{
public static function isList($array)
{
if (!is_array($array))
return false;
// TODO: this isn't actually correct in general, but it's correct given Stripe's responses
foreach (array_keys($array) as $k) {
if (!is_numeric($k))
return false;
}
return true;
}
public static function convertStripeObjectToArray($values)
{
$results = array();
foreach ($values as $k => $v) {
// FIXME: this is an encapsulation violation
if (Stripe_Object::$_permanentAttributes->includes($k)) {
continue;
}
if ($v instanceof Stripe_Object) {
$results[$k] = $v->__toArray(true);
}
else if (is_array($v)) {
$results[$k] = self::convertStripeObjectToArray($v);
}
else {
$results[$k] = $v;
}
}
return $results;
}
public static function convertToStripeObject($resp, $apiKey)
{
$types = array(
'charge' => 'Stripe_Charge',
'customer' => 'Stripe_Customer',
'list' => 'Stripe_List',
'invoice' => 'Stripe_Invoice',
'invoiceitem' => 'Stripe_InvoiceItem',
'event' => 'Stripe_Event',
'transfer' => 'Stripe_Transfer',
'plan' => 'Stripe_Plan',
'recipient' => 'Stripe_Recipient'
);
if (self::isList($resp)) {
$mapped = array();
foreach ($resp as $i)
array_push($mapped, self::convertToStripeObject($i, $apiKey));
return $mapped;
} else if (is_array($resp)) {
if (isset($resp['object']) && is_string($resp['object']) && isset($types[$resp['object']]))
$class = $types[$resp['object']];
else
$class = 'Stripe_Object';
return Stripe_Object::scopedConstructFrom($class, $resp, $apiKey);
} else {
return $resp;
}
}
}

View File

@ -0,0 +1,34 @@
<?php
class Stripe_Util_Set
{
private $_elts;
public function __construct($members=array())
{
$this->_elts = array();
foreach ($members as $item)
$this->_elts[$item] = true;
}
public function includes($elt)
{
return isset($this->_elts[$elt]);
}
public function add($elt)
{
$this->_elts[$elt] = true;
}
public function discard($elt)
{
unset($this->_elts[$elt]);
}
// TODO: make Set support foreach
public function toArray()
{
return array_keys($this->_elts);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,53 @@
<?php
echo "Running the Stripe PHP bindings test suite.\n".
"If you're trying to use the Stripe PHP bindings you'll probably want ".
"to require('lib/Stripe.php'); instead of this file\n";
function authorizeFromEnv()
{
$apiKey = getenv('STRIPE_API_KEY');
if (!$apiKey)
$apiKey = "tGN0bIwXnHdwOa85VABjPdSn8nWY7G7I";
Stripe::setApiKey($apiKey);
}
$ok = @include_once(dirname(__FILE__).'/simpletest/autorun.php');
if (!$ok) {
$ok = @include_once(dirname(__FILE__).'/../vendor/vierbergenlars/simpletest/autorun.php');
}
if (!$ok) {
echo "MISSING DEPENDENCY: The Stripe API test cases depend on SimpleTest. ".
"Download it at <http://www.simpletest.org/>, and either install it ".
"in your PHP include_path or put it in the test/ directory.\n";
exit(1);
}
// Throw an exception on any error
function exception_error_handler($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler('exception_error_handler');
error_reporting(E_ALL | E_STRICT);
require_once(dirname(__FILE__) . '/../lib/Stripe.php');
require_once(dirname(__FILE__) . '/Stripe/TestCase.php');
require_once(dirname(__FILE__) . '/Stripe/ApiRequestorTest.php');
require_once(dirname(__FILE__) . '/Stripe/AuthenticationErrorTest.php');
require_once(dirname(__FILE__) . '/Stripe/CardErrorTest.php');
require_once(dirname(__FILE__) . '/Stripe/AccountTest.php');
require_once(dirname(__FILE__) . '/Stripe/ChargeTest.php');
require_once(dirname(__FILE__) . '/Stripe/CouponTest.php');
require_once(dirname(__FILE__) . '/Stripe/CustomerTest.php');
require_once(dirname(__FILE__) . '/Stripe/DiscountTest.php');
require_once(dirname(__FILE__) . '/Stripe/Error.php');
require_once(dirname(__FILE__) . '/Stripe/InvalidRequestErrorTest.php');
require_once(dirname(__FILE__) . '/Stripe/InvoiceTest.php');
require_once(dirname(__FILE__) . '/Stripe/ObjectTest.php');
require_once(dirname(__FILE__) . '/Stripe/PlanTest.php');
require_once(dirname(__FILE__) . '/Stripe/Token.php');
require_once(dirname(__FILE__) . '/Stripe/TransferTest.php');
require_once(dirname(__FILE__) . '/Stripe/RecipientTest.php');
require_once(dirname(__FILE__) . '/Stripe/UtilTest.php');

View File

@ -0,0 +1,13 @@
<?php
class Stripe_AccountTest extends StripeTestCase
{
public function testRetrieve()
{
authorizeFromEnv();
$d = Stripe_Account::retrieve();
$this->assertEqual($d->email, "test+bindings@stripe.com");
$this->assertEqual($d->charge_enabled, false);
$this->assertEqual($d->details_submitted, false);
}
}

View File

@ -0,0 +1,64 @@
<?php
class Stripe_ApiRequestorTest extends UnitTestCase
{
public function testEncode()
{
$a = array('my' => 'value', 'that' => array('your' => 'example'), 'bar' => 1, 'baz' => null);
$enc = Stripe_APIRequestor::encode($a);
$this->assertEqual($enc, 'my=value&that%5Byour%5D=example&bar=1');
$a = array('that' => array('your' => 'example', 'foo' => null));
$enc = Stripe_APIRequestor::encode($a);
$this->assertEqual($enc, 'that%5Byour%5D=example');
$a = array('that' => 'example', 'foo' => array('bar', 'baz'));
$enc = Stripe_APIRequestor::encode($a);
$this->assertEqual($enc, 'that=example&foo%5B%5D=bar&foo%5B%5D=baz');
$a = array('my' => 'value', 'that' => array('your' => array('cheese', 'whiz', null)), 'bar' => 1, 'baz' => null);
$enc = Stripe_APIRequestor::encode($a);
$this->assertEqual($enc, 'my=value&that%5Byour%5D%5B%5D=cheese&that%5Byour%5D%5B%5D=whiz&bar=1');
}
public function testUtf8()
{
// UTF-8 string
$x = "\xc3\xa9";
$this->assertEqual(Stripe_ApiRequestor::utf8($x), $x);
// Latin-1 string
$x = "\xe9";
$this->assertEqual(Stripe_ApiRequestor::utf8($x), "\xc3\xa9");
// Not a string
$x = TRUE;
$this->assertEqual(Stripe_ApiRequestor::utf8($x), $x);
}
public function testEncodeObjects()
{
// We have to do some work here because this is normally
// private. This is just for testing! Also it only works on PHP >=
// 5.3
if (version_compare(PHP_VERSION, '5.3.2', '>=')) {
$reflector = new ReflectionClass('Stripe_APIRequestor');
$method = $reflector->getMethod('_encodeObjects');
$method->setAccessible(true);
$a = array('customer' => new Stripe_Customer('abcd'));
$enc = $method->invoke(null, $a);
$this->assertEqual($enc, array('customer' => 'abcd'));
// Preserves UTF-8
$v = array('customer' => "");
$enc = $method->invoke(null, $v);
$this->assertEqual($enc, $v);
// Encodes latin-1 -> UTF-8
$v = array('customer' => "\xe9");
$enc = $method->invoke(null, $v);
$this->assertEqual($enc, array('customer' => "\xc3\xa9"));
}
}
}

View File

@ -0,0 +1,14 @@
<?php
class Stripe_AuthenticationErrorTest extends UnitTestCase
{
public function testInvalidCredentials()
{
Stripe::setApiKey('invalid');
try {
Stripe_Customer::create();
} catch (Stripe_AuthenticationError $e) {
$this->assertEqual(401, $e->getHttpStatus());
}
}
}

View File

@ -0,0 +1,16 @@
<?php
class Stripe_CardErrorTest extends UnitTestCase
{
public function testDecline()
{
authorizeFromEnv();
try {
Stripe_Charge::create(array('amount' => 100, 'currency' => 'usd', 'card' => array('number' => '4000000000000002', 'exp_month' => '3', 'exp_year' => '2020')));
} catch (Stripe_CardError $e) {
$this->assertEqual(402, $e->getHttpStatus());
$body = $e->getJsonBody();
$this->assertTrue($body['error']);
}
}
}

View File

@ -0,0 +1,35 @@
<?php
class Stripe_ChargeTest extends UnitTestCase
{
public function testUrls()
{
$this->assertEqual(Stripe_Charge::classUrl('Stripe_Charge'), '/v1/charges');
$charge = new Stripe_Charge('abcd/efgh');
$this->assertEqual($charge->instanceUrl(), '/v1/charges/abcd%2Fefgh');
}
public function testCreate()
{
authorizeFromEnv();
$c = Stripe_Charge::create(array('amount' => 100,
'currency' => 'usd',
'card' => array('number' => '4242424242424242',
'exp_month' => 5,
'exp_year' => 2015)));
$this->assertTrue($c->paid);
$this->assertFalse($c->refunded);
}
public function testRetrieve()
{
authorizeFromEnv();
$c = Stripe_Charge::create(array('amount' => 100,
'currency' => 'usd',
'card' => array('number' => '4242424242424242',
'exp_month' => 5,
'exp_year' => 2015)));
$d = Stripe_Charge::retrieve($c->id);
$this->assertEqual($d->id, $c->id);
}
}

View File

@ -0,0 +1,17 @@
<?php
class Stripe_CouponTest extends StripeTestCase
{
public function testCreate()
{
authorizeFromEnv();
$id = 'test_coupon-' . self::randomString();
$c = Stripe_Coupon::create(array('percent_off' => 25,
'duration' => 'repeating',
'duration_in_months' => 5,
'id' => $id));
$this->assertEqual($id, $c->id);
$this->assertEqual(25, $c->percent_off);
}
}

View File

@ -0,0 +1,58 @@
<?php
class Stripe_CustomerTest extends StripeTestCase
{
public function testDeletion()
{
$customer = self::createTestCustomer();
$customer->delete();
$this->assertTrue($customer->deleted);
$this->assertNull($customer['active_card']);
}
public function testSave()
{
$customer = self::createTestCustomer();
$customer->email = 'gdb@stripe.com';
$customer->save();
$this->assertEqual($customer->email, 'gdb@stripe.com');
$customer2 = Stripe_Customer::retrieve($customer->id);
$this->assertEqual($customer->email, $customer2->email);
}
public function testBogusAttribute()
{
$customer = self::createTestCustomer();
$customer->bogus = 'bogus';
$caught = null;
try {
$customer->save();
} catch (Stripe_InvalidRequestError $exception) {
$caught = $exception;
}
$this->assertTrue($caught instanceof Stripe_InvalidRequestError);
}
public function testCancelSubscription()
{
$plan_id = 'gold-' . self::randomString();
self::retrieveOrCreatePlan($plan_id);
$customer = self::createTestCustomer(
array(
'plan' => $plan_id,
));
$customer->cancelSubscription(array('at_period_end' => true));
$this->assertEqual($customer->subscription->status, 'active');
$this->assertTrue($customer->subscription->cancel_at_period_end);
$customer->cancelSubscription();
$this->assertEqual($customer->subscription->status, 'canceled');
}
}

View File

@ -0,0 +1,25 @@
<?php
class Stripe_DiscountTest extends StripeTestCase
{
public function testDeletion()
{
authorizeFromEnv();
$id = 'test-coupon-' . self::randomString();
$coupon = Stripe_Coupon::create(array('percent_off' => 25,
'duration' => 'repeating',
'duration_in_months' => 5,
'id' => $id));
$customer = self::createTestCustomer(array('coupon' => $id));
$this->assertTrue(isset($customer->discount));
$this->assertTrue(isset($customer->discount->coupon));
$this->assertEqual($id, $customer->discount->coupon->id);
$customer->deleteDiscount();
$this->assertFalse(isset($customer->discount));
$customer = Stripe_Customer::retrieve($customer->id);
$this->assertFalse(isset($customer->discount));
}
}

View File

@ -0,0 +1,17 @@
<?php
class Stripe_ErrorTest extends UnitTestCase
{
public function testCreation()
{
try {
throw new Stripe_Error("hello", 500, "{'foo':'bar'}", array('foo' => 'bar'));
$this->fail("Did not raise error");
} catch (Stripe_Error $e) {
$this->assertEqual("hello", $e->getMessage());
$this->assertEqual(500, $e->getHttpStatus());
$this->assertEqual("{'foo':'bar'}", $e->getHttpBody());
$this->assertEqual(array('foo' => 'bar'), $e->getJsonBody());
}
}
}

View File

@ -0,0 +1,24 @@
<?php
class Stripe_InvalidRequestErrorTest extends UnitTestCase
{
public function testInvalidObject()
{
authorizeFromEnv();
try {
Stripe_Customer::retrieve('invalid');
} catch (Stripe_InvalidRequestError $e) {
$this->assertEqual(404, $e->getHttpStatus());
}
}
public function testBadData()
{
authorizeFromEnv();
try {
Stripe_Charge::create();
} catch (Stripe_InvalidRequestError $e) {
$this->assertEqual(400, $e->getHttpStatus());
}
}
}

View File

@ -0,0 +1,25 @@
<?php
class Stripe_InvoiceTest extends StripeTestCase
{
public function testUpcoming()
{
authorizeFromEnv();
$customer = self::createTestCustomer();
Stripe_InvoiceItem::create(
array(
'customer' => $customer->id,
'amount' => 0,
'currency' => 'usd',
));
$invoice = Stripe_Invoice::upcoming(
array(
'customer' => $customer->id,
));
$this->assertEqual($invoice->customer, $customer->id);
$this->assertEqual($invoice->attempted, false);
}
}

View File

@ -0,0 +1,53 @@
<?php
class Stripe_ObjectTest extends UnitTestCase
{
public function testArrayAccessorsSemantics()
{
$s = new Stripe_Object();
$s['foo'] = 'a';
$this->assertEqual($s['foo'], 'a');
$this->assertTrue(isset($s['foo']));
unset($s['foo']);
$this->assertFalse(isset($s['foo']));
}
public function testNormalAccessorsSemantics()
{
$s = new Stripe_Object();
$s->foo = 'a';
$this->assertEqual($s->foo, 'a');
$this->assertTrue(isset($s->foo));
unset($s->foo);
$this->assertFalse(isset($s->foo));
}
public function testArrayAccessorsMatchNormalAccessors()
{
$s = new Stripe_Object();
$s->foo = 'a';
$this->assertEqual($s['foo'], 'a');
$s['bar'] = 'b';
$this->assertEqual($s->bar, 'b');
}
public function testToString()
{
$s = new Stripe_Object();
$s->foo = 'a';
$s->bar = 'b';
// NOTE: The toString() implementation of Stripe_Object simply converts the
// object into a JSON string, but the exact format depends on the
// availability of JSON_PRETTY_PRINT, which isn't available until PHP 5.4.
// Instead of testing the exact string representation, verify that the
// object converts into a valid JSON string.
$string = (string)$s;
$object = json_decode($string, true);
$this->assertTrue(is_array($object));
}
}

View File

@ -0,0 +1,33 @@
<?php
class Stripe_PlanTest extends StripeTestCase
{
public function testDeletion()
{
authorizeFromEnv();
$p = Stripe_Plan::create(array('amount' => 2000,
'interval' => 'month',
'currency' => 'usd',
'name' => 'Plan',
'id' => 'gold-' . self::randomString()));
$p->delete();
$this->assertTrue($p->deleted);
}
public function testSave()
{
authorizeFromEnv();
$planId = 'gold-' . self::randomString();
$p = Stripe_Plan::create(array('amount' => 2000,
'interval' => 'month',
'currency' => 'usd',
'name' => 'Plan',
'id' => $planId));
$p->name = 'A new plan name';
$p->save();
$this->assertEqual($p->name, 'A new plan name');
$p2 = Stripe_Plan::retrieve($planId);
$this->assertEqual($p->name, $p2->name);
}
}

View File

@ -0,0 +1,39 @@
<?php
class Stripe_RecipientTest extends StripeTestCase
{
public function testDeletion()
{
$recipient = self::createTestRecipient();
$recipient->delete();
$this->assertTrue($recipient->deleted);
}
public function testSave()
{
$recipient = self::createTestRecipient();
$recipient->email = 'gdb@stripe.com';
$recipient->save();
$this->assertEqual($recipient->email, 'gdb@stripe.com');
$recipient2 = Stripe_Recipient::retrieve($recipient->id);
$this->assertEqual($recipient->email, $recipient2->email);
}
public function testBogusAttribute()
{
$recipient = self::createTestRecipient();
$recipient->bogus = 'bogus';
$caught = null;
try {
$recipient->save();
} catch (Stripe_InvalidRequestError $exception) {
$caught = $exception;
}
$this->assertTrue($caught instanceof Stripe_InvalidRequestError);
}
}

View File

@ -0,0 +1,83 @@
<?php
/**
* Base class for Stripe test cases, provides some utility methods for creating
* objects.
*/
abstract class StripeTestCase extends UnitTestCase
{
/**
* Create a valid test customer.
*/
protected static function createTestCustomer(array $attributes = array())
{
authorizeFromEnv();
return Stripe_Customer::create(
$attributes + array(
'card' => array(
'number' => '4242424242424242',
'exp_month' => 5,
'exp_year' => date('Y') + 3,
),
));
}
/**
* Create a valid test recipient
*/
protected static function createTestRecipient(array $attributes = array())
{
authorizeFromEnv();
return Stripe_Recipient::create(
$attributes + array(
'name' => 'PHP Test',
'type' => 'individual',
'tax_id' => '000000000',
'bank_account' => array(
'country' => 'US',
'routing_number' => '110000000',
'account_number' => '000123456789'
),
));
}
/**
* Generate a random 8-character string. Useful for ensuring
* multiple test suite runs don't conflict
*/
protected static function randomString()
{
$chars = "abcdefghijklmnopqrstuvwxyz";
$str = "";
for ($i = 0; $i < 10; $i++) {
$str .= $chars[rand(0, strlen($chars)-1)];
}
return $str;
}
/**
* Verify that a plan with a given ID exists, or create a new one if it does
* not.
*/
protected static function retrieveOrCreatePlan($id)
{
authorizeFromEnv();
try {
$plan = Stripe_Plan::retrieve($id);
} catch (Stripe_InvalidRequestError $exception) {
$plan = Stripe_Plan::create(
array(
'id' => $id,
'amount' => 0,
'currency' => 'usd',
'interval' => 'month',
'name' => 'Gold Test Plan',
));
}
}
}

View File

@ -0,0 +1,11 @@
<?php
class Stripe_TokenTest extends UnitTestCase
{
public function testUrls()
{
$this->assertEqual(Stripe_Token::classUrl('Stripe_Token'), '/v1/tokens');
$token = new Stripe_Token('abcd/efgh');
$this->assertEqual($token->instanceUrl(), '/v1/tokens/abcd%2Fefgh');
}
}

View File

@ -0,0 +1,35 @@
<?php
class Stripe_TransferTest extends StripeTestCase
{
public function testCreate()
{
$recipient = self::createTestRecipient();
authorizeFromEnv();
$transfer = Stripe_Transfer::create(
array(
'amount' => 100,
'currency' => 'usd',
'recipient' => $recipient->id
)
);
$this->assertEqual('pending', $transfer->status);
}
public function testRetrieve()
{
$recipient = self::createTestRecipient();
authorizeFromEnv();
$transfer = Stripe_Transfer::create(
array(
'amount' => 100,
'currency' => 'usd',
'recipient' => $recipient->id
)
);
$reloaded = Stripe_Transfer::retrieve($transfer->id);
$this->assertEqual($reloaded->id, $transfer->id);
}
}

View File

@ -0,0 +1,22 @@
<?php
class Stripe_UtilTest extends UnitTestCase
{
public function testIsList()
{
$list = array(5, 'nstaoush', array());
$this->assertTrue(Stripe_Util::isList($list));
$notlist = array(5, 'nstaoush', array(), 'bar' => 'baz');
$this->assertFalse(Stripe_Util::isList($notlist));
}
public function testThatPHPHasValueSemanticsForArrays()
{
$original = array('php-arrays' => 'value-semantics');
$derived = $original;
$derived['php-arrays'] = 'reference-semantics';
$this->assertEqual('value-semantics', $original['php-arrays']);
}
}

21
webhooks/stripe.php Normal file
View File

@ -0,0 +1,21 @@
<?php
// Verras Portal - Stripe Webhook Handler
require_once __DIR__ . '/../includes/Database.php';
// TODO: Include Stripe PHP SDK
// TODO: Get webhook endpoint secret from settings
// TODO: Verify the Stripe signature from the request header
// Get the request body
$payload = @file_get_contents('php://input');
$event = null;
// TODO: Handle the event (e.g., 'payment_intent.succeeded')
// - Find the order by 'stripe_payment_intent_id'
// - Update the order status to 'succeeded'
http_response_code(200);