installed plugin Easy Digital Downloads version 3.1.0.3

This commit is contained in:
2022-11-27 15:03:07 +00:00
committed by Gitium
parent 555673545b
commit c5dce2cec6
1200 changed files with 238970 additions and 0 deletions

View File

@ -0,0 +1,25 @@
<?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;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInita1abe13511edc0d0d2f910910593934f::getLoader();

View File

@ -0,0 +1,572 @@
<?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 ?string */
private $vendorDir;
// PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
*/
private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
*/
private $missingClasses = array();
/** @var ?string */
private $apcuPrefix;
/**
* @var self[]
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
}
/**
* @return string[]
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
*
* @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 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)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $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 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)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $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] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $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 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 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($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 indexed by their corresponding vendor directories.
*
* @return 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;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
* @private
*/
function includeFile($file)
{
include $file;
}

View File

@ -0,0 +1,352 @@
<?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 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|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 || empty($installed['versions'][$packageName]['dev_requirement']);
}
}
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($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();
}
/**
* @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();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
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 = require __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
$installed[] = self::$installed;
return $installed;
}
}

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.

View File

@ -0,0 +1,10 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);

View File

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

View File

@ -0,0 +1,10 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Stripe\\' => array($vendorDir . '/stripe/stripe-php/lib'),
);

View File

@ -0,0 +1,36 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInita1abe13511edc0d0d2f910910593934f
{
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;
}
spl_autoload_register(array('ComposerAutoloaderInita1abe13511edc0d0d2f910910593934f', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInita1abe13511edc0d0d2f910910593934f', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInita1abe13511edc0d0d2f910910593934f::getInitializer($loader));
$loader->register(true);
return $loader;
}
}

View File

@ -0,0 +1,36 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInita1abe13511edc0d0d2f910910593934f
{
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Stripe\\' => 7,
),
);
public static $prefixDirsPsr4 = array (
'Stripe\\' =>
array (
0 => __DIR__ . '/..' . '/stripe/stripe-php/lib',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInita1abe13511edc0d0d2f910910593934f::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInita1abe13511edc0d0d2f910910593934f::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInita1abe13511edc0d0d2f910910593934f::$classMap;
}, null, ClassLoader::class);
}
}

View File

@ -0,0 +1,70 @@
{
"packages": [
{
"name": "stripe/stripe-php",
"version": "v7.47.0",
"version_normalized": "7.47.0.0",
"source": {
"type": "git",
"url": "https://github.com/stripe/stripe-php.git",
"reference": "b51656cb398d081fcee53a76f6edb8fd5c1a5306"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/stripe/stripe-php/zipball/b51656cb398d081fcee53a76f6edb8fd5c1a5306",
"reference": "b51656cb398d081fcee53a76f6edb8fd5c1a5306",
"shasum": ""
},
"require": {
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"php": ">=5.6.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "2.16.1",
"php-coveralls/php-coveralls": "^2.1",
"phpunit/phpunit": "^5.7",
"squizlabs/php_codesniffer": "^3.3",
"symfony/process": "~3.4"
},
"time": "2020-08-13T22:35:56+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Stripe\\": "lib/"
}
},
"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/v7.47.0"
},
"install-path": "../stripe/stripe-php"
}
],
"dev": false,
"dev-package-names": []
}

View File

@ -0,0 +1,32 @@
<?php return array(
'root' => array(
'name' => 'easy-digital-downloads/edd-stripe',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '829e436e3e0b91ab69528aebcee3344aa2e91eca',
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => false,
),
'versions' => array(
'easy-digital-downloads/edd-stripe' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '829e436e3e0b91ab69528aebcee3344aa2e91eca',
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'stripe/stripe-php' => array(
'pretty_version' => 'v7.47.0',
'version' => '7.47.0.0',
'reference' => 'b51656cb398d081fcee53a76f6edb8fd5c1a5306',
'type' => 'library',
'install_path' => __DIR__ . '/../stripe/stripe-php',
'aliases' => array(),
'dev_requirement' => false,
),
),
);

View File

@ -0,0 +1,77 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at conduct@stripe.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2010-2019 Stripe, Inc. (https://stripe.com)
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.

View File

@ -0,0 +1,36 @@
export PHPDOCUMENTOR_VERSION := v3.0.0-rc
export PHPSTAN_VERSION := 0.12.18
vendor: composer.json
composer install
vendor/bin/phpstan: vendor
curl -sfL https://github.com/phpstan/phpstan/releases/download/$(PHPSTAN_VERSION)/phpstan.phar -o vendor/bin/phpstan
chmod +x vendor/bin/phpstan
vendor/bin/phpdoc: vendor
curl -sfL https://github.com/phpDocumentor/phpDocumentor/releases/download/$(PHPDOCUMENTOR_VERSION)/phpDocumentor.phar -o vendor/bin/phpdoc
chmod +x vendor/bin/phpdoc
test: vendor
vendor/bin/phpunit
.PHONY: test
fmt: vendor
vendor/bin/php-cs-fixer fix -v --using-cache=no .
.PHONY: fmt
fmtcheck: vendor
vendor/bin/php-cs-fixer fix -v --dry-run --using-cache=no .
.PHONY: fmtcheck
phpdoc: vendor/bin/phpdoc
vendor/bin/phpdoc
phpstan: vendor/bin/phpstan
php -d memory_limit=512M vendor/bin/phpstan analyse lib tests
.PHONY: phpstan
phpstan-baseline: vendor/bin/phpstan
php -d memory_limit=512M vendor/bin/phpstan analyse lib tests --generate-baseline
.PHONY: phpstan-baseline

View File

@ -0,0 +1,266 @@
# Stripe PHP bindings
[![Build Status](https://travis-ci.org/stripe/stripe-php.svg?branch=master)](https://travis-ci.org/stripe/stripe-php)
[![Latest Stable Version](https://poser.pugx.org/stripe/stripe-php/v/stable.svg)](https://packagist.org/packages/stripe/stripe-php)
[![Total Downloads](https://poser.pugx.org/stripe/stripe-php/downloads.svg)](https://packagist.org/packages/stripe/stripe-php)
[![License](https://poser.pugx.org/stripe/stripe-php/license.svg)](https://packagist.org/packages/stripe/stripe-php)
[![Code Coverage](https://coveralls.io/repos/stripe/stripe-php/badge.svg?branch=master)](https://coveralls.io/r/stripe/stripe-php?branch=master)
The Stripe PHP library provides convenient access to the Stripe API from
applications written in the PHP language. It includes a pre-defined set of
classes for API resources that initialize themselves dynamically from API
responses which makes it compatible with a wide range of versions of the Stripe
API.
## Requirements
PHP 5.6.0 and later.
## Composer
You can install the bindings via [Composer](http://getcomposer.org/). Run the following command:
```bash
composer require stripe/stripe-php
```
To use the bindings, use Composer's [autoload](https://getcomposer.org/doc/01-basic-usage.md#autoloading):
```php
require_once('vendor/autoload.php');
```
## Manual Installation
If you do not wish to use Composer, you can download the [latest release](https://github.com/stripe/stripe-php/releases). Then, to use the bindings, include the `init.php` file.
```php
require_once('/path/to/stripe-php/init.php');
```
## Dependencies
The bindings require the following extensions in order to work properly:
- [`curl`](https://secure.php.net/manual/en/book.curl.php), although you can use your own non-cURL client if you prefer
- [`json`](https://secure.php.net/manual/en/book.json.php)
- [`mbstring`](https://secure.php.net/manual/en/book.mbstring.php) (Multibyte String)
If you use Composer, these dependencies should be handled automatically. If you install manually, you'll want to make sure that these extensions are available.
## Getting Started
Simple usage looks like:
```php
$stripe = new \Stripe\StripeClient('sk_test_BQokikJOvBiI2HlWgH4olfQ2');
$customer = $stripe->customers->create([
'description' => 'example customer',
'email' => 'email@example.com',
'payment_method' => 'pm_card_visa',
]);
echo $customer;
```
### Client/service patterns vs legacy patterns
You can continue to use the legacy integration patterns used prior to version [7.33.0](https://github.com/stripe/stripe-php/blob/master/CHANGELOG.md#7330---2020-05-14). Review the [migration guide](https://github.com/stripe/stripe-php/wiki/Migration-to-StripeClient-and-services-in-7.33.0) for the backwards-compatible client/services pattern changes.
## Documentation
See the [PHP API docs](https://stripe.com/docs/api/php#intro).
## Legacy Version Support
### PHP 5.4 & 5.5
If you are using PHP 5.4 or 5.5, you can download v6.21.1 ([zip](https://github.com/stripe/stripe-php/archive/v6.21.1.zip), [tar.gz](https://github.com/stripe/stripe-php/archive/v5.9.2.tar.gz)) from our [releases page](https://github.com/stripe/stripe-php/releases). This version will continue to work with new versions of the Stripe API for all common uses.
### PHP 5.3
If you are using PHP 5.3, you can download v5.9.2 ([zip](https://github.com/stripe/stripe-php/archive/v5.9.2.zip), [tar.gz](https://github.com/stripe/stripe-php/archive/v5.9.2.tar.gz)) from our [releases page](https://github.com/stripe/stripe-php/releases). This version will continue to work with new versions of the Stripe API for all common uses.
## Custom Request Timeouts
_NOTE:_ We do not recommend decreasing the timeout for non-read-only calls (e.g. charge creation), since even if you locally timeout, the request on Stripe's side can still complete. If you are decreasing timeouts on these calls, make sure to use [idempotency tokens](https://stripe.com/docs/api/php#idempotent_requests) to avoid executing the same transaction twice as a result of timeout retry logic.
To modify request timeouts (connect or total, in seconds) you'll need to tell the API client to use a CurlClient other than its default. You'll set the timeouts in that CurlClient.
```php
// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient();
$curl->setTimeout(10); // default is \Stripe\HttpClient\CurlClient::DEFAULT_TIMEOUT
$curl->setConnectTimeout(5); // default is \Stripe\HttpClient\CurlClient::DEFAULT_CONNECT_TIMEOUT
echo $curl->getTimeout(); // 10
echo $curl->getConnectTimeout(); // 5
// tell Stripe to use the tweaked client
\Stripe\ApiRequestor::setHttpClient($curl);
// use the Stripe API client as you normally would
```
## Custom cURL Options (e.g. proxies)
Need to set a proxy for your requests? Pass in the requisite `CURLOPT_*` array to the CurlClient constructor, using the same syntax as `curl_stopt_array()`. This will set the default cURL options for each HTTP request made by the SDK, though many more common options (e.g. timeouts; see above on how to set those) will be overridden by the client even if set here.
```php
// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient([CURLOPT_PROXY => 'proxy.local:80']);
// tell Stripe to use the tweaked client
\Stripe\ApiRequestor::setHttpClient($curl);
```
Alternately, a callable can be passed to the CurlClient constructor that returns the above array based on request inputs. See `testDefaultOptions()` in `tests/CurlClientTest.php` for an example of this behavior. Note that the callable is called at the beginning of every API request, before the request is sent.
### Configuring a Logger
The library does minimal logging, but it can be configured
with a [`PSR-3` compatible logger][psr3] so that messages
end up there instead of `error_log`:
```php
\Stripe\Stripe::setLogger($logger);
```
### Accessing response data
You can access the data from the last API response on any object via `getLastResponse()`.
```php
$customer = $stripe->customers->create([
'description' => 'example customer',
]);
echo $customer->getLastResponse()->headers['Request-Id'];
```
### SSL / TLS compatibility issues
Stripe's API now requires that [all connections use TLS 1.2](https://stripe.com/blog/upgrading-tls). Some systems (most notably some older CentOS and RHEL versions) are capable of using TLS 1.2 but will use TLS 1.0 or 1.1 by default. In this case, you'd get an `invalid_request_error` with the following error message: "Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at [https://stripe.com/blog/upgrading-tls](https://stripe.com/blog/upgrading-tls).".
The recommended course of action is to [upgrade your cURL and OpenSSL packages](https://support.stripe.com/questions/how-do-i-upgrade-my-stripe-integration-from-tls-1-0-to-tls-1-2#php) so that TLS 1.2 is used by default, but if that is not possible, you might be able to solve the issue by setting the `CURLOPT_SSLVERSION` option to either `CURL_SSLVERSION_TLSv1` or `CURL_SSLVERSION_TLSv1_2`:
```php
$curl = new \Stripe\HttpClient\CurlClient([CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1]);
\Stripe\ApiRequestor::setHttpClient($curl);
```
### Per-request Configuration
For apps that need to use multiple keys during the lifetime of a process, like
one that uses [Stripe Connect][connect], it's also possible to set a
per-request key and/or account:
```php
$customers = $stripe->customers->all([],[
'api_key' => 'sk_test_...',
'stripe_account' => 'acct_...'
]);
$stripe->customers->retrieve('cus_123456789', [], [
'api_key' => 'sk_test_...',
'stripe_account' => 'acct_...'
]);
```
### Configuring CA Bundles
By default, the library will use its own internal bundle of known CA
certificates, but it's possible to configure your own:
```php
\Stripe\Stripe::setCABundlePath("path/to/ca/bundle");
```
### Configuring Automatic Retries
The library can be configured to automatically retry requests that fail due to
an intermittent network problem:
```php
\Stripe\Stripe::setMaxNetworkRetries(2);
```
[Idempotency keys][idempotency-keys] are added to requests to guarantee that
retries are safe.
### Request latency telemetry
By default, the library sends request latency telemetry to Stripe. These
numbers help Stripe improve the overall latency of its API for all users.
You can disable this behavior if you prefer:
```php
\Stripe\Stripe::setEnableTelemetry(false);
```
## Development
Get [Composer][composer]. For example, on Mac OS:
```bash
brew install composer
```
Install dependencies:
```bash
composer install
```
The test suite depends on [stripe-mock], so make sure to fetch and run it from a
background terminal ([stripe-mock's README][stripe-mock] also contains
instructions for installing via Homebrew and other methods):
```bash
go get -u github.com/stripe/stripe-mock
stripe-mock
```
Install dependencies as mentioned above (which will resolve [PHPUnit](http://packagist.org/packages/phpunit/phpunit)), then you can run the test suite:
```bash
./vendor/bin/phpunit
```
Or to run an individual test file:
```bash
./vendor/bin/phpunit tests/UtilTest.php
```
Update bundled CA certificates from the [Mozilla cURL release][curl]:
```bash
./update_certs.php
```
The library uses [PHP CS Fixer][php-cs-fixer] for code formatting. Code must be formatted before PRs are submitted, otherwise CI will fail. Run the formatter with:
```bash
./vendor/bin/php-cs-fixer fix -v .
```
## Attention plugin developers
Are you writing a plugin that integrates Stripe and embeds our library? Then please use the `setAppInfo` function to identify your plugin. For example:
```php
\Stripe\Stripe::setAppInfo("MyAwesomePlugin", "1.2.34", "https://myawesomeplugin.info");
```
The method should be called once, before any request is sent to the API. The second and third parameters are optional.
### SSL / TLS configuration option
See the "SSL / TLS compatibility issues" paragraph above for full context. If you want to ensure that your plugin can be used on all systems, you should add a configuration option to let your users choose between different values for `CURLOPT_SSLVERSION`: none (default), `CURL_SSLVERSION_TLSv1` and `CURL_SSLVERSION_TLSv1_2`.
[composer]: https://getcomposer.org/
[connect]: https://stripe.com/connect
[curl]: http://curl.haxx.se/docs/caextract.html
[idempotency-keys]: https://stripe.com/docs/api/php#idempotent_requests
[php-cs-fixer]: https://github.com/FriendsOfPHP/PHP-CS-Fixer
[psr3]: http://www.php-fig.org/psr/psr-3/
[stripe-mock]: https://github.com/stripe/stripe-mock

View File

@ -0,0 +1,25 @@
#!/usr/bin/env php
<?php
\chdir(__DIR__);
$autoload = (int) $argv[1];
$returnStatus = null;
if (!$autoload) {
// Modify composer to not autoload Stripe
$composer = \json_decode(\file_get_contents('composer.json'), true);
unset($composer['autoload'], $composer['autoload-dev']);
\file_put_contents('composer.json', \json_encode($composer, \JSON_PRETTY_PRINT));
}
\passthru('composer update', $returnStatus);
if (0 !== $returnStatus) {
exit(1);
}
$config = $autoload ? 'phpunit.xml' : 'phpunit.no_autoload.xml';
\passthru("./vendor/bin/phpunit -c {$config}", $returnStatus);
if (0 !== $returnStatus) {
exit(1);
}

View File

@ -0,0 +1,48 @@
{
"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.6.0",
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*"
},
"require-dev": {
"phpunit/phpunit": "^5.7",
"php-coveralls/php-coveralls": "^2.1",
"squizlabs/php_codesniffer": "^3.3",
"symfony/process": "~3.4",
"friendsofphp/php-cs-fixer": "2.16.1"
},
"autoload": {
"psr-4": {
"Stripe\\": "lib/"
}
},
"autoload-dev": {
"psr-4": {
"Stripe\\": [
"tests/",
"tests/Stripe/"
]
}
},
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
}
}
}

View File

@ -0,0 +1,236 @@
<?php
// File generated from our OpenAPI spec
// Stripe singleton
require __DIR__ . '/lib/Stripe.php';
// Utilities
require __DIR__ . '/lib/Util/CaseInsensitiveArray.php';
require __DIR__ . '/lib/Util/LoggerInterface.php';
require __DIR__ . '/lib/Util/DefaultLogger.php';
require __DIR__ . '/lib/Util/RandomGenerator.php';
require __DIR__ . '/lib/Util/RequestOptions.php';
require __DIR__ . '/lib/Util/Set.php';
require __DIR__ . '/lib/Util/Util.php';
require __DIR__ . '/lib/Util/ObjectTypes.php';
// HttpClient
require __DIR__ . '/lib/HttpClient/ClientInterface.php';
require __DIR__ . '/lib/HttpClient/CurlClient.php';
// Exceptions
require __DIR__ . '/lib/Exception/ExceptionInterface.php';
require __DIR__ . '/lib/Exception/ApiErrorException.php';
require __DIR__ . '/lib/Exception/ApiConnectionException.php';
require __DIR__ . '/lib/Exception/AuthenticationException.php';
require __DIR__ . '/lib/Exception/BadMethodCallException.php';
require __DIR__ . '/lib/Exception/CardException.php';
require __DIR__ . '/lib/Exception/IdempotencyException.php';
require __DIR__ . '/lib/Exception/InvalidArgumentException.php';
require __DIR__ . '/lib/Exception/InvalidRequestException.php';
require __DIR__ . '/lib/Exception/PermissionException.php';
require __DIR__ . '/lib/Exception/RateLimitException.php';
require __DIR__ . '/lib/Exception/SignatureVerificationException.php';
require __DIR__ . '/lib/Exception/UnexpectedValueException.php';
require __DIR__ . '/lib/Exception/UnknownApiErrorException.php';
// OAuth exceptions
require __DIR__ . '/lib/Exception/OAuth/ExceptionInterface.php';
require __DIR__ . '/lib/Exception/OAuth/OAuthErrorException.php';
require __DIR__ . '/lib/Exception/OAuth/InvalidClientException.php';
require __DIR__ . '/lib/Exception/OAuth/InvalidGrantException.php';
require __DIR__ . '/lib/Exception/OAuth/InvalidRequestException.php';
require __DIR__ . '/lib/Exception/OAuth/InvalidScopeException.php';
require __DIR__ . '/lib/Exception/OAuth/UnknownOAuthErrorException.php';
require __DIR__ . '/lib/Exception/OAuth/UnsupportedGrantTypeException.php';
require __DIR__ . '/lib/Exception/OAuth/UnsupportedResponseTypeException.php';
// API operations
require __DIR__ . '/lib/ApiOperations/All.php';
require __DIR__ . '/lib/ApiOperations/Create.php';
require __DIR__ . '/lib/ApiOperations/Delete.php';
require __DIR__ . '/lib/ApiOperations/NestedResource.php';
require __DIR__ . '/lib/ApiOperations/Request.php';
require __DIR__ . '/lib/ApiOperations/Retrieve.php';
require __DIR__ . '/lib/ApiOperations/Update.php';
// Plumbing
require __DIR__ . '/lib/ApiResponse.php';
require __DIR__ . '/lib/RequestTelemetry.php';
require __DIR__ . '/lib/StripeObject.php';
require __DIR__ . '/lib/ApiRequestor.php';
require __DIR__ . '/lib/ApiResource.php';
require __DIR__ . '/lib/SingletonApiResource.php';
require __DIR__ . '/lib/Service/AbstractService.php';
require __DIR__ . '/lib/Service/AbstractServiceFactory.php';
// StripeClient
require __DIR__ . '/lib/StripeClientInterface.php';
require __DIR__ . '/lib/BaseStripeClient.php';
require __DIR__ . '/lib/StripeClient.php';
// Stripe API Resources
require __DIR__ . '/lib/Account.php';
require __DIR__ . '/lib/AccountLink.php';
require __DIR__ . '/lib/AlipayAccount.php';
require __DIR__ . '/lib/ApplePayDomain.php';
require __DIR__ . '/lib/ApplicationFee.php';
require __DIR__ . '/lib/ApplicationFeeRefund.php';
require __DIR__ . '/lib/Balance.php';
require __DIR__ . '/lib/BalanceTransaction.php';
require __DIR__ . '/lib/BankAccount.php';
require __DIR__ . '/lib/BillingPortal/Session.php';
require __DIR__ . '/lib/BitcoinReceiver.php';
require __DIR__ . '/lib/BitcoinTransaction.php';
require __DIR__ . '/lib/Capability.php';
require __DIR__ . '/lib/Card.php';
require __DIR__ . '/lib/Charge.php';
require __DIR__ . '/lib/Checkout/Session.php';
require __DIR__ . '/lib/Collection.php';
require __DIR__ . '/lib/CountrySpec.php';
require __DIR__ . '/lib/Coupon.php';
require __DIR__ . '/lib/CreditNote.php';
require __DIR__ . '/lib/CreditNoteLineItem.php';
require __DIR__ . '/lib/Customer.php';
require __DIR__ . '/lib/CustomerBalanceTransaction.php';
require __DIR__ . '/lib/Discount.php';
require __DIR__ . '/lib/Dispute.php';
require __DIR__ . '/lib/EphemeralKey.php';
require __DIR__ . '/lib/ErrorObject.php';
require __DIR__ . '/lib/Event.php';
require __DIR__ . '/lib/ExchangeRate.php';
require __DIR__ . '/lib/File.php';
require __DIR__ . '/lib/FileLink.php';
require __DIR__ . '/lib/Invoice.php';
require __DIR__ . '/lib/InvoiceItem.php';
require __DIR__ . '/lib/InvoiceLineItem.php';
require __DIR__ . '/lib/Issuing/Authorization.php';
require __DIR__ . '/lib/Issuing/Card.php';
require __DIR__ . '/lib/Issuing/CardDetails.php';
require __DIR__ . '/lib/Issuing/Cardholder.php';
require __DIR__ . '/lib/Issuing/Dispute.php';
require __DIR__ . '/lib/Issuing/Transaction.php';
require __DIR__ . '/lib/LineItem.php';
require __DIR__ . '/lib/LoginLink.php';
require __DIR__ . '/lib/Mandate.php';
require __DIR__ . '/lib/Order.php';
require __DIR__ . '/lib/OrderItem.php';
require __DIR__ . '/lib/OrderReturn.php';
require __DIR__ . '/lib/PaymentIntent.php';
require __DIR__ . '/lib/PaymentMethod.php';
require __DIR__ . '/lib/Payout.php';
require __DIR__ . '/lib/Person.php';
require __DIR__ . '/lib/Plan.php';
require __DIR__ . '/lib/Price.php';
require __DIR__ . '/lib/Product.php';
require __DIR__ . '/lib/PromotionCode.php';
require __DIR__ . '/lib/Radar/EarlyFraudWarning.php';
require __DIR__ . '/lib/Radar/ValueList.php';
require __DIR__ . '/lib/Radar/ValueListItem.php';
require __DIR__ . '/lib/Recipient.php';
require __DIR__ . '/lib/RecipientTransfer.php';
require __DIR__ . '/lib/Refund.php';
require __DIR__ . '/lib/Reporting/ReportRun.php';
require __DIR__ . '/lib/Reporting/ReportType.php';
require __DIR__ . '/lib/Review.php';
require __DIR__ . '/lib/SetupIntent.php';
require __DIR__ . '/lib/Sigma/ScheduledQueryRun.php';
require __DIR__ . '/lib/SKU.php';
require __DIR__ . '/lib/Source.php';
require __DIR__ . '/lib/SourceTransaction.php';
require __DIR__ . '/lib/Subscription.php';
require __DIR__ . '/lib/SubscriptionItem.php';
require __DIR__ . '/lib/SubscriptionSchedule.php';
require __DIR__ . '/lib/TaxId.php';
require __DIR__ . '/lib/TaxRate.php';
require __DIR__ . '/lib/Terminal/ConnectionToken.php';
require __DIR__ . '/lib/Terminal/Location.php';
require __DIR__ . '/lib/Terminal/Reader.php';
require __DIR__ . '/lib/ThreeDSecure.php';
require __DIR__ . '/lib/Token.php';
require __DIR__ . '/lib/Topup.php';
require __DIR__ . '/lib/Transfer.php';
require __DIR__ . '/lib/TransferReversal.php';
require __DIR__ . '/lib/UsageRecord.php';
require __DIR__ . '/lib/UsageRecordSummary.php';
require __DIR__ . '/lib/WebhookEndpoint.php';
// Services
require __DIR__ . '/lib/Service/AccountService.php';
require __DIR__ . '/lib/Service/AccountLinkService.php';
require __DIR__ . '/lib/Service/ApplePayDomainService.php';
require __DIR__ . '/lib/Service/ApplicationFeeService.php';
require __DIR__ . '/lib/Service/BalanceService.php';
require __DIR__ . '/lib/Service/BalanceTransactionService.php';
require __DIR__ . '/lib/Service/BillingPortal/SessionService.php';
require __DIR__ . '/lib/Service/ChargeService.php';
require __DIR__ . '/lib/Service/Checkout/SessionService.php';
require __DIR__ . '/lib/Service/CountrySpecService.php';
require __DIR__ . '/lib/Service/CouponService.php';
require __DIR__ . '/lib/Service/CreditNoteService.php';
require __DIR__ . '/lib/Service/CustomerService.php';
require __DIR__ . '/lib/Service/DisputeService.php';
require __DIR__ . '/lib/Service/EphemeralKeyService.php';
require __DIR__ . '/lib/Service/EventService.php';
require __DIR__ . '/lib/Service/ExchangeRateService.php';
require __DIR__ . '/lib/Service/FileService.php';
require __DIR__ . '/lib/Service/FileLinkService.php';
require __DIR__ . '/lib/Service/InvoiceService.php';
require __DIR__ . '/lib/Service/InvoiceItemService.php';
require __DIR__ . '/lib/Service/Issuing/AuthorizationService.php';
require __DIR__ . '/lib/Service/Issuing/CardService.php';
require __DIR__ . '/lib/Service/Issuing/CardholderService.php';
require __DIR__ . '/lib/Service/Issuing/DisputeService.php';
require __DIR__ . '/lib/Service/Issuing/TransactionService.php';
require __DIR__ . '/lib/Service/MandateService.php';
require __DIR__ . '/lib/Service/OrderService.php';
require __DIR__ . '/lib/Service/OrderReturnService.php';
require __DIR__ . '/lib/Service/PaymentIntentService.php';
require __DIR__ . '/lib/Service/PaymentMethodService.php';
require __DIR__ . '/lib/Service/PayoutService.php';
require __DIR__ . '/lib/Service/PlanService.php';
require __DIR__ . '/lib/Service/PriceService.php';
require __DIR__ . '/lib/Service/ProductService.php';
require __DIR__ . '/lib/Service/PromotionCodeService.php';
require __DIR__ . '/lib/Service/Radar/EarlyFraudWarningService.php';
require __DIR__ . '/lib/Service/Radar/ValueListService.php';
require __DIR__ . '/lib/Service/Radar/ValueListItemService.php';
require __DIR__ . '/lib/Service/RefundService.php';
require __DIR__ . '/lib/Service/Reporting/ReportRunService.php';
require __DIR__ . '/lib/Service/Reporting/ReportTypeService.php';
require __DIR__ . '/lib/Service/ReviewService.php';
require __DIR__ . '/lib/Service/SetupIntentService.php';
require __DIR__ . '/lib/Service/Sigma/ScheduledQueryRunService.php';
require __DIR__ . '/lib/Service/SkuService.php';
require __DIR__ . '/lib/Service/SourceService.php';
require __DIR__ . '/lib/Service/SubscriptionService.php';
require __DIR__ . '/lib/Service/SubscriptionItemService.php';
require __DIR__ . '/lib/Service/SubscriptionScheduleService.php';
require __DIR__ . '/lib/Service/TaxRateService.php';
require __DIR__ . '/lib/Service/Terminal/ConnectionTokenService.php';
require __DIR__ . '/lib/Service/Terminal/LocationService.php';
require __DIR__ . '/lib/Service/Terminal/ReaderService.php';
require __DIR__ . '/lib/Service/TokenService.php';
require __DIR__ . '/lib/Service/TopupService.php';
require __DIR__ . '/lib/Service/TransferService.php';
require __DIR__ . '/lib/Service/WebhookEndpointService.php';
// Service factories
require __DIR__ . '/lib/Service/CoreServiceFactory.php';
require __DIR__ . '/lib/Service/BillingPortal/BillingPortalServiceFactory.php';
require __DIR__ . '/lib/Service/Checkout/CheckoutServiceFactory.php';
require __DIR__ . '/lib/Service/Issuing/IssuingServiceFactory.php';
require __DIR__ . '/lib/Service/Radar/RadarServiceFactory.php';
require __DIR__ . '/lib/Service/Reporting/ReportingServiceFactory.php';
require __DIR__ . '/lib/Service/Sigma/SigmaServiceFactory.php';
require __DIR__ . '/lib/Service/Terminal/TerminalServiceFactory.php';
// OAuth
require __DIR__ . '/lib/OAuth.php';
require __DIR__ . '/lib/OAuthErrorObject.php';
require __DIR__ . '/lib/Service/OAuthService.php';
// Webhooks
require __DIR__ . '/lib/Webhook.php';
require __DIR__ . '/lib/WebhookSignature.php';

View File

@ -0,0 +1,431 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* This is an object representing a Stripe account. You can retrieve it to see
* properties on the account like its current e-mail address or if the account is
* enabled yet to make live charges.
*
* Some properties, marked below, are available only to platforms that want to <a
* href="https://stripe.com/docs/connect/accounts">create and manage Express or
* Custom accounts</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|\Stripe\StripeObject $business_profile Business information about the account.
* @property null|string $business_type The business type.
* @property \Stripe\StripeObject $capabilities
* @property bool $charges_enabled Whether the account can create live charges.
* @property \Stripe\StripeObject $company
* @property string $country The account's country.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $default_currency Three-letter ISO currency code representing the default currency for the account. This must be a currency that <a href="https://stripe.com/docs/payouts">Stripe supports in the account's country</a>.
* @property bool $details_submitted Whether account details have been submitted. Standard accounts cannot receive payouts before this is true.
* @property null|string $email The primary user's email address.
* @property \Stripe\Collection $external_accounts External accounts (bank accounts and debit cards) currently attached to this account
* @property \Stripe\Person $individual <p>This is an object representing a person associated with a Stripe account.</p><p>Related guide: <a href="https://stripe.com/docs/connect/identity-verification-api#person-information">Handling Identity Verification with the API</a>.</p>
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property bool $payouts_enabled Whether Stripe can send payouts to this account.
* @property \Stripe\StripeObject $requirements
* @property null|\Stripe\StripeObject $settings Options for customizing how the account functions within Stripe.
* @property \Stripe\StripeObject $tos_acceptance
* @property string $type The Stripe account type. Can be <code>standard</code>, <code>express</code>, or <code>custom</code>.
*/
class Account extends ApiResource
{
const OBJECT_NAME = 'account';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\NestedResource;
use ApiOperations\Update;
const BUSINESS_TYPE_COMPANY = 'company';
const BUSINESS_TYPE_GOVERNMENT_ENTITY = 'government_entity';
const BUSINESS_TYPE_INDIVIDUAL = 'individual';
const BUSINESS_TYPE_NON_PROFIT = 'non_profit';
const CAPABILITY_CARD_PAYMENTS = 'card_payments';
const CAPABILITY_LEGACY_PAYMENTS = 'legacy_payments';
const CAPABILITY_PLATFORM_PAYMENTS = 'platform_payments';
const CAPABILITY_TRANSFERS = 'transfers';
const CAPABILITY_STATUS_ACTIVE = 'active';
const CAPABILITY_STATUS_INACTIVE = 'inactive';
const CAPABILITY_STATUS_PENDING = 'pending';
const TYPE_CUSTOM = 'custom';
const TYPE_EXPRESS = 'express';
const TYPE_STANDARD = 'standard';
use ApiOperations\Retrieve {
retrieve as protected _retrieve;
}
public static function getSavedNestedResources()
{
static $savedNestedResources = null;
if (null === $savedNestedResources) {
$savedNestedResources = new Util\Set([
'external_account',
'bank_account',
]);
}
return $savedNestedResources;
}
public function instanceUrl()
{
if (null === $this['id']) {
return '/v1/account';
}
return parent::instanceUrl();
}
public function serializeParameters($force = false)
{
$update = parent::serializeParameters($force);
if (isset($this->_values['legal_entity'])) {
$entity = $this['legal_entity'];
if (isset($entity->_values['additional_owners'])) {
$owners = $entity['additional_owners'];
$entityUpdate = isset($update['legal_entity']) ? $update['legal_entity'] : [];
$entityUpdate['additional_owners'] = $this->serializeAdditionalOwners($entity, $owners);
$update['legal_entity'] = $entityUpdate;
}
}
if (isset($this->_values['individual'])) {
$individual = $this['individual'];
if (($individual instanceof Person) && !isset($update['individual'])) {
$update['individual'] = $individual->serializeParameters($force);
}
}
return $update;
}
private function serializeAdditionalOwners($legalEntity, $additionalOwners)
{
if (isset($legalEntity->_originalValues['additional_owners'])) {
$originalValue = $legalEntity->_originalValues['additional_owners'];
} else {
$originalValue = [];
}
if (($originalValue) && (\count($originalValue) > \count($additionalOwners))) {
throw new Exception\InvalidArgumentException(
'You cannot delete an item from an array, you must instead set a new array'
);
}
$updateArr = [];
foreach ($additionalOwners as $i => $v) {
$update = ($v instanceof StripeObject) ? $v->serializeParameters() : $v;
if ($update !== []) {
if (!$originalValue ||
!\array_key_exists($i, $originalValue) ||
($update !== $legalEntity->serializeParamsValue($originalValue[$i], null, false, true))) {
$updateArr[$i] = $update;
}
}
}
return $updateArr;
}
/**
* @param null|array|string $id the ID of the account to retrieve, or an
* options array containing an `id` key
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Account
*/
public static function retrieve($id = null, $opts = null)
{
if (!$opts && \is_string($id) && 'sk_' === \substr($id, 0, 3)) {
$opts = $id;
$id = null;
}
return self::_retrieve($id, $opts);
}
/**
* @param null|array $clientId
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\StripeObject object containing the response from the API
*/
public function deauthorize($clientId = null, $opts = null)
{
$params = [
'client_id' => $clientId,
'stripe_user_id' => $this->id,
];
return OAuth::deauthorize($params, $opts);
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of persons
*/
public function persons($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/persons';
list($response, $opts) = $this->_request('get', $url, $params, $opts);
$obj = Util\Util::convertToStripeObject($response, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Account the rejected account
*/
public function reject($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/reject';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
/*
* Capabilities methods
* We can not add the capabilities() method today as the Account object already has a
* capabilities property which is a hash and not the sub-list of capabilities.
*/
const PATH_CAPABILITIES = '/capabilities';
/**
* @param string $id the ID of the account on which to retrieve the capabilities
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of capabilities
*/
public static function allCapabilities($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_CAPABILITIES, $params, $opts);
}
/**
* @param string $id the ID of the account to which the capability belongs
* @param string $capabilityId the ID of the capability to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Capability
*/
public static function retrieveCapability($id, $capabilityId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_CAPABILITIES, $capabilityId, $params, $opts);
}
/**
* @param string $id the ID of the account to which the capability belongs
* @param string $capabilityId the ID of the capability to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Capability
*/
public static function updateCapability($id, $capabilityId, $params = null, $opts = null)
{
return self::_updateNestedResource($id, static::PATH_CAPABILITIES, $capabilityId, $params, $opts);
}
const PATH_EXTERNAL_ACCOUNTS = '/external_accounts';
/**
* @param string $id the ID of the account on which to retrieve the external accounts
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of external accounts (BankAccount or Card)
*/
public static function allExternalAccounts($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_EXTERNAL_ACCOUNTS, $params, $opts);
}
/**
* @param string $id the ID of the account on which to create the external account
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\BankAccount|\Stripe\Card
*/
public static function createExternalAccount($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_EXTERNAL_ACCOUNTS, $params, $opts);
}
/**
* @param string $id the ID of the account to which the external account belongs
* @param string $externalAccountId the ID of the external account to delete
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\BankAccount|\Stripe\Card
*/
public static function deleteExternalAccount($id, $externalAccountId, $params = null, $opts = null)
{
return self::_deleteNestedResource($id, static::PATH_EXTERNAL_ACCOUNTS, $externalAccountId, $params, $opts);
}
/**
* @param string $id the ID of the account to which the external account belongs
* @param string $externalAccountId the ID of the external account to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\BankAccount|\Stripe\Card
*/
public static function retrieveExternalAccount($id, $externalAccountId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_EXTERNAL_ACCOUNTS, $externalAccountId, $params, $opts);
}
/**
* @param string $id the ID of the account to which the external account belongs
* @param string $externalAccountId the ID of the external account to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\BankAccount|\Stripe\Card
*/
public static function updateExternalAccount($id, $externalAccountId, $params = null, $opts = null)
{
return self::_updateNestedResource($id, static::PATH_EXTERNAL_ACCOUNTS, $externalAccountId, $params, $opts);
}
const PATH_LOGIN_LINKS = '/login_links';
/**
* @param string $id the ID of the account on which to create the login link
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\LoginLink
*/
public static function createLoginLink($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_LOGIN_LINKS, $params, $opts);
}
const PATH_PERSONS = '/persons';
/**
* @param string $id the ID of the account on which to retrieve the persons
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of persons
*/
public static function allPersons($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_PERSONS, $params, $opts);
}
/**
* @param string $id the ID of the account on which to create the person
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Person
*/
public static function createPerson($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_PERSONS, $params, $opts);
}
/**
* @param string $id the ID of the account to which the person belongs
* @param string $personId the ID of the person to delete
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Person
*/
public static function deletePerson($id, $personId, $params = null, $opts = null)
{
return self::_deleteNestedResource($id, static::PATH_PERSONS, $personId, $params, $opts);
}
/**
* @param string $id the ID of the account to which the person belongs
* @param string $personId the ID of the person to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Person
*/
public static function retrievePerson($id, $personId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_PERSONS, $personId, $params, $opts);
}
/**
* @param string $id the ID of the account to which the person belongs
* @param string $personId the ID of the person to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Person
*/
public static function updatePerson($id, $personId, $params = null, $opts = null)
{
return self::_updateNestedResource($id, static::PATH_PERSONS, $personId, $params, $opts);
}
}

View File

@ -0,0 +1,26 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Account Links are the means by which a Connect platform grants a connected
* account permission to access Stripe-hosted applications, such as Connect
* Onboarding.
*
* Related guide: <a
* href="https://stripe.com/docs/connect/connect-onboarding">Connect
* Onboarding</a>.
*
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property int $expires_at The timestamp at which this account link will expire.
* @property string $url The URL for the account link.
*/
class AccountLink extends ApiResource
{
const OBJECT_NAME = 'account_link';
use ApiOperations\Create;
}

View File

@ -0,0 +1,75 @@
<?php
namespace Stripe;
/**
* Class AlipayAccount.
*
* @deprecated Alipay accounts are deprecated. Please use the sources API instead.
* @see https://stripe.com/docs/sources/alipay
*/
class AlipayAccount extends ApiResource
{
const OBJECT_NAME = 'alipay_account';
use ApiOperations\Delete;
use ApiOperations\Update;
/**
* @return string The instance URL for this resource. It needs to be special
* cased because it doesn't fit into the standard resource pattern.
*/
public function instanceUrl()
{
if ($this['customer']) {
$base = Customer::classUrl();
$parent = $this['customer'];
$path = 'sources';
} else {
$msg = 'Alipay accounts cannot be accessed without a customer ID.';
throw new Exception\UnexpectedValueException($msg);
}
$parentExtn = \urlencode(Util\Util::utf8($parent));
$extn = \urlencode(Util\Util::utf8($this['id']));
return "{$base}/{$parentExtn}/{$path}/{$extn}";
}
/**
* @param array|string $_id
* @param null|array|string $_opts
*
* @throws \Stripe\Exception\BadMethodCallException
*
* @deprecated Alipay accounts are deprecated. Please use the sources API instead.
* @see https://stripe.com/docs/sources/alipay
*/
public static function retrieve($_id, $_opts = null)
{
$msg = 'Alipay accounts cannot be retrieved without a customer ID. ' .
'Retrieve an Alipay account using `Customer::retrieveSource(' .
"'customer_id', 'alipay_account_id')`.";
throw new Exception\BadMethodCallException($msg);
}
/**
* @param string $_id
* @param null|array $_params
* @param null|array|string $_options
*
* @throws \Stripe\Exception\BadMethodCallException
*
* @deprecated Alipay accounts are deprecated. Please use the sources API instead.
* @see https://stripe.com/docs/sources/alipay
*/
public static function update($_id, $_params = null, $_options = null)
{
$msg = 'Alipay accounts cannot be updated without a customer ID. ' .
'Update an Alipay account using `Customer::updateSource(' .
"'customer_id', 'alipay_account_id', \$updateParams)`.";
throw new Exception\BadMethodCallException($msg);
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for listable resources. Adds a `all()` static method to the class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait All
{
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection of ApiResources
*/
public static function all($params = null, $opts = null)
{
self::_validateParams($params);
$url = static::classUrl();
list($response, $opts) = static::_staticRequest('get', $url, $params, $opts);
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
if (!($obj instanceof \Stripe\Collection)) {
throw new \Stripe\Exception\UnexpectedValueException(
'Expected type ' . \Stripe\Collection::class . ', got "' . \get_class($obj) . '" instead.'
);
}
$obj->setLastResponse($response);
$obj->setFilters($params);
return $obj;
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for creatable resources. Adds a `create()` static method to the class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Create
{
/**
* @param null|array $params
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return static the created resource
*/
public static function create($params = null, $options = null)
{
self::_validateParams($params);
$url = static::classUrl();
list($response, $opts) = static::_staticRequest('post', $url, $params, $options);
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for deletable resources. Adds a `delete()` method to the class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Delete
{
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return static the deleted resource
*/
public function delete($params = null, $opts = null)
{
self::_validateParams($params);
$url = $this->instanceUrl();
list($response, $opts) = $this->_request('delete', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}

View File

@ -0,0 +1,135 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for resources that have nested resources.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait NestedResource
{
/**
* @param string $method
* @param string $url
* @param null|array $params
* @param null|array|string $options
*
* @return \Stripe\StripeObject
*/
protected static function _nestedResourceOperation($method, $url, $params = null, $options = null)
{
self::_validateParams($params);
list($response, $opts) = static::_staticRequest($method, $url, $params, $options);
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* @param string $id
* @param string $nestedPath
* @param null|string $nestedId
*
* @return string
*/
protected static function _nestedResourceUrl($id, $nestedPath, $nestedId = null)
{
$url = static::resourceUrl($id) . $nestedPath;
if (null !== $nestedId) {
$url .= "/{$nestedId}";
}
return $url;
}
/**
* @param string $id
* @param string $nestedPath
* @param null|array $params
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\StripeObject
*/
protected static function _createNestedResource($id, $nestedPath, $params = null, $options = null)
{
$url = static::_nestedResourceUrl($id, $nestedPath);
return self::_nestedResourceOperation('post', $url, $params, $options);
}
/**
* @param string $id
* @param string $nestedPath
* @param null|string $nestedId
* @param null|array $params
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\StripeObject
*/
protected static function _retrieveNestedResource($id, $nestedPath, $nestedId, $params = null, $options = null)
{
$url = static::_nestedResourceUrl($id, $nestedPath, $nestedId);
return self::_nestedResourceOperation('get', $url, $params, $options);
}
/**
* @param string $id
* @param string $nestedPath
* @param null|string $nestedId
* @param null|array $params
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\StripeObject
*/
protected static function _updateNestedResource($id, $nestedPath, $nestedId, $params = null, $options = null)
{
$url = static::_nestedResourceUrl($id, $nestedPath, $nestedId);
return self::_nestedResourceOperation('post', $url, $params, $options);
}
/**
* @param string $id
* @param string $nestedPath
* @param null|string $nestedId
* @param null|array $params
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\StripeObject
*/
protected static function _deleteNestedResource($id, $nestedPath, $nestedId, $params = null, $options = null)
{
$url = static::_nestedResourceUrl($id, $nestedPath, $nestedId);
return self::_nestedResourceOperation('delete', $url, $params, $options);
}
/**
* @param string $id
* @param string $nestedPath
* @param null|array $params
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\StripeObject
*/
protected static function _allNestedResources($id, $nestedPath, $params = null, $options = null)
{
$url = static::_nestedResourceUrl($id, $nestedPath);
return self::_nestedResourceOperation('get', $url, $params, $options);
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for resources that need to make API requests.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Request
{
/**
* @param null|array|mixed $params The list of parameters to validate
*
* @throws \Stripe\Exception\InvalidArgumentException if $params exists and is not an array
*/
protected static function _validateParams($params = null)
{
if ($params && !\is_array($params)) {
$message = 'You must pass an array as the first argument to Stripe API '
. 'method calls. (HINT: an example call to create a charge '
. "would be: \"Stripe\\Charge::create(['amount' => 100, "
. "'currency' => 'usd', 'source' => 'tok_1234'])\")";
throw new \Stripe\Exception\InvalidArgumentException($message);
}
}
/**
* @param string $method HTTP method ('get', 'post', etc.)
* @param string $url URL for the request
* @param array $params list of parameters for the request
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return array tuple containing (the JSON response, $options)
*/
protected function _request($method, $url, $params = [], $options = null)
{
$opts = $this->_opts->merge($options);
list($resp, $options) = static::_staticRequest($method, $url, $params, $opts);
$this->setLastResponse($resp);
return [$resp->json, $options];
}
/**
* @param string $method HTTP method ('get', 'post', etc.)
* @param string $url URL for the request
* @param array $params list of parameters for the request
* @param null|array|string $options
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return array tuple containing (the JSON response, $options)
*/
protected static function _staticRequest($method, $url, $params, $options)
{
$opts = \Stripe\Util\RequestOptions::parse($options);
$baseUrl = isset($opts->apiBase) ? $opts->apiBase : static::baseUrl();
$requestor = new \Stripe\ApiRequestor($opts->apiKey, $baseUrl);
list($response, $opts->apiKey) = $requestor->request($method, $url, $params, $opts->headers);
$opts->discardNonPersistentHeaders();
return [$response, $opts];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for retrievable resources. Adds a `retrieve()` static method to the
* class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Retrieve
{
/**
* @param array|string $id the ID of the API resource to retrieve,
* or an options array containing an `id` key
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return static
*/
public static function retrieve($id, $opts = null)
{
$opts = \Stripe\Util\RequestOptions::parse($opts);
$instance = new static($id, $opts);
$instance->refresh();
return $instance;
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace Stripe\ApiOperations;
/**
* Trait for updatable resources. Adds an `update()` static method and a
* `save()` method to the class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Update
{
/**
* @param string $id the ID of the resource to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return static the updated resource
*/
public static function update($id, $params = null, $opts = null)
{
self::_validateParams($params);
$url = static::resourceUrl($id);
list($response, $opts) = static::_staticRequest('post', $url, $params, $opts);
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return static the saved resource
*/
public function save($opts = null)
{
$params = $this->serializeParameters();
if (\count($params) > 0) {
$url = $this->instanceUrl();
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
}
return $this;
}
}

View File

@ -0,0 +1,475 @@
<?php
namespace Stripe;
/**
* Class ApiRequestor.
*/
class ApiRequestor
{
/**
* @var null|string
*/
private $_apiKey;
/**
* @var string
*/
private $_apiBase;
/**
* @var HttpClient\ClientInterface
*/
private static $_httpClient;
/**
* @var RequestTelemetry
*/
private static $requestTelemetry;
/**
* ApiRequestor constructor.
*
* @param null|string $apiKey
* @param null|string $apiBase
*/
public function __construct($apiKey = null, $apiBase = null)
{
$this->_apiKey = $apiKey;
if (!$apiBase) {
$apiBase = Stripe::$apiBase;
}
$this->_apiBase = $apiBase;
}
/**
* Creates a telemetry json blob for use in 'X-Stripe-Client-Telemetry' headers.
*
* @static
*
* @param RequestTelemetry $requestTelemetry
*
* @return string
*/
private static function _telemetryJson($requestTelemetry)
{
$payload = [
'last_request_metrics' => [
'request_id' => $requestTelemetry->requestId,
'request_duration_ms' => $requestTelemetry->requestDuration,
],
];
$result = \json_encode($payload);
if (false !== $result) {
return $result;
}
Stripe::getLogger()->error('Serializing telemetry payload failed!');
return '{}';
}
/**
* @static
*
* @param ApiResource|array|bool|mixed $d
*
* @return ApiResource|array|mixed|string
*/
private static function _encodeObjects($d)
{
if ($d instanceof ApiResource) {
return Util\Util::utf8($d->id);
}
if (true === $d) {
return 'true';
}
if (false === $d) {
return 'false';
}
if (\is_array($d)) {
$res = [];
foreach ($d as $k => $v) {
$res[$k] = self::_encodeObjects($v);
}
return $res;
}
return Util\Util::utf8($d);
}
/**
* @param string $method
* @param string $url
* @param null|array $params
* @param null|array $headers
*
* @throws Exception\ApiErrorException
*
* @return array tuple containing (ApiReponse, API key)
*/
public function request($method, $url, $params = null, $headers = null)
{
$params = $params ?: [];
$headers = $headers ?: [];
list($rbody, $rcode, $rheaders, $myApiKey) =
$this->_requestRaw($method, $url, $params, $headers);
$json = $this->_interpretResponse($rbody, $rcode, $rheaders);
$resp = new ApiResponse($rbody, $rcode, $rheaders, $json);
return [$resp, $myApiKey];
}
/**
* @param string $rbody a JSON string
* @param int $rcode
* @param array $rheaders
* @param array $resp
*
* @throws Exception\UnexpectedValueException
* @throws Exception\ApiErrorException
*/
public function handleErrorResponse($rbody, $rcode, $rheaders, $resp)
{
if (!\is_array($resp) || !isset($resp['error'])) {
$msg = "Invalid response object from API: {$rbody} "
. "(HTTP response code was {$rcode})";
throw new Exception\UnexpectedValueException($msg);
}
$errorData = $resp['error'];
$error = null;
if (\is_string($errorData)) {
$error = self::_specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorData);
}
if (!$error) {
$error = self::_specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData);
}
throw $error;
}
/**
* @static
*
* @param string $rbody
* @param int $rcode
* @param array $rheaders
* @param array $resp
* @param array $errorData
*
* @return Exception\ApiErrorException
*/
private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData)
{
$msg = isset($errorData['message']) ? $errorData['message'] : null;
$param = isset($errorData['param']) ? $errorData['param'] : null;
$code = isset($errorData['code']) ? $errorData['code'] : null;
$type = isset($errorData['type']) ? $errorData['type'] : null;
$declineCode = isset($errorData['decline_code']) ? $errorData['decline_code'] : null;
switch ($rcode) {
case 400:
// 'rate_limit' code is deprecated, but left here for backwards compatibility
// for API versions earlier than 2015-09-08
if ('rate_limit' === $code) {
return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
}
if ('idempotency_error' === $type) {
return Exception\IdempotencyException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
}
// no break
case 404:
return Exception\InvalidRequestException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
case 401:
return Exception\AuthenticationException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
case 402:
return Exception\CardException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $declineCode, $param);
case 403:
return Exception\PermissionException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
case 429:
return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
default:
return Exception\UnknownApiErrorException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
}
}
/**
* @static
*
* @param bool|string $rbody
* @param int $rcode
* @param array $rheaders
* @param array $resp
* @param string $errorCode
*
* @return Exception\OAuth\OAuthErrorException
*/
private static function _specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorCode)
{
$description = isset($resp['error_description']) ? $resp['error_description'] : $errorCode;
switch ($errorCode) {
case 'invalid_client':
return Exception\OAuth\InvalidClientException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
case 'invalid_grant':
return Exception\OAuth\InvalidGrantException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
case 'invalid_request':
return Exception\OAuth\InvalidRequestException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
case 'invalid_scope':
return Exception\OAuth\InvalidScopeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
case 'unsupported_grant_type':
return Exception\OAuth\UnsupportedGrantTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
case 'unsupported_response_type':
return Exception\OAuth\UnsupportedResponseTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
default:
return Exception\OAuth\UnknownOAuthErrorException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
}
}
/**
* @static
*
* @param null|array $appInfo
*
* @return null|string
*/
private static function _formatAppInfo($appInfo)
{
if (null !== $appInfo) {
$string = $appInfo['name'];
if (null !== $appInfo['version']) {
$string .= '/' . $appInfo['version'];
}
if (null !== $appInfo['url']) {
$string .= ' (' . $appInfo['url'] . ')';
}
return $string;
}
return null;
}
/**
* @static
*
* @param string $apiKey
* @param null $clientInfo
*
* @return array
*/
private static function _defaultHeaders($apiKey, $clientInfo = null)
{
$uaString = 'Stripe/v1 PhpBindings/' . Stripe::VERSION;
$langVersion = \PHP_VERSION;
$uname_disabled = \in_array('php_uname', \explode(',', \ini_get('disable_functions')), true);
$uname = $uname_disabled ? '(disabled)' : \php_uname();
$appInfo = Stripe::getAppInfo();
$ua = [
'bindings_version' => Stripe::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'stripe',
'uname' => $uname,
];
if ($clientInfo) {
$ua = \array_merge($clientInfo, $ua);
}
if (null !== $appInfo) {
$uaString .= ' ' . self::_formatAppInfo($appInfo);
$ua['application'] = $appInfo;
}
return [
'X-Stripe-Client-User-Agent' => \json_encode($ua),
'User-Agent' => $uaString,
'Authorization' => 'Bearer ' . $apiKey,
];
}
/**
* @param string $method
* @param string $url
* @param array $params
* @param array $headers
*
* @throws Exception\AuthenticationException
* @throws Exception\ApiConnectionException
*
* @return array
*/
private function _requestRaw($method, $url, $params, $headers)
{
$myApiKey = $this->_apiKey;
if (!$myApiKey) {
$myApiKey = Stripe::$apiKey;
}
if (!$myApiKey) {
$msg = '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.';
throw new Exception\AuthenticationException($msg);
}
// Clients can supply arbitrary additional keys to be included in the
// X-Stripe-Client-User-Agent header via the optional getUserAgentInfo()
// method
$clientUAInfo = null;
if (\method_exists($this->httpClient(), 'getUserAgentInfo')) {
$clientUAInfo = $this->httpClient()->getUserAgentInfo();
}
$absUrl = $this->_apiBase . $url;
$params = self::_encodeObjects($params);
$defaultHeaders = $this->_defaultHeaders($myApiKey, $clientUAInfo);
if (Stripe::$apiVersion) {
$defaultHeaders['Stripe-Version'] = Stripe::$apiVersion;
}
if (Stripe::$accountId) {
$defaultHeaders['Stripe-Account'] = Stripe::$accountId;
}
if (Stripe::$enableTelemetry && null !== self::$requestTelemetry) {
$defaultHeaders['X-Stripe-Client-Telemetry'] = self::_telemetryJson(self::$requestTelemetry);
}
$hasFile = false;
foreach ($params as $k => $v) {
if (\is_resource($v)) {
$hasFile = true;
$params[$k] = self::_processResourceParam($v);
} elseif ($v instanceof \CURLFile) {
$hasFile = true;
}
}
if ($hasFile) {
$defaultHeaders['Content-Type'] = 'multipart/form-data';
} else {
$defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
$combinedHeaders = \array_merge($defaultHeaders, $headers);
$rawHeaders = [];
foreach ($combinedHeaders as $header => $value) {
$rawHeaders[] = $header . ': ' . $value;
}
$requestStartMs = Util\Util::currentTimeMillis();
list($rbody, $rcode, $rheaders) = $this->httpClient()->request(
$method,
$absUrl,
$rawHeaders,
$params,
$hasFile
);
if (isset($rheaders['request-id'], $rheaders['request-id'][0])) {
self::$requestTelemetry = new RequestTelemetry(
$rheaders['request-id'][0],
Util\Util::currentTimeMillis() - $requestStartMs
);
}
return [$rbody, $rcode, $rheaders, $myApiKey];
}
/**
* @param resource $resource
*
* @throws Exception\InvalidArgumentException
*
* @return \CURLFile|string
*/
private function _processResourceParam($resource)
{
if ('stream' !== \get_resource_type($resource)) {
throw new Exception\InvalidArgumentException(
'Attempted to upload a resource that is not a stream'
);
}
$metaData = \stream_get_meta_data($resource);
if ('plainfile' !== $metaData['wrapper_type']) {
throw new Exception\InvalidArgumentException(
'Only plainfile resource streams are supported'
);
}
// We don't have the filename or mimetype, but the API doesn't care
return new \CURLFile($metaData['uri']);
}
/**
* @param string $rbody
* @param int $rcode
* @param array $rheaders
*
* @throws Exception\UnexpectedValueException
* @throws Exception\ApiErrorException
*
* @return array
*/
private function _interpretResponse($rbody, $rcode, $rheaders)
{
$resp = \json_decode($rbody, true);
$jsonError = \json_last_error();
if (null === $resp && \JSON_ERROR_NONE !== $jsonError) {
$msg = "Invalid response body from API: {$rbody} "
. "(HTTP response code was {$rcode}, json_last_error() was {$jsonError})";
throw new Exception\UnexpectedValueException($msg, $rcode);
}
if ($rcode < 200 || $rcode >= 300) {
$this->handleErrorResponse($rbody, $rcode, $rheaders, $resp);
}
return $resp;
}
/**
* @static
*
* @param HttpClient\ClientInterface $client
*/
public static function setHttpClient($client)
{
self::$_httpClient = $client;
}
/**
* @static
*
* Resets any stateful telemetry data
*/
public static function resetTelemetry()
{
self::$requestTelemetry = null;
}
/**
* @return HttpClient\ClientInterface
*/
private function httpClient()
{
if (!self::$_httpClient) {
self::$_httpClient = HttpClient\CurlClient::instance();
}
return self::$_httpClient;
}
}

View File

@ -0,0 +1,120 @@
<?php
namespace Stripe;
/**
* Class ApiResource.
*/
abstract class ApiResource extends StripeObject
{
use ApiOperations\Request;
/**
* @return \Stripe\Util\Set A list of fields that can be their own type of
* API resource (say a nested card under an account for example), and if
* that resource is set, it should be transmitted to the API on a create or
* update. Doing so is not the default behavior because API resources
* should normally be persisted on their own RESTful endpoints.
*/
public static function getSavedNestedResources()
{
static $savedNestedResources = null;
if (null === $savedNestedResources) {
$savedNestedResources = new Util\Set();
}
return $savedNestedResources;
}
/**
* @var bool A flag that can be set a behavior that will cause this
* resource to be encoded and sent up along with an update of its parent
* resource. This is usually not desirable because resources are updated
* individually on their own endpoints, but there are certain cases,
* replacing a customer's source for example, where this is allowed.
*/
public $saveWithParent = false;
public function __set($k, $v)
{
parent::__set($k, $v);
$v = $this->{$k};
if ((static::getSavedNestedResources()->includes($k)) &&
($v instanceof ApiResource)) {
$v->saveWithParent = true;
}
}
/**
* @throws Exception\ApiErrorException
*
* @return ApiResource the refreshed resource
*/
public function refresh()
{
$requestor = new ApiRequestor($this->_opts->apiKey, static::baseUrl());
$url = $this->instanceUrl();
list($response, $this->_opts->apiKey) = $requestor->request(
'get',
$url,
$this->_retrieveOptions,
$this->_opts->headers
);
$this->setLastResponse($response);
$this->refreshFrom($response->json, $this->_opts);
return $this;
}
/**
* @return string the base URL for the given class
*/
public static function baseUrl()
{
return Stripe::$apiBase;
}
/**
* @return string the endpoint URL for the given class
*/
public static function classUrl()
{
// Replace dots with slashes for namespaced resources, e.g. if the object's name is
// "foo.bar", then its URL will be "/v1/foo/bars".
$base = \str_replace('.', '/', static::OBJECT_NAME);
return "/v1/{$base}s";
}
/**
* @param null|string $id the ID of the resource
*
* @throws Exception\UnexpectedValueException if $id is null
*
* @return string the instance endpoint URL for the given class
*/
public static function resourceUrl($id)
{
if (null === $id) {
$class = static::class;
$message = 'Could not determine which URL to request: '
. "{$class} instance has invalid ID: {$id}";
throw new Exception\UnexpectedValueException($message);
}
$id = Util\Util::utf8($id);
$base = static::classUrl();
$extn = \urlencode($id);
return "{$base}/{$extn}";
}
/**
* @return string the full API URL for this API resource
*/
public function instanceUrl()
{
return static::resourceUrl($this['id']);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace Stripe;
use Stripe\Util\CaseInsensitiveArray;
/**
* Class ApiResponse.
*/
class ApiResponse
{
/**
* @var null|array|CaseInsensitiveArray
*/
public $headers;
/**
* @var string
*/
public $body;
/**
* @var null|array
*/
public $json;
/**
* @var int
*/
public $code;
/**
* @param string $body
* @param int $code
* @param null|array|CaseInsensitiveArray $headers
* @param null|array $json
*/
public function __construct($body, $code, $headers, $json)
{
$this->body = $body;
$this->code = $code;
$this->headers = $headers;
$this->json = $json;
}
}

View File

@ -0,0 +1,31 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $domain_name
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
*/
class ApplePayDomain extends ApiResource
{
const OBJECT_NAME = 'apple_pay_domain';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\Retrieve;
/**
* @return string The class URL for this resource. It needs to be special
* cased because it doesn't fit into the standard resource pattern.
*/
public static function classUrl()
{
return '/v1/apple_pay/domains';
}
}

View File

@ -0,0 +1,90 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property string|\Stripe\Account $account ID of the Stripe account this fee was taken from.
* @property int $amount Amount earned, in %s.
* @property int $amount_refunded Amount in %s refunded (can be less than the amount attribute on the fee if a partial refund was issued)
* @property string|\Stripe\StripeObject $application ID of the Connect application that earned the fee.
* @property null|string|\Stripe\BalanceTransaction $balance_transaction Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds).
* @property string|\Stripe\Charge $charge ID of the charge that the application fee was taken from.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|string|\Stripe\Charge $originating_transaction ID of the corresponding charge on the platform account, if this fee was the result of a charge using the <code>destination</code> parameter.
* @property bool $refunded Whether the fee has been fully refunded. If the fee is only partially refunded, this attribute will still be false.
* @property \Stripe\Collection $refunds A list of refunds that have been applied to the fee.
*/
class ApplicationFee extends ApiResource
{
const OBJECT_NAME = 'application_fee';
use ApiOperations\All;
use ApiOperations\NestedResource;
use ApiOperations\Retrieve;
const PATH_REFUNDS = '/refunds';
/**
* @param string $id the ID of the application fee on which to retrieve the fee refunds
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of fee refunds
*/
public static function allRefunds($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_REFUNDS, $params, $opts);
}
/**
* @param string $id the ID of the application fee on which to create the fee refund
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\ApplicationFeeRefund
*/
public static function createRefund($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_REFUNDS, $params, $opts);
}
/**
* @param string $id the ID of the application fee to which the fee refund belongs
* @param string $refundId the ID of the fee refund to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\ApplicationFeeRefund
*/
public static function retrieveRefund($id, $refundId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_REFUNDS, $refundId, $params, $opts);
}
/**
* @param string $id the ID of the application fee to which the fee refund belongs
* @param string $refundId the ID of the fee refund to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\ApplicationFeeRefund
*/
public static function updateRefund($id, $refundId, $params = null, $opts = null)
{
return self::_updateNestedResource($id, static::PATH_REFUNDS, $refundId, $params, $opts);
}
}

View File

@ -0,0 +1,66 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* <code>Application Fee Refund</code> objects allow you to refund an application
* fee that has previously been created but not yet refunded. Funds will be
* refunded to the Stripe account from which the fee was originally collected.
*
* Related guide: <a
* href="https://stripe.com/docs/connect/destination-charges#refunding-app-fee">Refunding
* Application Fees</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount Amount, in %s.
* @property null|string|\Stripe\BalanceTransaction $balance_transaction Balance transaction that describes the impact on your account balance.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property string|\Stripe\ApplicationFee $fee ID of the application fee that was refunded.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
*/
class ApplicationFeeRefund extends ApiResource
{
const OBJECT_NAME = 'fee_refund';
use ApiOperations\Update {
save as protected _save;
}
/**
* @return string the API URL for this Stripe refund
*/
public function instanceUrl()
{
$id = $this['id'];
$fee = $this['fee'];
if (!$id) {
throw new Exception\UnexpectedValueException(
'Could not determine which URL to request: ' .
"class instance has invalid ID: {$id}",
null
);
}
$id = Util\Util::utf8($id);
$fee = Util\Util::utf8($fee);
$base = ApplicationFee::classUrl();
$feeExtn = \urlencode($fee);
$extn = \urlencode($id);
return "{$base}/{$feeExtn}/refunds/{$extn}";
}
/**
* @param null|array|string $opts
*
* @return ApplicationFeeRefund the saved refund
*/
public function save($opts = null)
{
return $this->_save($opts);
}
}

View File

@ -0,0 +1,44 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* This is an object representing your Stripe balance. You can retrieve it to see
* the balance currently on your Stripe account.
*
* You can also retrieve the balance history, which contains a list of <a
* href="https://stripe.com/docs/reporting/balance-transaction-types">transactions</a>
* that contributed to the balance (charges, payouts, and so forth).
*
* The available and pending amounts for each currency are broken down further by
* payment source types.
*
* Related guide: <a
* href="https://stripe.com/docs/connect/account-balances">Understanding Connect
* Account Balances</a>.
*
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property \Stripe\StripeObject[] $available Funds that are available to be transferred or paid out, whether automatically by Stripe or explicitly via the <a href="https://stripe.com/docs/api#transfers">Transfers API</a> or <a href="https://stripe.com/docs/api#payouts">Payouts API</a>. The available balance for each currency and payment type can be found in the <code>source_types</code> property.
* @property \Stripe\StripeObject[] $connect_reserved Funds held due to negative balances on connected Custom accounts. The connect reserve balance for each currency and payment type can be found in the <code>source_types</code> property.
* @property \Stripe\StripeObject $issuing
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject[] $pending Funds that are not yet available in the balance, due to the 7-day rolling pay cycle. The pending balance for each currency, and for each payment type, can be found in the <code>source_types</code> property.
*/
class Balance extends SingletonApiResource
{
const OBJECT_NAME = 'balance';
/**
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Balance
*/
public static function retrieve($opts = null)
{
return self::_singletonRetrieve($opts);
}
}

View File

@ -0,0 +1,70 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Balance transactions represent funds moving through your Stripe account. They're
* created for every type of transaction that comes into or flows out of your
* Stripe account balance.
*
* Related guide: <a
* href="https://stripe.com/docs/reports/balance-transaction-types">Balance
* Transaction Types</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount Gross amount of the transaction, in %s.
* @property int $available_on The date the transaction's net funds will become available in the Stripe balance.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property null|float $exchange_rate The exchange rate used, if applicable, for this transaction. Specifically, if money was converted from currency A to currency B, then the <code>amount</code> in currency A, times <code>exchange_rate</code>, would be the <code>amount</code> in currency B. For example, suppose you charged a customer 10.00 EUR. Then the PaymentIntent's <code>amount</code> would be <code>1000</code> and <code>currency</code> would be <code>eur</code>. Suppose this was converted into 12.34 USD in your Stripe account. Then the BalanceTransaction's <code>amount</code> would be <code>1234</code>, <code>currency</code> would be <code>usd</code>, and <code>exchange_rate</code> would be <code>1.234</code>.
* @property int $fee Fees (in %s) paid for this transaction.
* @property \Stripe\StripeObject[] $fee_details Detailed breakdown of fees (in %s) paid for this transaction.
* @property int $net Net amount of the transaction, in %s.
* @property string $reporting_category <a href="https://stripe.com/docs/reports/reporting-categories">Learn more</a> about how reporting categories can help you understand balance transactions from an accounting perspective.
* @property null|string|\Stripe\StripeObject $source The Stripe object to which this transaction is related.
* @property string $status If the transaction's net funds are available in the Stripe balance yet. Either <code>available</code> or <code>pending</code>.
* @property string $type Transaction type: <code>adjustment</code>, <code>advance</code>, <code>advance_funding</code>, <code>anticipation_repayment</code>, <code>application_fee</code>, <code>application_fee_refund</code>, <code>charge</code>, <code>connect_collection_transfer</code>, <code>issuing_authorization_hold</code>, <code>issuing_authorization_release</code>, <code>issuing_dispute</code>, <code>issuing_transaction</code>, <code>payment</code>, <code>payment_failure_refund</code>, <code>payment_refund</code>, <code>payout</code>, <code>payout_cancel</code>, <code>payout_failure</code>, <code>refund</code>, <code>refund_failure</code>, <code>reserve_transaction</code>, <code>reserved_funds</code>, <code>stripe_fee</code>, <code>stripe_fx_fee</code>, <code>tax_fee</code>, <code>topup</code>, <code>topup_reversal</code>, <code>transfer</code>, <code>transfer_cancel</code>, <code>transfer_failure</code>, or <code>transfer_refund</code>. <a href="https://stripe.com/docs/reports/balance-transaction-types">Learn more</a> about balance transaction types and what they represent. If you are looking to classify transactions for accounting purposes, you might want to consider <code>reporting_category</code> instead.
*/
class BalanceTransaction extends ApiResource
{
const OBJECT_NAME = 'balance_transaction';
use ApiOperations\All;
use ApiOperations\Retrieve;
const TYPE_ADJUSTMENT = 'adjustment';
const TYPE_ADVANCE = 'advance';
const TYPE_ADVANCE_FUNDING = 'advance_funding';
const TYPE_ANTICIPATION_REPAYMENT = 'anticipation_repayment';
const TYPE_APPLICATION_FEE = 'application_fee';
const TYPE_APPLICATION_FEE_REFUND = 'application_fee_refund';
const TYPE_CHARGE = 'charge';
const TYPE_CONNECT_COLLECTION_TRANSFER = 'connect_collection_transfer';
const TYPE_ISSUING_AUTHORIZATION_HOLD = 'issuing_authorization_hold';
const TYPE_ISSUING_AUTHORIZATION_RELEASE = 'issuing_authorization_release';
const TYPE_ISSUING_DISPUTE = 'issuing_dispute';
const TYPE_ISSUING_TRANSACTION = 'issuing_transaction';
const TYPE_PAYMENT = 'payment';
const TYPE_PAYMENT_FAILURE_REFUND = 'payment_failure_refund';
const TYPE_PAYMENT_REFUND = 'payment_refund';
const TYPE_PAYOUT = 'payout';
const TYPE_PAYOUT_CANCEL = 'payout_cancel';
const TYPE_PAYOUT_FAILURE = 'payout_failure';
const TYPE_REFUND = 'refund';
const TYPE_REFUND_FAILURE = 'refund_failure';
const TYPE_RESERVE_TRANSACTION = 'reserve_transaction';
const TYPE_RESERVED_FUNDS = 'reserved_funds';
const TYPE_STRIPE_FEE = 'stripe_fee';
const TYPE_STRIPE_FX_FEE = 'stripe_fx_fee';
const TYPE_TAX_FEE = 'tax_fee';
const TYPE_TOPUP = 'topup';
const TYPE_TOPUP_REVERSAL = 'topup_reversal';
const TYPE_TRANSFER = 'transfer';
const TYPE_TRANSFER_CANCEL = 'transfer_cancel';
const TYPE_TRANSFER_FAILURE = 'transfer_failure';
const TYPE_TRANSFER_REFUND = 'transfer_refund';
}

View File

@ -0,0 +1,131 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* These bank accounts are payment methods on <code>Customer</code> objects.
*
* On the other hand <a
* href="https://stripe.com/docs/api#external_accounts">External Accounts</a> are
* transfer destinations on <code>Account</code> objects for <a
* href="https://stripe.com/docs/connect/custom-accounts">Custom accounts</a>. They
* can be bank accounts or debit cards as well, and are documented in the links
* above.
*
* Related guide: <a
* href="https://stripe.com/docs/payments/bank-debits-transfers">Bank Debits and
* Transfers</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|string|\Stripe\Account $account The ID of the account that the bank account is associated with.
* @property null|string $account_holder_name The name of the person or business that owns the bank account.
* @property null|string $account_holder_type The type of entity that holds the account. This can be either <code>individual</code> or <code>company</code>.
* @property null|string $bank_name Name of the bank associated with the routing number (e.g., <code>WELLS FARGO</code>).
* @property string $country Two-letter ISO code representing the country the bank account is located in.
* @property string $currency Three-letter <a href="https://stripe.com/docs/payouts">ISO code for the currency</a> paid out to the bank account.
* @property null|string|\Stripe\Customer $customer The ID of the customer that the bank account is associated with.
* @property null|bool $default_for_currency Whether this bank account is the default external account for its currency.
* @property null|string $fingerprint Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same.
* @property string $last4 The last four digits of the bank account number.
* @property null|\Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $routing_number The routing transit number for the bank account.
* @property string $status <p>For bank accounts, possible values are <code>new</code>, <code>validated</code>, <code>verified</code>, <code>verification_failed</code>, or <code>errored</code>. A bank account that hasn't had any activity or validation performed is <code>new</code>. If Stripe can determine that the bank account exists, its status will be <code>validated</code>. Note that there often isnt enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be <code>verified</code>. If the verification failed for any reason, such as microdeposit failure, the status will be <code>verification_failed</code>. If a transfer sent to this bank account fails, we'll set the status to <code>errored</code> and will not continue to send transfers until the bank details are updated.</p><p>For external accounts, possible values are <code>new</code> and <code>errored</code>. Validations aren't run against external accounts because they're only used for payouts. This means the other statuses don't apply. If a transfer fails, the status is set to <code>errored</code> and transfers are stopped until account details are updated.</p>
*/
class BankAccount extends ApiResource
{
const OBJECT_NAME = 'bank_account';
use ApiOperations\Delete;
use ApiOperations\Update;
/**
* Possible string representations of the bank verification status.
*
* @see https://stripe.com/docs/api/external_account_bank_accounts/object#account_bank_account_object-status
*/
const STATUS_NEW = 'new';
const STATUS_VALIDATED = 'validated';
const STATUS_VERIFIED = 'verified';
const STATUS_VERIFICATION_FAILED = 'verification_failed';
const STATUS_ERRORED = 'errored';
/**
* @return string The instance URL for this resource. It needs to be special
* cased because it doesn't fit into the standard resource pattern.
*/
public function instanceUrl()
{
if ($this['customer']) {
$base = Customer::classUrl();
$parent = $this['customer'];
$path = 'sources';
} elseif ($this['account']) {
$base = Account::classUrl();
$parent = $this['account'];
$path = 'external_accounts';
} else {
$msg = 'Bank accounts cannot be accessed without a customer ID or account ID.';
throw new Exception\UnexpectedValueException($msg, null);
}
$parentExtn = \urlencode(Util\Util::utf8($parent));
$extn = \urlencode(Util\Util::utf8($this['id']));
return "{$base}/{$parentExtn}/{$path}/{$extn}";
}
/**
* @param array|string $_id
* @param null|array|string $_opts
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function retrieve($_id, $_opts = null)
{
$msg = 'Bank accounts cannot be retrieved without a customer ID or ' .
'an account ID. Retrieve a bank account using ' .
"`Customer::retrieveSource('customer_id', " .
"'bank_account_id')` or `Account::retrieveExternalAccount(" .
"'account_id', 'bank_account_id')`.";
throw new Exception\BadMethodCallException($msg);
}
/**
* @param string $_id
* @param null|array $_params
* @param null|array|string $_options
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function update($_id, $_params = null, $_options = null)
{
$msg = 'Bank accounts cannot be updated without a customer ID or an ' .
'account ID. Update a bank account using ' .
"`Customer::updateSource('customer_id', 'bank_account_id', " .
'$updateParams)` or `Account::updateExternalAccount(' .
"'account_id', 'bank_account_id', \$updateParams)`.";
throw new Exception\BadMethodCallException($msg);
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return BankAccount the verified bank account
*/
public function verify($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/verify';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}

View File

@ -0,0 +1,266 @@
<?php
namespace Stripe;
class BaseStripeClient implements StripeClientInterface
{
/** @var string default base URL for Stripe's API */
const DEFAULT_API_BASE = 'https://api.stripe.com';
/** @var string default base URL for Stripe's OAuth API */
const DEFAULT_CONNECT_BASE = 'https://connect.stripe.com';
/** @var string default base URL for Stripe's Files API */
const DEFAULT_FILES_BASE = 'https://files.stripe.com';
/** @var array<string, mixed> */
private $config;
/** @var \Stripe\Util\RequestOptions */
private $defaultOpts;
/**
* Initializes a new instance of the {@link BaseStripeClient} class.
*
* The constructor takes a single argument. The argument can be a string, in which case it
* should be the API key. It can also be an array with various configuration settings.
*
* Configuration settings include the following options:
*
* - api_key (null|string): the Stripe API key, to be used in regular API requests.
* - client_id (null|string): the Stripe client ID, to be used in OAuth requests.
* - stripe_account (null|string): a Stripe account ID. If set, all requests sent by the client
* will automatically use the {@code Stripe-Account} header with that account ID.
* - stripe_version (null|string): a Stripe API verion. If set, all requests sent by the client
* will include the {@code Stripe-Version} header with that API version.
*
* The following configuration settings are also available, though setting these should rarely be necessary
* (only useful if you want to send requests to a mock server like stripe-mock):
*
* - api_base (string): the base URL for regular API requests. Defaults to
* {@link DEFAULT_API_BASE}.
* - connect_base (string): the base URL for OAuth requests. Defaults to
* {@link DEFAULT_CONNECT_BASE}.
* - files_base (string): the base URL for file creation requests. Defaults to
* {@link DEFAULT_FILES_BASE}.
*
* @param array<string, mixed>|string $config the API key as a string, or an array containing
* the client configuration settings
*/
public function __construct($config = [])
{
if (\is_string($config)) {
$config = ['api_key' => $config];
} elseif (!\is_array($config)) {
throw new \Stripe\Exception\InvalidArgumentException('$config must be a string or an array');
}
$config = \array_merge($this->getDefaultConfig(), $config);
$this->validateConfig($config);
$this->config = $config;
$this->defaultOpts = \Stripe\Util\RequestOptions::parse([
'stripe_account' => $config['stripe_account'],
'stripe_version' => $config['stripe_version'],
]);
}
/**
* Gets the API key used by the client to send requests.
*
* @return null|string the API key used by the client to send requests
*/
public function getApiKey()
{
return $this->config['api_key'];
}
/**
* Gets the client ID used by the client in OAuth requests.
*
* @return null|string the client ID used by the client in OAuth requests
*/
public function getClientId()
{
return $this->config['client_id'];
}
/**
* Gets the base URL for Stripe's API.
*
* @return string the base URL for Stripe's API
*/
public function getApiBase()
{
return $this->config['api_base'];
}
/**
* Gets the base URL for Stripe's OAuth API.
*
* @return string the base URL for Stripe's OAuth API
*/
public function getConnectBase()
{
return $this->config['connect_base'];
}
/**
* Gets the base URL for Stripe's Files API.
*
* @return string the base URL for Stripe's Files API
*/
public function getFilesBase()
{
return $this->config['files_base'];
}
/**
* Sends a request to Stripe's API.
*
* @param string $method the HTTP method
* @param string $path the path of the request
* @param array $params the parameters of the request
* @param array|\Stripe\Util\RequestOptions $opts the special modifiers of the request
*
* @return \Stripe\StripeObject the object returned by Stripe's API
*/
public function request($method, $path, $params, $opts)
{
$opts = $this->defaultOpts->merge($opts, true);
$baseUrl = $opts->apiBase ?: $this->getApiBase();
$requestor = new \Stripe\ApiRequestor($this->apiKeyForRequest($opts), $baseUrl);
list($response, $opts->apiKey) = $requestor->request($method, $path, $params, $opts->headers);
$opts->discardNonPersistentHeaders();
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* Sends a request to Stripe's API.
*
* @param string $method the HTTP method
* @param string $path the path of the request
* @param array $params the parameters of the request
* @param array|\Stripe\Util\RequestOptions $opts the special modifiers of the request
*
* @return \Stripe\Collection of ApiResources
*/
public function requestCollection($method, $path, $params, $opts)
{
$obj = $this->request($method, $path, $params, $opts);
if (!($obj instanceof \Stripe\Collection)) {
$received_class = \get_class($obj);
$msg = "Expected to receive `Stripe\\Collection` object from Stripe API. Instead received `{$received_class}`.";
throw new \Stripe\Exception\UnexpectedValueException($msg);
}
$obj->setFilters($params);
return $obj;
}
/**
* @param \Stripe\Util\RequestOptions $opts
*
* @throws \Stripe\Exception\AuthenticationException
*
* @return string
*/
private function apiKeyForRequest($opts)
{
$apiKey = $opts->apiKey ?: $this->getApiKey();
if (null === $apiKey) {
$msg = 'No API key provided. Set your API key when constructing the '
. 'StripeClient instance, or provide it on a per-request basis '
. 'using the `api_key` key in the $opts argument.';
throw new \Stripe\Exception\AuthenticationException($msg);
}
return $apiKey;
}
/**
* TODO: replace this with a private constant when we drop support for PHP < 5.
*
* @return array<string, mixed>
*/
private function getDefaultConfig()
{
return [
'api_key' => null,
'client_id' => null,
'stripe_account' => null,
'stripe_version' => null,
'api_base' => self::DEFAULT_API_BASE,
'connect_base' => self::DEFAULT_CONNECT_BASE,
'files_base' => self::DEFAULT_FILES_BASE,
];
}
/**
* @param array<string, mixed> $config
*
* @throws \Stripe\Exception\InvalidArgumentException
*/
private function validateConfig($config)
{
// api_key
if (null !== $config['api_key'] && !\is_string($config['api_key'])) {
throw new \Stripe\Exception\InvalidArgumentException('api_key must be null or a string');
}
if (null !== $config['api_key'] && ('' === $config['api_key'])) {
$msg = 'api_key cannot be the empty string';
throw new \Stripe\Exception\InvalidArgumentException($msg);
}
if (null !== $config['api_key'] && (\preg_match('/\s/', $config['api_key']))) {
$msg = 'api_key cannot contain whitespace';
throw new \Stripe\Exception\InvalidArgumentException($msg);
}
// client_id
if (null !== $config['client_id'] && !\is_string($config['client_id'])) {
throw new \Stripe\Exception\InvalidArgumentException('client_id must be null or a string');
}
// stripe_account
if (null !== $config['stripe_account'] && !\is_string($config['stripe_account'])) {
throw new \Stripe\Exception\InvalidArgumentException('stripe_account must be null or a string');
}
// stripe_version
if (null !== $config['stripe_version'] && !\is_string($config['stripe_version'])) {
throw new \Stripe\Exception\InvalidArgumentException('stripe_version must be null or a string');
}
// api_base
if (!\is_string($config['api_base'])) {
throw new \Stripe\Exception\InvalidArgumentException('api_base must be a string');
}
// connect_base
if (!\is_string($config['connect_base'])) {
throw new \Stripe\Exception\InvalidArgumentException('connect_base must be a string');
}
// files_base
if (!\is_string($config['files_base'])) {
throw new \Stripe\Exception\InvalidArgumentException('files_base must be a string');
}
// check absence of extra keys
$extraConfigKeys = \array_diff(\array_keys($config), \array_keys($this->getDefaultConfig()));
if (!empty($extraConfigKeys)) {
throw new \Stripe\Exception\InvalidArgumentException('Found unknown key(s) in configuration array: ' . \implode(',', $extraConfigKeys));
}
}
}

View File

@ -0,0 +1,32 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\BillingPortal;
/**
* A session describes the instantiation of the customer portal for a particular
* customer. By visiting the session's URL, the customer can manage their
* subscriptions and billing details. For security reasons, sessions are
* short-lived and will expire if the customer does not visit the URL. Create
* sessions on-demand when customers intend to manage their subscriptions and
* billing details.
*
* Integration guide: <a
* href="https://stripe.com/docs/billing/subscriptions/integrating-customer-portal">Billing
* customer portal</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $customer The ID of the customer for this session.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property string $return_url The URL to which Stripe should send customers when they click on the link to return to your website.
* @property string $url The short-lived URL of the session giving customers access to the customer portal.
*/
class Session extends \Stripe\ApiResource
{
const OBJECT_NAME = 'billing_portal.session';
use \Stripe\ApiOperations\Create;
}

View File

@ -0,0 +1,71 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @deprecated Bitcoin receivers are deprecated. Please use the sources API instead.
* @see https://stripe.com/docs/sources/bitcoin
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property bool $active True when this bitcoin receiver has received a non-zero amount of bitcoin.
* @property int $amount The amount of <code>currency</code> that you are collecting as payment.
* @property int $amount_received The amount of <code>currency</code> to which <code>bitcoin_amount_received</code> has been converted.
* @property int $bitcoin_amount The amount of bitcoin that the customer should send to fill the receiver. The <code>bitcoin_amount</code> is denominated in Satoshi: there are 10^8 Satoshi in one bitcoin.
* @property int $bitcoin_amount_received The amount of bitcoin that has been sent by the customer to this receiver.
* @property string $bitcoin_uri This URI can be displayed to the customer as a clickable link (to activate their bitcoin client) or as a QR code (for mobile wallets).
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://stripe.com/docs/currencies">ISO code for the currency</a> to which the bitcoin will be converted.
* @property null|string $customer The customer ID of the bitcoin receiver.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property null|string $email The customer's email address, set by the API call that creates the receiver.
* @property bool $filled This flag is initially false and updates to true when the customer sends the <code>bitcoin_amount</code> to this receiver.
* @property string $inbound_address A bitcoin address that is specific to this receiver. The customer can send bitcoin to this address to fill the receiver.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $payment The ID of the payment created from the receiver, if any. Hidden when viewing the receiver with a publishable key.
* @property null|string $refund_address The refund address of this bitcoin receiver.
* @property \Stripe\Collection $transactions A list with one entry for each time that the customer sent bitcoin to the receiver. Hidden when viewing the receiver with a publishable key.
* @property bool $uncaptured_funds This receiver contains uncaptured funds that can be used for a payment or refunded.
* @property null|bool $used_for_payment Indicate if this source is used for payment.
*/
class BitcoinReceiver extends ApiResource
{
const OBJECT_NAME = 'bitcoin_receiver';
use ApiOperations\All;
use ApiOperations\Retrieve;
/**
* @return string The class URL for this resource. It needs to be special
* cased because it doesn't fit into the standard resource pattern.
*/
public static function classUrl()
{
return '/v1/bitcoin/receivers';
}
/**
* @return string The instance URL for this resource. It needs to be special
* cased because it doesn't fit into the standard resource pattern.
*/
public function instanceUrl()
{
if ($this['customer']) {
$base = Customer::classUrl();
$parent = $this['customer'];
$path = 'sources';
$parentExtn = \urlencode(Util\Util::utf8($parent));
$extn = \urlencode(Util\Util::utf8($this['id']));
return "{$base}/{$parentExtn}/{$path}/{$extn}";
}
$base = BitcoinReceiver::classUrl();
$extn = \urlencode(Util\Util::utf8($this['id']));
return "{$base}/{$extn}";
}
}

View File

@ -0,0 +1,19 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The amount of <code>currency</code> that the transaction was converted to in real-time.
* @property int $bitcoin_amount The amount of bitcoin contained in the transaction.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://stripe.com/docs/currencies">ISO code for the currency</a> to which this transaction was converted.
* @property string $receiver The receiver to which this transaction was sent.
*/
class BitcoinTransaction extends ApiResource
{
const OBJECT_NAME = 'bitcoin_transaction';
}

View File

@ -0,0 +1,87 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* This is an object representing a capability for a Stripe account.
*
* Related guide: <a
* href="https://stripe.com/docs/connect/account-capabilities">Account
* capabilities</a>.
*
* @property string $id The identifier for the capability.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property string|\Stripe\Account $account The account for which the capability enables functionality.
* @property bool $requested Whether the capability has been requested.
* @property null|int $requested_at Time at which the capability was requested. Measured in seconds since the Unix epoch.
* @property \Stripe\StripeObject $requirements
* @property string $status The status of the capability. Can be <code>active</code>, <code>inactive</code>, <code>pending</code>, or <code>unrequested</code>.
*/
class Capability extends ApiResource
{
const OBJECT_NAME = 'capability';
use ApiOperations\Update;
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_PENDING = 'pending';
const STATUS_UNREQUESTED = 'unrequested';
/**
* @return string the API URL for this Stripe account reversal
*/
public function instanceUrl()
{
$id = $this['id'];
$account = $this['account'];
if (!$id) {
throw new Exception\UnexpectedValueException(
'Could not determine which URL to request: ' .
"class instance has invalid ID: {$id}",
null
);
}
$id = Util\Util::utf8($id);
$account = Util\Util::utf8($account);
$base = Account::classUrl();
$accountExtn = \urlencode($account);
$extn = \urlencode($id);
return "{$base}/{$accountExtn}/capabilities/{$extn}";
}
/**
* @param array|string $_id
* @param null|array|string $_opts
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function retrieve($_id, $_opts = null)
{
$msg = 'Capabilities cannot be retrieved without an account ID. ' .
'Retrieve a capability using `Account::retrieveCapability(' .
"'account_id', 'capability_id')`.";
throw new Exception\BadMethodCallException($msg);
}
/**
* @param string $_id
* @param null|array $_params
* @param null|array|string $_options
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function update($_id, $_params = null, $_options = null)
{
$msg = 'Capabilities cannot be updated without an account ID. ' .
'Update a capability using `Account::updateCapability(' .
"'account_id', 'capability_id', \$updateParams)`.";
throw new Exception\BadMethodCallException($msg);
}
}

View File

@ -0,0 +1,142 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* You can store multiple cards on a customer in order to charge the customer
* later. You can also store multiple debit cards on a recipient in order to
* transfer to those cards later.
*
* Related guide: <a href="https://stripe.com/docs/sources/cards">Card Payments
* with Sources</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|string|\Stripe\Account $account The account this card belongs to. This attribute will not be in the card object if the card belongs to a customer or recipient instead.
* @property null|string $address_city City/District/Suburb/Town/Village.
* @property null|string $address_country Billing address country, if provided when creating card.
* @property null|string $address_line1 Address line 1 (Street address/PO Box/Company name).
* @property null|string $address_line1_check If <code>address_line1</code> was provided, results of the check: <code>pass</code>, <code>fail</code>, <code>unavailable</code>, or <code>unchecked</code>.
* @property null|string $address_line2 Address line 2 (Apartment/Suite/Unit/Building).
* @property null|string $address_state State/County/Province/Region.
* @property null|string $address_zip ZIP or postal code.
* @property null|string $address_zip_check If <code>address_zip</code> was provided, results of the check: <code>pass</code>, <code>fail</code>, <code>unavailable</code>, or <code>unchecked</code>.
* @property null|string[] $available_payout_methods A set of available payout methods for this card. Will be either <code>[&quot;standard&quot;]</code> or <code>[&quot;standard&quot;, &quot;instant&quot;]</code>. Only values from this set should be passed as the <code>method</code> when creating a transfer.
* @property string $brand Card brand. Can be <code>American Express</code>, <code>Diners Club</code>, <code>Discover</code>, <code>JCB</code>, <code>MasterCard</code>, <code>UnionPay</code>, <code>Visa</code>, or <code>Unknown</code>.
* @property null|string $country Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected.
* @property null|string $currency
* @property null|string|\Stripe\Customer $customer The customer that this card belongs to. This attribute will not be in the card object if the card belongs to an account or recipient instead.
* @property null|string $cvc_check If a CVC was provided, results of the check: <code>pass</code>, <code>fail</code>, <code>unavailable</code>, or <code>unchecked</code>.
* @property null|bool $default_for_currency Whether this card is the default external account for its currency.
* @property null|string $dynamic_last4 (For tokenized numbers only.) The last four digits of the device account number.
* @property int $exp_month Two-digit number representing the card's expiration month.
* @property int $exp_year Four-digit number representing the card's expiration year.
* @property null|string $fingerprint Uniquely identifies this particular card number. You can use this attribute to check whether two customers whove signed up with you are using the same card number,for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number.
* @property string $funding Card funding type. Can be <code>credit</code>, <code>debit</code>, <code>prepaid</code>, or <code>unknown</code>.
* @property string $last4 The last four digits of the card.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $name Cardholder name.
* @property null|string|\Stripe\Recipient $recipient The recipient that this card belongs to. This attribute will not be in the card object if the card belongs to a customer or account instead.
* @property null|string $tokenization_method If the card number is tokenized, this is the method that was used. Can be <code>android_pay</code> (includes Google Pay), <code>apple_pay</code>, <code>masterpass</code>, <code>visa_checkout</code>, or null.
*/
class Card extends ApiResource
{
const OBJECT_NAME = 'card';
use ApiOperations\Delete;
use ApiOperations\Update;
/**
* Possible string representations of the CVC check status.
*
* @see https://stripe.com/docs/api/cards/object#card_object-cvc_check
*/
const CVC_CHECK_FAIL = 'fail';
const CVC_CHECK_PASS = 'pass';
const CVC_CHECK_UNAVAILABLE = 'unavailable';
const CVC_CHECK_UNCHECKED = 'unchecked';
/**
* Possible string representations of the funding of the card.
*
* @see https://stripe.com/docs/api/cards/object#card_object-funding
*/
const FUNDING_CREDIT = 'credit';
const FUNDING_DEBIT = 'debit';
const FUNDING_PREPAID = 'prepaid';
const FUNDING_UNKNOWN = 'unknown';
/**
* Possible string representations of the tokenization method when using Apple Pay or Google Pay.
*
* @see https://stripe.com/docs/api/cards/object#card_object-tokenization_method
*/
const TOKENIZATION_METHOD_APPLE_PAY = 'apple_pay';
const TOKENIZATION_METHOD_GOOGLE_PAY = 'google_pay';
/**
* @return string The instance URL for this resource. It needs to be special
* cased because cards are nested resources that may belong to different
* top-level resources.
*/
public function instanceUrl()
{
if ($this['customer']) {
$base = Customer::classUrl();
$parent = $this['customer'];
$path = 'sources';
} elseif ($this['account']) {
$base = Account::classUrl();
$parent = $this['account'];
$path = 'external_accounts';
} elseif ($this['recipient']) {
$base = Recipient::classUrl();
$parent = $this['recipient'];
$path = 'cards';
} else {
$msg = 'Cards cannot be accessed without a customer ID, account ID or recipient ID.';
throw new Exception\UnexpectedValueException($msg);
}
$parentExtn = \urlencode(Util\Util::utf8($parent));
$extn = \urlencode(Util\Util::utf8($this['id']));
return "{$base}/{$parentExtn}/{$path}/{$extn}";
}
/**
* @param array|string $_id
* @param null|array|string $_opts
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function retrieve($_id, $_opts = null)
{
$msg = 'Cards cannot be retrieved without a customer ID or an ' .
'account ID. Retrieve a card using ' .
"`Customer::retrieveSource('customer_id', 'card_id')` or " .
"`Account::retrieveExternalAccount('account_id', 'card_id')`.";
throw new Exception\BadMethodCallException($msg);
}
/**
* @param string $_id
* @param null|array $_params
* @param null|array|string $_options
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function update($_id, $_params = null, $_options = null)
{
$msg = 'Cards cannot be updated without a customer ID or an ' .
'account ID. Update a card using ' .
"`Customer::updateSource('customer_id', 'card_id', " .
'$updateParams)` or `Account::updateExternalAccount(' .
"'account_id', 'card_id', \$updateParams)`.";
throw new Exception\BadMethodCallException($msg);
}
}

View File

@ -0,0 +1,145 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* To charge a credit or a debit card, you create a <code>Charge</code> object. You
* can retrieve and refund individual charges as well as list all charges. Charges
* are identified by a unique, random ID.
*
* Related guide: <a
* href="https://stripe.com/docs/payments/accept-a-payment-charges">Accept a
* payment with the Charges API</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount Amount intended to be collected by this payment. A positive integer representing how much to charge in the <a href="https://stripe.com/docs/currencies#zero-decimal">smallest currency unit</a> (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or <a href="https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts">equivalent in charge currency</a>. The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99).
* @property int $amount_refunded Amount in %s refunded (can be less than the amount attribute on the charge if a partial refund was issued).
* @property null|string|\Stripe\StripeObject $application ID of the Connect application that created the charge.
* @property null|string|\Stripe\ApplicationFee $application_fee The application fee (if any) for the charge. <a href="https://stripe.com/docs/connect/direct-charges#collecting-fees">See the Connect documentation</a> for details.
* @property null|int $application_fee_amount The amount of the application fee (if any) for the charge. <a href="https://stripe.com/docs/connect/direct-charges#collecting-fees">See the Connect documentation</a> for details.
* @property null|string|\Stripe\BalanceTransaction $balance_transaction ID of the balance transaction that describes the impact of this charge on your account balance (not including refunds or disputes).
* @property \Stripe\StripeObject $billing_details
* @property null|string $calculated_statement_descriptor The full statement descriptor that is passed to card networks, and that is displayed on your customers' credit card and bank statements. Allows you to see what the statement descriptor looks like after the static and dynamic portions are combined.
* @property bool $captured If the charge was created without capturing, this Boolean represents whether it is still uncaptured or has since been captured.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property null|string|\Stripe\Customer $customer ID of the customer this charge is for if one exists.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property null|string|\Stripe\Account $destination ID of an existing, connected Stripe account to transfer funds to if <code>transfer_data</code> was specified in the charge request.
* @property null|string|\Stripe\Dispute $dispute Details about the dispute if the charge has been disputed.
* @property bool $disputed Whether the charge has been disputed.
* @property null|string $failure_code Error code explaining reason for charge failure if available (see <a href="https://stripe.com/docs/api#errors">the errors section</a> for a list of codes).
* @property null|string $failure_message Message to user further explaining reason for charge failure if available.
* @property null|\Stripe\StripeObject $fraud_details Information on fraud assessments for the charge.
* @property null|string|\Stripe\Invoice $invoice ID of the invoice this charge is for if one exists.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string|\Stripe\Account $on_behalf_of The account (if any) the charge was made on behalf of without triggering an automatic transfer. See the <a href="https://stripe.com/docs/connect/charges-transfers">Connect documentation</a> for details.
* @property null|string|\Stripe\Order $order ID of the order this charge is for if one exists.
* @property null|\Stripe\StripeObject $outcome Details about whether the payment was accepted, and why. See <a href="https://stripe.com/docs/declines">understanding declines</a> for details.
* @property bool $paid <code>true</code> if the charge succeeded, or was successfully authorized for later capture.
* @property null|string|\Stripe\PaymentIntent $payment_intent ID of the PaymentIntent associated with this charge, if one exists.
* @property null|string $payment_method ID of the payment method used in this charge.
* @property null|\Stripe\StripeObject $payment_method_details Details about the payment method at the time of the transaction.
* @property null|string $receipt_email This is the email address that the receipt for this charge was sent to.
* @property null|string $receipt_number This is the transaction number that appears on email receipts sent for this charge. This attribute will be <code>null</code> until a receipt has been sent.
* @property null|string $receipt_url This is the URL to view the receipt for this charge. The receipt is kept up-to-date to the latest state of the charge, including any refunds. If the charge is for an Invoice, the receipt will be stylized as an Invoice receipt.
* @property bool $refunded Whether the charge has been fully refunded. If the charge is only partially refunded, this attribute will still be false.
* @property \Stripe\Collection $refunds A list of refunds that have been applied to the charge.
* @property null|string|\Stripe\Review $review ID of the review associated with this charge if one exists.
* @property null|\Stripe\StripeObject $shipping Shipping information for the charge.
* @property null|\Stripe\StripeObject $source This is a legacy field that will be removed in the future. It contains the Source, Card, or BankAccount object used for the charge. For details about the payment method used for this charge, refer to <code>payment_method</code> or <code>payment_method_details</code> instead.
* @property null|string|\Stripe\Transfer $source_transfer The transfer ID which created this charge. Only present if the charge came from another Stripe account. <a href="https://stripe.com/docs/connect/destination-charges">See the Connect documentation</a> for details.
* @property null|string $statement_descriptor For card charges, use <code>statement_descriptor_suffix</code> instead. Otherwise, you can use this value as the complete description of a charge on your customers statements. Must contain at least one letter, maximum 22 characters.
* @property null|string $statement_descriptor_suffix Provides information about the charge that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor thats set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.
* @property string $status The status of the payment is either <code>succeeded</code>, <code>pending</code>, or <code>failed</code>.
* @property string|\Stripe\Transfer $transfer ID of the transfer to the <code>destination</code> account (only applicable if the charge was created using the <code>destination</code> parameter).
* @property null|\Stripe\StripeObject $transfer_data An optional dictionary including the account to automatically transfer to as part of a destination charge. <a href="https://stripe.com/docs/connect/destination-charges">See the Connect documentation</a> for details.
* @property null|string $transfer_group A string that identifies this transaction as part of a group. See the <a href="https://stripe.com/docs/connect/charges-transfers#transfer-options">Connect documentation</a> for details.
*/
class Charge extends ApiResource
{
const OBJECT_NAME = 'charge';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Retrieve;
use ApiOperations\Update;
const STATUS_FAILED = 'failed';
const STATUS_PENDING = 'pending';
const STATUS_SUCCEEDED = 'succeeded';
/**
* Possible string representations of decline codes.
* These strings are applicable to the decline_code property of the \Stripe\Exception\CardException exception.
*
* @see https://stripe.com/docs/declines/codes
*/
const DECLINED_AUTHENTICATION_REQUIRED = 'authentication_required';
const DECLINED_APPROVE_WITH_ID = 'approve_with_id';
const DECLINED_CALL_ISSUER = 'call_issuer';
const DECLINED_CARD_NOT_SUPPORTED = 'card_not_supported';
const DECLINED_CARD_VELOCITY_EXCEEDED = 'card_velocity_exceeded';
const DECLINED_CURRENCY_NOT_SUPPORTED = 'currency_not_supported';
const DECLINED_DO_NOT_HONOR = 'do_not_honor';
const DECLINED_DO_NOT_TRY_AGAIN = 'do_not_try_again';
const DECLINED_DUPLICATED_TRANSACTION = 'duplicate_transaction';
const DECLINED_EXPIRED_CARD = 'expired_card';
const DECLINED_FRAUDULENT = 'fraudulent';
const DECLINED_GENERIC_DECLINE = 'generic_decline';
const DECLINED_INCORRECT_NUMBER = 'incorrect_number';
const DECLINED_INCORRECT_CVC = 'incorrect_cvc';
const DECLINED_INCORRECT_PIN = 'incorrect_pin';
const DECLINED_INCORRECT_ZIP = 'incorrect_zip';
const DECLINED_INSUFFICIENT_FUNDS = 'insufficient_funds';
const DECLINED_INVALID_ACCOUNT = 'invalid_account';
const DECLINED_INVALID_AMOUNT = 'invalid_amount';
const DECLINED_INVALID_CVC = 'invalid_cvc';
const DECLINED_INVALID_EXPIRY_YEAR = 'invalid_expiry_year';
const DECLINED_INVALID_NUMBER = 'invalid_number';
const DECLINED_INVALID_PIN = 'invalid_pin';
const DECLINED_ISSUER_NOT_AVAILABLE = 'issuer_not_available';
const DECLINED_LOST_CARD = 'lost_card';
const DECLINED_MERCHANT_BLACKLIST = 'merchant_blacklist';
const DECLINED_NEW_ACCOUNT_INFORMATION_AVAILABLE = 'new_account_information_available';
const DECLINED_NO_ACTION_TAKEN = 'no_action_taken';
const DECLINED_NOT_PERMITTED = 'not_permitted';
const DECLINED_OFFLINE_PIN_REQUIRED = 'offline_pin_required';
const DECLINED_ONLINE_OR_OFFLINE_PIN_REQUIRED = 'online_or_offline_pin_required';
const DECLINED_PICKUP_CARD = 'pickup_card';
const DECLINED_PIN_TRY_EXCEEDED = 'pin_try_exceeded';
const DECLINED_PROCESSING_ERROR = 'processing_error';
const DECLINED_REENTER_TRANSACTION = 'reenter_transaction';
const DECLINED_RESTRICTED_CARD = 'restricted_card';
const DECLINED_REVOCATION_OF_ALL_AUTHORIZATIONS = 'revocation_of_all_authorizations';
const DECLINED_REVOCATION_OF_AUTHORIZATION = 'revocation_of_authorization';
const DECLINED_SECURITY_VIOLATION = 'security_violation';
const DECLINED_SERVICE_NOT_ALLOWED = 'service_not_allowed';
const DECLINED_STOLEN_CARD = 'stolen_card';
const DECLINED_STOP_PAYMENT_ORDER = 'stop_payment_order';
const DECLINED_TESTMODE_DECLINE = 'testmode_decline';
const DECLINED_TRANSACTION_NOT_ALLOWED = 'transaction_not_allowed';
const DECLINED_TRY_AGAIN_LATER = 'try_again_later';
const DECLINED_WITHDRAWAL_COUNT_LIMIT_EXCEEDED = 'withdrawal_count_limit_exceeded';
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Charge the captured charge
*/
public function capture($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/capture';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}

View File

@ -0,0 +1,84 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\Checkout;
/**
* A Checkout Session represents your customer's session as they pay for one-time
* purchases or subscriptions through <a
* href="https://stripe.com/docs/payments/checkout">Checkout</a>. We recommend
* creating a new Session each time your customer attempts to pay.
*
* Once payment is successful, the Checkout Session will contain a reference to the
* <a href="https://stripe.com/docs/api/customers">Customer</a>, and either the
* successful <a
* href="https://stripe.com/docs/api/payment_intents">PaymentIntent</a> or an
* active <a href="https://stripe.com/docs/api/subscriptions">Subscription</a>.
*
* You can create a Checkout Session on your server and pass its ID to the client
* to begin Checkout.
*
* Related guide: <a href="https://stripe.com/docs/payments/checkout/api">Checkout
* Server Quickstart</a>.
*
* @property string $id Unique identifier for the object. Used to pass to <code>redirectToCheckout</code> in Stripe.js.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|bool $allow_promotion_codes Enables user redeemable promotion codes.
* @property null|int $amount_subtotal Total of all items before discounts or taxes are applied.
* @property null|int $amount_total Total of all items after discounts and taxes are applied.
* @property null|string $billing_address_collection Describes whether Checkout should collect the customer's billing address.
* @property string $cancel_url The URL the customer will be directed to if they decide to cancel payment and return to your website.
* @property null|string $client_reference_id A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems.
* @property null|string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property null|string|\Stripe\Customer $customer The ID of the customer for this session. For Checkout Sessions in <code>payment</code> or <code>subscription</code> mode, Checkout will create a new customer object based on information provided during the session unless an existing customer was provided when the session was created.
* @property null|string $customer_email If provided, this value will be used when the Customer object is created. If not provided, customers will be asked to enter their email address. Use this parameter to prefill customer data if you already have an email on file. To access information about the customer once a session is complete, use the <code>customer</code> attribute.
* @property \Stripe\StripeObject[] $display_items The line items, plans, or SKUs purchased by the customer. Prefer using <code>line_items</code>.
* @property \Stripe\Collection $line_items The line items purchased by the customer.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|string $locale The IETF language tag of the locale Checkout is displayed in. If blank or <code>auto</code>, the browser's locale is used.
* @property null|\Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $mode The mode of the Checkout Session, one of <code>payment</code>, <code>setup</code>, or <code>subscription</code>.
* @property null|string|\Stripe\PaymentIntent $payment_intent The ID of the PaymentIntent for Checkout Sessions in <code>payment</code> mode.
* @property string[] $payment_method_types A list of the types of payment methods (e.g. card) this Checkout Session is allowed to accept.
* @property null|string|\Stripe\SetupIntent $setup_intent The ID of the SetupIntent for Checkout Sessions in <code>setup</code> mode.
* @property null|\Stripe\StripeObject $shipping Shipping information for this Checkout Session.
* @property null|\Stripe\StripeObject $shipping_address_collection When set, provides configuration for Checkout to collect a shipping address from a customer.
* @property null|string $submit_type Describes the type of transaction being performed by Checkout in order to customize relevant text on the page, such as the submit button. <code>submit_type</code> can only be specified on Checkout Sessions in <code>payment</code> mode, but not Checkout Sessions in <code>subscription</code> or <code>setup</code> mode.
* @property null|string|\Stripe\Subscription $subscription The ID of the subscription for Checkout Sessions in <code>subscription</code> mode.
* @property string $success_url The URL the customer will be directed to after the payment or subscription creation is successful.
* @property null|\Stripe\StripeObject $total_details Tax and discount details for the computed total amount.
*/
class Session extends \Stripe\ApiResource
{
const OBJECT_NAME = 'checkout.session';
use \Stripe\ApiOperations\All;
use \Stripe\ApiOperations\Create;
use \Stripe\ApiOperations\NestedResource;
use \Stripe\ApiOperations\Retrieve;
const BILLING_ADDRESS_COLLECTION_AUTO = 'auto';
const BILLING_ADDRESS_COLLECTION_REQUIRED = 'required';
const SUBMIT_TYPE_AUTO = 'auto';
const SUBMIT_TYPE_BOOK = 'book';
const SUBMIT_TYPE_DONATE = 'donate';
const SUBMIT_TYPE_PAY = 'pay';
const PATH_LINE_ITEMS = '/line_items';
/**
* @param string $id the ID of the session on which to retrieve the items
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of items
*/
public static function allLineItems($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_LINE_ITEMS, $params, $opts);
}
}

View File

@ -0,0 +1,281 @@
<?php
namespace Stripe;
/**
* Class Collection.
*
* @property string $object
* @property string $url
* @property bool $has_more
* @property \Stripe\StripeObject[] $data
*/
class Collection extends StripeObject implements \Countable, \IteratorAggregate
{
const OBJECT_NAME = 'list';
use ApiOperations\Request;
/** @var array */
protected $filters = [];
/**
* @return string the base URL for the given class
*/
public static function baseUrl()
{
return Stripe::$apiBase;
}
/**
* Returns the filters.
*
* @return array the filters
*/
public function getFilters()
{
return $this->filters;
}
/**
* Sets the filters, removing paging options.
*
* @param array $filters the filters
*/
public function setFilters($filters)
{
$this->filters = $filters;
}
public function offsetGet($k)
{
if (\is_string($k)) {
return parent::offsetGet($k);
}
$msg = "You tried to access the {$k} index, but Collection " .
'types only support string keys. (HINT: List calls ' .
'return an object with a `data` (which is the data ' .
"array). You likely want to call ->data[{$k}])";
throw new Exception\InvalidArgumentException($msg);
}
public function all($params = null, $opts = null)
{
self::_validateParams($params);
list($url, $params) = $this->extractPathAndUpdateParams($params);
list($response, $opts) = $this->_request('get', $url, $params, $opts);
$obj = Util\Util::convertToStripeObject($response, $opts);
if (!($obj instanceof \Stripe\Collection)) {
throw new \Stripe\Exception\UnexpectedValueException(
'Expected type ' . \Stripe\Collection::class . ', got "' . \get_class($obj) . '" instead.'
);
}
$obj->setFilters($params);
return $obj;
}
public function create($params = null, $opts = null)
{
self::_validateParams($params);
list($url, $params) = $this->extractPathAndUpdateParams($params);
list($response, $opts) = $this->_request('post', $url, $params, $opts);
return Util\Util::convertToStripeObject($response, $opts);
}
public function retrieve($id, $params = null, $opts = null)
{
self::_validateParams($params);
list($url, $params) = $this->extractPathAndUpdateParams($params);
$id = Util\Util::utf8($id);
$extn = \urlencode($id);
list($response, $opts) = $this->_request(
'get',
"{$url}/{$extn}",
$params,
$opts
);
return Util\Util::convertToStripeObject($response, $opts);
}
/**
* @return int the number of objects in the current page
*/
public function count()
{
return \count($this->data);
}
/**
* @return \ArrayIterator an iterator that can be used to iterate
* across objects in the current page
*/
public function getIterator()
{
return new \ArrayIterator($this->data);
}
/**
* @return \ArrayIterator an iterator that can be used to iterate
* backwards across objects in the current page
*/
public function getReverseIterator()
{
return new \ArrayIterator(\array_reverse($this->data));
}
/**
* @return \Generator|StripeObject[] A generator that can be used to
* iterate across all objects across all pages. As page boundaries are
* encountered, the next page will be fetched automatically for
* continued iteration.
*/
public function autoPagingIterator()
{
$page = $this;
while (true) {
$filters = $this->filters ?: [];
if (\array_key_exists('ending_before', $filters) &&
!\array_key_exists('starting_after', $filters)) {
foreach ($page->getReverseIterator() as $item) {
yield $item;
}
$page = $page->previousPage();
} else {
foreach ($page as $item) {
yield $item;
}
$page = $page->nextPage();
}
if ($page->isEmpty()) {
break;
}
}
}
/**
* Returns an empty collection. This is returned from {@see nextPage()}
* when we know that there isn't a next page in order to replicate the
* behavior of the API when it attempts to return a page beyond the last.
*
* @param null|array|string $opts
*
* @return Collection
*/
public static function emptyCollection($opts = null)
{
return Collection::constructFrom(['data' => []], $opts);
}
/**
* Returns true if the page object contains no element.
*
* @return bool
*/
public function isEmpty()
{
return empty($this->data);
}
/**
* Fetches the next page in the resource list (if there is one).
*
* This method will try to respect the limit of the current page. If none
* was given, the default limit will be fetched again.
*
* @param null|array $params
* @param null|array|string $opts
*
* @return Collection
*/
public function nextPage($params = null, $opts = null)
{
if (!$this->has_more) {
return static::emptyCollection($opts);
}
$lastId = \end($this->data)->id;
$params = \array_merge(
$this->filters ?: [],
['starting_after' => $lastId],
$params ?: []
);
return $this->all($params, $opts);
}
/**
* Fetches the previous page in the resource list (if there is one).
*
* This method will try to respect the limit of the current page. If none
* was given, the default limit will be fetched again.
*
* @param null|array $params
* @param null|array|string $opts
*
* @return Collection
*/
public function previousPage($params = null, $opts = null)
{
if (!$this->has_more) {
return static::emptyCollection($opts);
}
$firstId = $this->data[0]->id;
$params = \array_merge(
$this->filters ?: [],
['ending_before' => $firstId],
$params ?: []
);
return $this->all($params, $opts);
}
/**
* Gets the first item from the current page. Returns `null` if the current page is empty.
*
* @return null|\Stripe\StripeObject
*/
public function first()
{
return \count($this->data) > 0 ? $this->data[0] : null;
}
/**
* Gets the last item from the current page. Returns `null` if the current page is empty.
*
* @return null|\Stripe\StripeObject
*/
public function last()
{
return \count($this->data) > 0 ? $this->data[\count($this->data) - 1] : null;
}
private function extractPathAndUpdateParams($params)
{
$url = \parse_url($this->url);
if (!isset($url['path'])) {
throw new Exception\UnexpectedValueException("Could not parse list url into parts: {$url}");
}
if (isset($url['query'])) {
// If the URL contains a query param, parse it out into $params so they
// don't interact weirdly with each other.
$query = [];
\parse_str($url['query'], $query);
$params = \array_merge($params ?: [], $query);
}
return [$url['path'], $params];
}
}

View File

@ -0,0 +1,30 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Stripe needs to collect certain pieces of information about each account
* created. These requirements can differ depending on the account's country. The
* Country Specs API makes these rules available to your integration.
*
* You can also view the information from this API call as <a
* href="/docs/connect/required-verification-information">an online guide</a>.
*
* @property string $id Unique identifier for the object. Represented as the ISO country code for this country.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property string $default_currency The default currency for this country. This applies to both payment methods and bank accounts.
* @property \Stripe\StripeObject $supported_bank_account_currencies Currencies that can be accepted in the specific country (for transfers).
* @property string[] $supported_payment_currencies Currencies that can be accepted in the specified country (for payments).
* @property string[] $supported_payment_methods Payment methods available in the specified country. You may need to enable some payment methods (e.g., <a href="https://stripe.com/docs/ach">ACH</a>) on your account before they appear in this list. The <code>stripe</code> payment method refers to <a href="https://stripe.com/docs/connect/destination-charges">charging through your platform</a>.
* @property string[] $supported_transfer_countries Countries that can accept transfers from the specified country.
* @property \Stripe\StripeObject $verification_fields
*/
class CountrySpec extends ApiResource
{
const OBJECT_NAME = 'country_spec';
use ApiOperations\All;
use ApiOperations\Retrieve;
}

View File

@ -0,0 +1,41 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* A coupon contains information about a percent-off or amount-off discount you
* might want to apply to a customer. Coupons may be applied to <a
* href="https://stripe.com/docs/api#invoices">invoices</a> or <a
* href="https://stripe.com/docs/api#create_order-coupon">orders</a>. Coupons do
* not work with conventional one-off <a
* href="https://stripe.com/docs/api#create_charge">charges</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|int $amount_off Amount (in the <code>currency</code> specified) that will be taken off the subtotal of any invoices for this customer.
* @property \Stripe\StripeObject $applies_to
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property null|string $currency If <code>amount_off</code> has been set, the three-letter <a href="https://stripe.com/docs/currencies">ISO code for the currency</a> of the amount to take off.
* @property string $duration One of <code>forever</code>, <code>once</code>, and <code>repeating</code>. Describes how long a customer who applies this coupon will get the discount.
* @property null|int $duration_in_months If <code>duration</code> is <code>repeating</code>, the number of months the coupon applies. Null if coupon <code>duration</code> is <code>forever</code> or <code>once</code>.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|int $max_redemptions Maximum number of times this coupon can be redeemed, in total, across all customers, before it is no longer valid.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $name Name of the coupon displayed to customers on for instance invoices or receipts.
* @property null|float $percent_off Percent that will be taken off the subtotal of any invoices for this customer for the duration of the coupon. For example, a coupon with percent_off of 50 will make a %s100 invoice %s50 instead.
* @property null|int $redeem_by Date after which the coupon can no longer be redeemed.
* @property int $times_redeemed Number of times this coupon has been applied to a customer.
* @property bool $valid Taking account of the above properties, whether this coupon can still be applied to a customer.
*/
class Coupon extends ApiResource
{
const OBJECT_NAME = 'coupon';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\Retrieve;
use ApiOperations\Update;
}

View File

@ -0,0 +1,111 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Issue a credit note to adjust an invoice's amount after the invoice is
* finalized.
*
* Related guide: <a
* href="https://stripe.com/docs/billing/invoices/credit-notes">Credit Notes</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The integer amount in <strong>%s</strong> representing the total amount of the credit note, including tax.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property string|\Stripe\Customer $customer ID of the customer.
* @property null|string|\Stripe\CustomerBalanceTransaction $customer_balance_transaction Customer balance transaction related to this credit note.
* @property int $discount_amount The integer amount in <strong>%s</strong> representing the total amount of discount that was credited.
* @property \Stripe\StripeObject[] $discount_amounts The aggregate amounts calculated per discount for all line items.
* @property string|\Stripe\Invoice $invoice ID of the invoice.
* @property \Stripe\Collection $lines Line items that make up the credit note
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|string $memo Customer-facing text that appears on the credit note PDF.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property string $number A unique number that identifies this particular credit note and appears on the PDF of the credit note and its associated invoice.
* @property null|int $out_of_band_amount Amount that was credited outside of Stripe.
* @property string $pdf The link to download the PDF of the credit note.
* @property null|string $reason Reason for issuing this credit note, one of <code>duplicate</code>, <code>fraudulent</code>, <code>order_change</code>, or <code>product_unsatisfactory</code>
* @property null|string|\Stripe\Refund $refund Refund related to this credit note.
* @property string $status Status of this credit note, one of <code>issued</code> or <code>void</code>. Learn more about <a href="https://stripe.com/docs/billing/invoices/credit-notes#voiding">voiding credit notes</a>.
* @property int $subtotal The integer amount in <strong>%s</strong> representing the amount of the credit note, excluding tax and invoice level discounts.
* @property \Stripe\StripeObject[] $tax_amounts The aggregate amounts calculated per tax rate for all line items.
* @property int $total The integer amount in <strong>%s</strong> representing the total amount of the credit note, including tax and all discount.
* @property string $type Type of this credit note, one of <code>pre_payment</code> or <code>post_payment</code>. A <code>pre_payment</code> credit note means it was issued when the invoice was open. A <code>post_payment</code> credit note means it was issued when the invoice was paid.
* @property null|int $voided_at The time that the credit note was voided.
*/
class CreditNote extends ApiResource
{
const OBJECT_NAME = 'credit_note';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\NestedResource;
use ApiOperations\Retrieve;
use ApiOperations\Update;
const REASON_DUPLICATE = 'duplicate';
const REASON_FRAUDULENT = 'fraudulent';
const REASON_ORDER_CHANGE = 'order_change';
const REASON_PRODUCT_UNSATISFACTORY = 'product_unsatisfactory';
const STATUS_ISSUED = 'issued';
const STATUS_VOID = 'void';
const TYPE_POST_PAYMENT = 'post_payment';
const TYPE_PRE_PAYMENT = 'pre_payment';
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\CreditNote the previewed credit note
*/
public static function preview($params = null, $opts = null)
{
$url = static::classUrl() . '/preview';
list($response, $opts) = static::_staticRequest('get', $url, $params, $opts);
$obj = Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return CreditNote the voided credit note
*/
public function voidCreditNote($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/void';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
const PATH_LINES = '/lines';
/**
* @param string $id the ID of the credit note on which to retrieve the credit note line items
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of credit note line items
*/
public static function allLines($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_LINES, $params, $opts);
}
}

View File

@ -0,0 +1,26 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The integer amount in <strong>%s</strong> representing the gross amount being credited for this line item, excluding (exclusive) tax and discounts.
* @property null|string $description Description of the item being credited.
* @property int $discount_amount The integer amount in <strong>%s</strong> representing the discount being credited for this line item.
* @property \Stripe\StripeObject[] $discount_amounts The amount of discount calculated per discount for this line item
* @property string $invoice_line_item ID of the invoice line item being credited
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|int $quantity The number of units of product being credited.
* @property \Stripe\StripeObject[] $tax_amounts The amount of tax calculated per tax rate for this line item
* @property \Stripe\TaxRate[] $tax_rates The tax rates which apply to the line item.
* @property string $type The type of the credit note line item, one of <code>invoice_line_item</code> or <code>custom_line_item</code>. When the type is <code>invoice_line_item</code> there is an additional <code>invoice_line_item</code> property on the resource the value of which is the id of the credited line item on the invoice.
* @property null|int $unit_amount The cost of each unit of product being credited.
* @property null|string $unit_amount_decimal Same as <code>unit_amount</code>, but contains a decimal value with at most 12 decimal places.
*/
class CreditNoteLineItem extends ApiResource
{
const OBJECT_NAME = 'credit_note_line_item';
}

View File

@ -0,0 +1,276 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* <code>Customer</code> objects allow you to perform recurring charges, and to
* track multiple charges, that are associated with the same customer. The API
* allows you to create, delete, and update your customers. You can retrieve
* individual customers as well as a list of all your customers.
*
* Related guide: <a
* href="https://stripe.com/docs/payments/save-during-payment">Save a card during
* payment</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|\Stripe\StripeObject $address The customer's address.
* @property int $balance Current balance, if any, being stored on the customer. If negative, the customer has credit to apply to their next invoice. If positive, the customer has an amount owed that will be added to their next invoice. The balance does not refer to any unpaid invoices; it solely takes into account amounts that have yet to be successfully applied to any invoice. This balance is only taken into account as invoices are finalized.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property null|string $currency Three-letter <a href="https://stripe.com/docs/currencies">ISO code for the currency</a> the customer can be charged in for recurring billing purposes.
* @property null|string|\Stripe\StripeObject $default_source <p>ID of the default payment source for the customer.</p><p>If you are using payment methods created via the PaymentMethods API, see the <a href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a> field instead.</p>
* @property null|bool $delinquent When the customer's latest invoice is billed by charging automatically, delinquent is true if the invoice's latest charge is failed. When the customer's latest invoice is billed by sending an invoice, delinquent is true if the invoice is not paid by its due date.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property null|\Stripe\Discount $discount Describes the current discount active on the customer, if there is one.
* @property null|string $email The customer's email address.
* @property null|string $invoice_prefix The prefix for the customer used to generate unique invoice numbers.
* @property \Stripe\StripeObject $invoice_settings
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $name The customer's full name or business name.
* @property int $next_invoice_sequence The suffix of the customer's next invoice number, e.g., 0001.
* @property null|string $phone The customer's phone number.
* @property null|string[] $preferred_locales The customer's preferred locales (languages), ordered by preference.
* @property null|\Stripe\StripeObject $shipping Mailing and shipping address for the customer. Appears on invoices emailed to this customer.
* @property \Stripe\Collection $sources The customer's payment sources, if any.
* @property null|\Stripe\Collection $subscriptions The customer's current subscriptions, if any.
* @property null|string $tax_exempt Describes the customer's tax exemption status. One of <code>none</code>, <code>exempt</code>, or <code>reverse</code>. When set to <code>reverse</code>, invoice and receipt PDFs include the text <strong>&quot;Reverse charge&quot;</strong>.
* @property \Stripe\Collection $tax_ids The customer's tax IDs.
*/
class Customer extends ApiResource
{
const OBJECT_NAME = 'customer';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\NestedResource;
use ApiOperations\Retrieve;
use ApiOperations\Update;
const TAX_EXEMPT_EXEMPT = 'exempt';
const TAX_EXEMPT_NONE = 'none';
const TAX_EXEMPT_REVERSE = 'reverse';
public static function getSavedNestedResources()
{
static $savedNestedResources = null;
if (null === $savedNestedResources) {
$savedNestedResources = new Util\Set([
'source',
]);
}
return $savedNestedResources;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @return \Stripe\Customer the updated customer
*/
public function deleteDiscount($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/discount';
list($response, $opts) = $this->_request('delete', $url, $params, $opts);
$this->refreshFrom(['discount' => null], $opts, true);
}
const PATH_BALANCE_TRANSACTIONS = '/balance_transactions';
/**
* @param string $id the ID of the customer on which to retrieve the customer balance transactions
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of customer balance transactions
*/
public static function allBalanceTransactions($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_BALANCE_TRANSACTIONS, $params, $opts);
}
/**
* @param string $id the ID of the customer on which to create the customer balance transaction
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\CustomerBalanceTransaction
*/
public static function createBalanceTransaction($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_BALANCE_TRANSACTIONS, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the customer balance transaction belongs
* @param string $balanceTransactionId the ID of the customer balance transaction to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\CustomerBalanceTransaction
*/
public static function retrieveBalanceTransaction($id, $balanceTransactionId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_BALANCE_TRANSACTIONS, $balanceTransactionId, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the customer balance transaction belongs
* @param string $balanceTransactionId the ID of the customer balance transaction to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\CustomerBalanceTransaction
*/
public static function updateBalanceTransaction($id, $balanceTransactionId, $params = null, $opts = null)
{
return self::_updateNestedResource($id, static::PATH_BALANCE_TRANSACTIONS, $balanceTransactionId, $params, $opts);
}
const PATH_SOURCES = '/sources';
/**
* @param string $id the ID of the customer on which to retrieve the payment sources
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of payment sources (AlipayAccount, BankAccount, BitcoinReceiver, Card or Source)
*/
public static function allSources($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_SOURCES, $params, $opts);
}
/**
* @param string $id the ID of the customer on which to create the payment source
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\AlipayAccount|\Stripe\BankAccount|\Stripe\BitcoinReceiver|\Stripe\Card|\Stripe\Source
*/
public static function createSource($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_SOURCES, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the payment source belongs
* @param string $sourceId the ID of the payment source to delete
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\AlipayAccount|\Stripe\BankAccount|\Stripe\BitcoinReceiver|\Stripe\Card|\Stripe\Source
*/
public static function deleteSource($id, $sourceId, $params = null, $opts = null)
{
return self::_deleteNestedResource($id, static::PATH_SOURCES, $sourceId, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the payment source belongs
* @param string $sourceId the ID of the payment source to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\AlipayAccount|\Stripe\BankAccount|\Stripe\BitcoinReceiver|\Stripe\Card|\Stripe\Source
*/
public static function retrieveSource($id, $sourceId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_SOURCES, $sourceId, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the payment source belongs
* @param string $sourceId the ID of the payment source to update
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\AlipayAccount|\Stripe\BankAccount|\Stripe\BitcoinReceiver|\Stripe\Card|\Stripe\Source
*/
public static function updateSource($id, $sourceId, $params = null, $opts = null)
{
return self::_updateNestedResource($id, static::PATH_SOURCES, $sourceId, $params, $opts);
}
const PATH_TAX_IDS = '/tax_ids';
/**
* @param string $id the ID of the customer on which to retrieve the tax ids
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Collection the list of tax ids
*/
public static function allTaxIds($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_TAX_IDS, $params, $opts);
}
/**
* @param string $id the ID of the customer on which to create the tax id
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\TaxId
*/
public static function createTaxId($id, $params = null, $opts = null)
{
return self::_createNestedResource($id, static::PATH_TAX_IDS, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the tax id belongs
* @param string $taxIdId the ID of the tax id to delete
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\TaxId
*/
public static function deleteTaxId($id, $taxIdId, $params = null, $opts = null)
{
return self::_deleteNestedResource($id, static::PATH_TAX_IDS, $taxIdId, $params, $opts);
}
/**
* @param string $id the ID of the customer to which the tax id belongs
* @param string $taxIdId the ID of the tax id to retrieve
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\TaxId
*/
public static function retrieveTaxId($id, $taxIdId, $params = null, $opts = null)
{
return self::_retrieveNestedResource($id, static::PATH_TAX_IDS, $taxIdId, $params, $opts);
}
}

View File

@ -0,0 +1,103 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Each customer has a <a
* href="https://stripe.com/docs/api/customers/object#customer_object-balance"><code>balance</code></a>
* value, which denotes a debit or credit that's automatically applied to their
* next invoice upon finalization. You may modify the value directly by using the
* <a href="https://stripe.com/docs/api/customers/update">update customer API</a>,
* or by creating a Customer Balance Transaction, which increments or decrements
* the customer's <code>balance</code> by the specified <code>amount</code>.
*
* Related guide: <a
* href="https://stripe.com/docs/billing/customer/balance">Customer Balance</a> to
* learn more.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The amount of the transaction. A negative value is a credit for the customer's balance, and a positive value is a debit to the customer's <code>balance</code>.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property null|string|\Stripe\CreditNote $credit_note The ID of the credit note (if any) related to the transaction.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property string|\Stripe\Customer $customer The ID of the customer the transaction belongs to.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property int $ending_balance The customer's <code>balance</code> after the transaction was applied. A negative value decreases the amount due on the customer's next invoice. A positive value increases the amount due on the customer's next invoice.
* @property null|string|\Stripe\Invoice $invoice The ID of the invoice (if any) related to the transaction.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|\Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property string $type Transaction type: <code>adjustment</code>, <code>applied_to_invoice</code>, <code>credit_note</code>, <code>initial</code>, <code>invoice_too_large</code>, <code>invoice_too_small</code>, <code>unspent_receiver_credit</code>, or <code>unapplied_from_invoice</code>. See the <a href="https://stripe.com/docs/billing/customer/balance#types">Customer Balance page</a> to learn more about transaction types.
*/
class CustomerBalanceTransaction extends ApiResource
{
const OBJECT_NAME = 'customer_balance_transaction';
const TYPE_ADJUSTMENT = 'adjustment';
const TYPE_APPLIED_TO_INVOICE = 'applied_to_invoice';
const TYPE_CREDIT_NOTE = 'credit_note';
const TYPE_INITIAL = 'initial';
const TYPE_INVOICE_TOO_LARGE = 'invoice_too_large';
const TYPE_INVOICE_TOO_SMALL = 'invoice_too_small';
const TYPE_UNSPENT_RECEIVER_CREDIT = 'unspent_receiver_credit';
const TYPE_ADJUSTEMENT = 'adjustment';
/**
* @return string the API URL for this balance transaction
*/
public function instanceUrl()
{
$id = $this['id'];
$customer = $this['customer'];
if (!$id) {
throw new Exception\UnexpectedValueException(
"Could not determine which URL to request: class instance has invalid ID: {$id}",
null
);
}
$id = Util\Util::utf8($id);
$customer = Util\Util::utf8($customer);
$base = Customer::classUrl();
$customerExtn = \urlencode($customer);
$extn = \urlencode($id);
return "{$base}/{$customerExtn}/balance_transactions/{$extn}";
}
/**
* @param array|string $_id
* @param null|array|string $_opts
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function retrieve($_id, $_opts = null)
{
$msg = 'Customer Balance Transactions cannot be retrieved without a ' .
'customer ID. Retrieve a Customer Balance Transaction using ' .
"`Customer::retrieveBalanceTransaction('customer_id', " .
"'balance_transaction_id')`.";
throw new Exception\BadMethodCallException($msg);
}
/**
* @param string $_id
* @param null|array $_params
* @param null|array|string $_options
*
* @throws \Stripe\Exception\BadMethodCallException
*/
public static function update($_id, $_params = null, $_options = null)
{
$msg = 'Customer Balance Transactions cannot be updated without a ' .
'customer ID. Update a Customer Balance Transaction using ' .
"`Customer::updateBalanceTransaction('customer_id', " .
"'balance_transaction_id', \$updateParams)`.";
throw new Exception\BadMethodCallException($msg);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace Stripe;
/**
* Class Discount.
*
* @property string $object
* @property Coupon $coupon
* @property string $customer
* @property int $end
* @property int $start
* @property string $subscription
*/
class Discount extends StripeObject
{
const OBJECT_NAME = 'discount';
}

View File

@ -0,0 +1,82 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* A dispute occurs when a customer questions your charge with their card issuer.
* When this happens, you're given the opportunity to respond to the dispute with
* evidence that shows that the charge is legitimate. You can find more information
* about the dispute process in our <a href="/docs/disputes">Disputes and Fraud</a>
* documentation.
*
* Related guide: <a href="https://stripe.com/docs/disputes">Disputes and
* Fraud</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount Disputed amount. Usually the amount of the charge, but can differ (usually because of currency fluctuation or because only part of the order is disputed).
* @property \Stripe\BalanceTransaction[] $balance_transactions List of zero, one, or two balance transactions that show funds withdrawn and reinstated to your Stripe account as a result of this dispute.
* @property string|\Stripe\Charge $charge ID of the charge that was disputed.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property \Stripe\StripeObject $evidence
* @property \Stripe\StripeObject $evidence_details
* @property bool $is_charge_refundable If true, it is still possible to refund the disputed payment. Once the payment has been fully refunded, no further funds will be withdrawn from your Stripe account as a result of this dispute.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $network_reason_code Network-dependent reason code for the dispute.
* @property null|string|\Stripe\PaymentIntent $payment_intent ID of the PaymentIntent that was disputed.
* @property string $reason Reason given by cardholder for dispute. Possible values are <code>bank_cannot_process</code>, <code>check_returned</code>, <code>credit_not_processed</code>, <code>customer_initiated</code>, <code>debit_not_authorized</code>, <code>duplicate</code>, <code>fraudulent</code>, <code>general</code>, <code>incorrect_account_details</code>, <code>insufficient_funds</code>, <code>product_not_received</code>, <code>product_unacceptable</code>, <code>subscription_canceled</code>, or <code>unrecognized</code>. Read more about <a href="https://stripe.com/docs/disputes/categories">dispute reasons</a>.
* @property string $status Current status of dispute. Possible values are <code>warning_needs_response</code>, <code>warning_under_review</code>, <code>warning_closed</code>, <code>needs_response</code>, <code>under_review</code>, <code>charge_refunded</code>, <code>won</code>, or <code>lost</code>.
*/
class Dispute extends ApiResource
{
const OBJECT_NAME = 'dispute';
use ApiOperations\All;
use ApiOperations\Retrieve;
use ApiOperations\Update;
const REASON_BANK_CANNOT_PROCESS = 'bank_cannot_process';
const REASON_CHECK_RETURNED = 'check_returned';
const REASON_CREDIT_NOT_PROCESSED = 'credit_not_processed';
const REASON_CUSTOMER_INITIATED = 'customer_initiated';
const REASON_DEBIT_NOT_AUTHORIZED = 'debit_not_authorized';
const REASON_DUPLICATE = 'duplicate';
const REASON_FRAUDULENT = 'fraudulent';
const REASON_GENERAL = 'general';
const REASON_INCORRECT_ACCOUNT_DETAILS = 'incorrect_account_details';
const REASON_INSUFFICIENT_FUNDS = 'insufficient_funds';
const REASON_PRODUCT_NOT_RECEIVED = 'product_not_received';
const REASON_PRODUCT_UNACCEPTABLE = 'product_unacceptable';
const REASON_SUBSCRIPTION_CANCELED = 'subscription_canceled';
const REASON_UNRECOGNIZED = 'unrecognized';
const STATUS_CHARGE_REFUNDED = 'charge_refunded';
const STATUS_LOST = 'lost';
const STATUS_NEEDS_RESPONSE = 'needs_response';
const STATUS_UNDER_REVIEW = 'under_review';
const STATUS_WARNING_CLOSED = 'warning_closed';
const STATUS_WARNING_NEEDS_RESPONSE = 'warning_needs_response';
const STATUS_WARNING_UNDER_REVIEW = 'warning_under_review';
const STATUS_WON = 'won';
/**
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Dispute the closed dispute
*/
// TODO: add $params to standardize signature
public function close($opts = null)
{
$url = $this->instanceUrl() . '/close';
list($response, $opts) = $this->_request('post', $url, null, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}

View File

@ -0,0 +1,43 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property int $expires Time at which the key will expire. Measured in seconds since the Unix epoch.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property string $secret The key's secret. You can use this value to make authorized requests to the Stripe API.
* @property array $associated_objects
*/
class EphemeralKey extends ApiResource
{
const OBJECT_NAME = 'ephemeral_key';
use ApiOperations\Delete;
use ApiOperations\Create {
create as protected _create;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\InvalidArgumentException if stripe_version is missing
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\EphemeralKey the created key
*/
public static function create($params = null, $opts = null)
{
if (!$opts || !isset($opts['stripe_version'])) {
throw new Exception\InvalidArgumentException('stripe_version must be specified to create an ephemeral key');
}
return self::_create($params, $opts);
}
}

View File

@ -0,0 +1,161 @@
<?php
namespace Stripe;
/**
* Class ErrorObject.
*
* @property string $charge For card errors, the ID of the failed charge.
* @property string $code For some errors that could be handled
* programmatically, a short string indicating the error code reported.
* @property string $decline_code For card errors resulting from a card issuer
* decline, a short string indicating the card issuer's reason for the
* decline if they provide one.
* @property string $doc_url A URL to more information about the error code
* reported.
* @property string $message A human-readable message providing more details
* about the error. For card errors, these messages can be shown to your
* users.
* @property string $param If the error is parameter-specific, the parameter
* related to the error. For example, you can use this to display a message
* near the correct form field.
* @property PaymentIntent $payment_intent The PaymentIntent object for errors
* returned on a request involving a PaymentIntent.
* @property PaymentMethod $payment_method The PaymentMethod object for errors
* returned on a request involving a PaymentMethod.
* @property SetupIntent $setup_intent The SetupIntent object for errors
* returned on a request involving a SetupIntent.
* @property StripeObject $source The source object for errors returned on a
* request involving a source.
* @property string $type The type of error returned. One of
* `api_connection_error`, `api_error`, `authentication_error`,
* `card_error`, `idempotency_error`, `invalid_request_error`, or
* `rate_limit_error`.
*/
class ErrorObject extends StripeObject
{
/**
* Possible string representations of an error's code.
*
* @see https://stripe.com/docs/error-codes
*/
const CODE_ACCOUNT_ALREADY_EXISTS = 'account_already_exists';
const CODE_ACCOUNT_COUNTRY_INVALID_ADDRESS = 'account_country_invalid_address';
const CODE_ACCOUNT_INVALID = 'account_invalid';
const CODE_ACCOUNT_NUMBER_INVALID = 'account_number_invalid';
const CODE_ALIPAY_UPGRADE_REQUIRED = 'alipay_upgrade_required';
const CODE_AMOUNT_TOO_LARGE = 'amount_too_large';
const CODE_AMOUNT_TOO_SMALL = 'amount_too_small';
const CODE_API_KEY_EXPIRED = 'api_key_expired';
const CODE_BALANCE_INSUFFICIENT = 'balance_insufficient';
const CODE_BANK_ACCOUNT_EXISTS = 'bank_account_exists';
const CODE_BANK_ACCOUNT_UNUSABLE = 'bank_account_unusable';
const CODE_BANK_ACCOUNT_UNVERIFIED = 'bank_account_unverified';
const CODE_BITCOIN_UPGRADE_REQUIRED = 'bitcoin_upgrade_required';
const CODE_CARD_DECLINED = 'card_declined';
const CODE_CHARGE_ALREADY_CAPTURED = 'charge_already_captured';
const CODE_CHARGE_ALREADY_REFUNDED = 'charge_already_refunded';
const CODE_CHARGE_DISPUTED = 'charge_disputed';
const CODE_CHARGE_EXCEEDS_SOURCE_LIMIT = 'charge_exceeds_source_limit';
const CODE_CHARGE_EXPIRED_FOR_CAPTURE = 'charge_expired_for_capture';
const CODE_COUNTRY_UNSUPPORTED = 'country_unsupported';
const CODE_COUPON_EXPIRED = 'coupon_expired';
const CODE_CUSTOMER_MAX_SUBSCRIPTIONS = 'customer_max_subscriptions';
const CODE_EMAIL_INVALID = 'email_invalid';
const CODE_EXPIRED_CARD = 'expired_card';
const CODE_IDEMPOTENCY_KEY_IN_USE = 'idempotency_key_in_use';
const CODE_INCORRECT_ADDRESS = 'incorrect_address';
const CODE_INCORRECT_CVC = 'incorrect_cvc';
const CODE_INCORRECT_NUMBER = 'incorrect_number';
const CODE_INCORRECT_ZIP = 'incorrect_zip';
const CODE_INSTANT_PAYOUTS_UNSUPPORTED = 'instant_payouts_unsupported';
const CODE_INVALID_CARD_TYPE = 'invalid_card_type';
const CODE_INVALID_CHARGE_AMOUNT = 'invalid_charge_amount';
const CODE_INVALID_CVC = 'invalid_cvc';
const CODE_INVALID_EXPIRY_MONTH = 'invalid_expiry_month';
const CODE_INVALID_EXPIRY_YEAR = 'invalid_expiry_year';
const CODE_INVALID_NUMBER = 'invalid_number';
const CODE_INVALID_SOURCE_USAGE = 'invalid_source_usage';
const CODE_INVOICE_NO_CUSTOMER_LINE_ITEMS = 'invoice_no_customer_line_items';
const CODE_INVOICE_NO_SUBSCRIPTION_LINE_ITEMS = 'invoice_no_subscription_line_items';
const CODE_INVOICE_NOT_EDITABLE = 'invoice_not_editable';
const CODE_INVOICE_PAYMENT_INTENT_REQUIRES_ACTION = 'invoice_payment_intent_requires_action';
const CODE_INVOICE_UPCOMING_NONE = 'invoice_upcoming_none';
const CODE_LIVEMODE_MISMATCH = 'livemode_mismatch';
const CODE_LOCK_TIMEOUT = 'lock_timeout';
const CODE_MISSING = 'missing';
const CODE_NOT_ALLOWED_ON_STANDARD_ACCOUNT = 'not_allowed_on_standard_account';
const CODE_ORDER_CREATION_FAILED = 'order_creation_failed';
const CODE_ORDER_REQUIRED_SETTINGS = 'order_required_settings';
const CODE_ORDER_STATUS_INVALID = 'order_status_invalid';
const CODE_ORDER_UPSTREAM_TIMEOUT = 'order_upstream_timeout';
const CODE_OUT_OF_INVENTORY = 'out_of_inventory';
const CODE_PARAMETER_INVALID_EMPTY = 'parameter_invalid_empty';
const CODE_PARAMETER_INVALID_INTEGER = 'parameter_invalid_integer';
const CODE_PARAMETER_INVALID_STRING_BLANK = 'parameter_invalid_string_blank';
const CODE_PARAMETER_INVALID_STRING_EMPTY = 'parameter_invalid_string_empty';
const CODE_PARAMETER_MISSING = 'parameter_missing';
const CODE_PARAMETER_UNKNOWN = 'parameter_unknown';
const CODE_PARAMETERS_EXCLUSIVE = 'parameters_exclusive';
const CODE_PAYMENT_INTENT_AUTHENTICATION_FAILURE = 'payment_intent_authentication_failure';
const CODE_PAYMENT_INTENT_INCOMPATIBLE_PAYMENT_METHOD = 'payment_intent_incompatible_payment_method';
const CODE_PAYMENT_INTENT_INVALID_PARAMETER = 'payment_intent_invalid_parameter';
const CODE_PAYMENT_INTENT_PAYMENT_ATTEMPT_FAILED = 'payment_intent_payment_attempt_failed';
const CODE_PAYMENT_INTENT_UNEXPECTED_STATE = 'payment_intent_unexpected_state';
const CODE_PAYMENT_METHOD_UNACTIVATED = 'payment_method_unactivated';
const CODE_PAYMENT_METHOD_UNEXPECTED_STATE = 'payment_method_unexpected_state';
const CODE_PAYOUTS_NOT_ALLOWED = 'payouts_not_allowed';
const CODE_PLATFORM_API_KEY_EXPIRED = 'platform_api_key_expired';
const CODE_POSTAL_CODE_INVALID = 'postal_code_invalid';
const CODE_PROCESSING_ERROR = 'processing_error';
const CODE_PRODUCT_INACTIVE = 'product_inactive';
const CODE_RATE_LIMIT = 'rate_limit';
const CODE_RESOURCE_ALREADY_EXISTS = 'resource_already_exists';
const CODE_RESOURCE_MISSING = 'resource_missing';
const CODE_ROUTING_NUMBER_INVALID = 'routing_number_invalid';
const CODE_SECRET_KEY_REQUIRED = 'secret_key_required';
const CODE_SEPA_UNSUPPORTED_ACCOUNT = 'sepa_unsupported_account';
const CODE_SETUP_ATTEMPT_FAILED = 'setup_attempt_failed';
const CODE_SETUP_INTENT_AUTHENTICATION_FAILURE = 'setup_intent_authentication_failure';
const CODE_SETUP_INTENT_UNEXPECTED_STATE = 'setup_intent_unexpected_state';
const CODE_SHIPPING_CALCULATION_FAILED = 'shipping_calculation_failed';
const CODE_SKU_INACTIVE = 'sku_inactive';
const CODE_STATE_UNSUPPORTED = 'state_unsupported';
const CODE_TAX_ID_INVALID = 'tax_id_invalid';
const CODE_TAXES_CALCULATION_FAILED = 'taxes_calculation_failed';
const CODE_TESTMODE_CHARGES_ONLY = 'testmode_charges_only';
const CODE_TLS_VERSION_UNSUPPORTED = 'tls_version_unsupported';
const CODE_TOKEN_ALREADY_USED = 'token_already_used';
const CODE_TOKEN_IN_USE = 'token_in_use';
const CODE_TRANSFERS_NOT_ALLOWED = 'transfers_not_allowed';
const CODE_UPSTREAM_ORDER_CREATION_FAILED = 'upstream_order_creation_failed';
const CODE_URL_INVALID = 'url_invalid';
/**
* Refreshes this object using the provided values.
*
* @param array $values
* @param null|array|string|Util\RequestOptions $opts
* @param bool $partial defaults to false
*/
public function refreshFrom($values, $opts, $partial = false)
{
// Unlike most other API resources, the API will omit attributes in
// error objects when they have a null value. We manually set default
// values here to facilitate generic error handling.
$values = \array_merge([
'charge' => null,
'code' => null,
'decline_code' => null,
'doc_url' => null,
'message' => null,
'param' => null,
'payment_intent' => null,
'payment_method' => null,
'setup_intent' => null,
'source' => null,
'type' => null,
], $values);
parent::refreshFrom($values, $opts, $partial);
}
}

View File

@ -0,0 +1,212 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Events are our way of letting you know when something interesting happens in
* your account. When an interesting event occurs, we create a new
* <code>Event</code> object. For example, when a charge succeeds, we create a
* <code>charge.succeeded</code> event; and when an invoice payment attempt fails,
* we create an <code>invoice.payment_failed</code> event. Note that many API
* requests may cause multiple events to be created. For example, if you create a
* new subscription for a customer, you will receive both a
* <code>customer.subscription.created</code> event and a
* <code>charge.succeeded</code> event.
*
* Events occur when the state of another API resource changes. The state of that
* resource at the time of the change is embedded in the event's data field. For
* example, a <code>charge.succeeded</code> event will contain a charge, and an
* <code>invoice.payment_failed</code> event will contain an invoice.
*
* As with other API resources, you can use endpoints to retrieve an <a
* href="https://stripe.com/docs/api#retrieve_event">individual event</a> or a <a
* href="https://stripe.com/docs/api#list_events">list of events</a> from the API.
* We also have a separate <a
* href="http://en.wikipedia.org/wiki/Webhook">webhooks</a> system for sending the
* <code>Event</code> objects directly to an endpoint on your server. Webhooks are
* managed in your <a href="https://dashboard.stripe.com/account/webhooks">account
* settings</a>, and our <a href="https://stripe.com/docs/webhooks">Using
* Webhooks</a> guide will help you get set up.
*
* When using <a href="https://stripe.com/docs/connect">Connect</a>, you can also
* receive notifications of events that occur in connected accounts. For these
* events, there will be an additional <code>account</code> attribute in the
* received <code>Event</code> object.
*
* <strong>NOTE:</strong> Right now, access to events through the <a
* href="https://stripe.com/docs/api#retrieve_event">Retrieve Event API</a> is
* guaranteed only for 30 days.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property string $account The connected account that originated the event.
* @property null|string $api_version The Stripe API version used to render <code>data</code>. <em>Note: This property is populated only for events on or after October 31, 2014</em>.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property \Stripe\StripeObject $data
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property int $pending_webhooks Number of webhooks that have yet to be successfully delivered (i.e., to return a 20x response) to the URLs you've specified.
* @property null|\Stripe\StripeObject $request Information on the API request that instigated the event.
* @property string $type Description of the event (e.g., <code>invoice.created</code> or <code>charge.refunded</code>).
*/
class Event extends ApiResource
{
const OBJECT_NAME = 'event';
use ApiOperations\All;
use ApiOperations\Retrieve;
/**
* Possible string representations of event types.
*
* @see https://stripe.com/docs/api#event_types
*/
const ACCOUNT_UPDATED = 'account.updated';
const ACCOUNT_APPLICATION_AUTHORIZED = 'account.application.authorized';
const ACCOUNT_APPLICATION_DEAUTHORIZED = 'account.application.deauthorized';
const ACCOUNT_EXTERNAL_ACCOUNT_CREATED = 'account.external_account.created';
const ACCOUNT_EXTERNAL_ACCOUNT_DELETED = 'account.external_account.deleted';
const ACCOUNT_EXTERNAL_ACCOUNT_UPDATED = 'account.external_account.updated';
const APPLICATION_FEE_CREATED = 'application_fee.created';
const APPLICATION_FEE_REFUNDED = 'application_fee.refunded';
const APPLICATION_FEE_REFUND_UPDATED = 'application_fee.refund.updated';
const BALANCE_AVAILABLE = 'balance.available';
const CHARGE_CAPTURED = 'charge.captured';
const CHARGE_EXPIRED = 'charge.expired';
const CHARGE_FAILED = 'charge.failed';
const CHARGE_PENDING = 'charge.pending';
const CHARGE_REFUNDED = 'charge.refunded';
const CHARGE_SUCCEEDED = 'charge.succeeded';
const CHARGE_UPDATED = 'charge.updated';
const CHARGE_DISPUTE_CLOSED = 'charge.dispute.closed';
const CHARGE_DISPUTE_CREATED = 'charge.dispute.created';
const CHARGE_DISPUTE_FUNDS_REINSTATED = 'charge.dispute.funds_reinstated';
const CHARGE_DISPUTE_FUNDS_WITHDRAWN = 'charge.dispute.funds_withdrawn';
const CHARGE_DISPUTE_UPDATED = 'charge.dispute.updated';
const CHARGE_REFUND_UPDATED = 'charge.refund.updated';
const CHECKOUT_SESSION_ASYNC_PAYMENT_FAILED = 'checkout.session.async_payment_failed';
const CHECKOUT_SESSION_ASYNC_PAYMENT_SUCCEEDED = 'checkout.session.async_payment_succeeded';
const CHECKOUT_SESSION_COMPLETED = 'checkout.session.completed';
const COUPON_CREATED = 'coupon.created';
const COUPON_DELETED = 'coupon.deleted';
const COUPON_UPDATED = 'coupon.updated';
const CREDIT_NOTE_CREATED = 'credit_note.created';
const CREDIT_NOTE_UPDATED = 'credit_note.updated';
const CREDIT_NOTE_VOIDED = 'credit_note.voided';
const CUSTOMER_CREATED = 'customer.created';
const CUSTOMER_DELETED = 'customer.deleted';
const CUSTOMER_UPDATED = 'customer.updated';
const CUSTOMER_DISCOUNT_CREATED = 'customer.discount.created';
const CUSTOMER_DISCOUNT_DELETED = 'customer.discount.deleted';
const CUSTOMER_DISCOUNT_UPDATED = 'customer.discount.updated';
const CUSTOMER_SOURCE_CREATED = 'customer.source.created';
const CUSTOMER_SOURCE_DELETED = 'customer.source.deleted';
const CUSTOMER_SOURCE_EXPIRING = 'customer.source.expiring';
const CUSTOMER_SOURCE_UPDATED = 'customer.source.updated';
const CUSTOMER_SUBSCRIPTION_CREATED = 'customer.subscription.created';
const CUSTOMER_SUBSCRIPTION_DELETED = 'customer.subscription.deleted';
const CUSTOMER_SUBSCRIPTION_TRIAL_WILL_END = 'customer.subscription.trial_will_end';
const CUSTOMER_SUBSCRIPTION_UPDATED = 'customer.subscription.updated';
const FILE_CREATED = 'file.created';
const INVOICE_CREATED = 'invoice.created';
const INVOICE_DELETED = 'invoice.deleted';
const INVOICE_FINALIZED = 'invoice.finalized';
const INVOICE_MARKED_UNCOLLECTIBLE = 'invoice.marked_uncollectible';
const INVOICE_PAID = 'invoice.paid';
const INVOICE_PAYMENT_ACTION_REQUIRED = 'invoice.payment_action_required';
const INVOICE_PAYMENT_FAILED = 'invoice.payment_failed';
const INVOICE_PAYMENT_SUCCEEDED = 'invoice.payment_succeeded';
const INVOICE_SENT = 'invoice.sent';
const INVOICE_UPCOMING = 'invoice.upcoming';
const INVOICE_UPDATED = 'invoice.updated';
const INVOICE_VOIDED = 'invoice.voided';
const INVOICEITEM_CREATED = 'invoiceitem.created';
const INVOICEITEM_DELETED = 'invoiceitem.deleted';
const INVOICEITEM_UPDATED = 'invoiceitem.updated';
const ISSUER_FRAUD_RECORD_CREATED = 'issuer_fraud_record.created';
const ISSUING_AUTHORIZATION_CREATED = 'issuing_authorization.created';
const ISSUING_AUTHORIZATION_REQUEST = 'issuing_authorization.request';
const ISSUING_AUTHORIZATION_UPDATED = 'issuing_authorization.updated';
const ISSUING_CARD_CREATED = 'issuing_card.created';
const ISSUING_CARD_UPDATED = 'issuing_card.updated';
const ISSUING_CARDHOLDER_CREATED = 'issuing_cardholder.created';
const ISSUING_CARDHOLDER_UPDATED = 'issuing_cardholder.updated';
const ISSUING_DISPUTE_CREATED = 'issuing_dispute.created';
const ISSUING_DISPUTE_FUNDS_REINSTATED = 'issuing_dispute.funds_reinstated';
const ISSUING_DISPUTE_UPDATED = 'issuing_dispute.updated';
const ISSUING_TRANSACTION_CREATED = 'issuing_transaction.created';
const ISSUING_TRANSACTION_UPDATED = 'issuing_transaction.updated';
const ORDER_CREATED = 'order.created';
const ORDER_PAYMENT_FAILED = 'order.payment_failed';
const ORDER_PAYMENT_SUCCEEDED = 'order.payment_succeeded';
const ORDER_UPDATED = 'order.updated';
const ORDER_RETURN_CREATED = 'order_return.created';
const PAYMENT_INTENT_AMOUNT_CAPTURABLE_UPDATED = 'payment_intent.amount_capturable_updated';
const PAYMENT_INTENT_CANCELED = 'payment_intent.canceled';
const PAYMENT_INTENT_CREATED = 'payment_intent.created';
const PAYMENT_INTENT_PAYMENT_FAILED = 'payment_intent.payment_failed';
const PAYMENT_INTENT_SUCCEEDED = 'payment_intent.succeeded';
const PAYMENT_METHOD_ATTACHED = 'payment_method.attached';
const PAYMENT_METHOD_CARD_AUTOMATICALLY_UPDATED = 'payment_method.card_automatically_updated';
const PAYMENT_METHOD_DETACHED = 'payment_method.detached';
const PAYMENT_METHOD_UPDATED = 'payment_method.updated';
const PAYOUT_CANCELED = 'payout.canceled';
const PAYOUT_CREATED = 'payout.created';
const PAYOUT_FAILED = 'payout.failed';
const PAYOUT_PAID = 'payout.paid';
const PAYOUT_UPDATED = 'payout.updated';
const PERSON_CREATED = 'person.created';
const PERSON_DELETED = 'person.deleted';
const PERSON_UPDATED = 'person.updated';
const PING = 'ping';
const PLAN_CREATED = 'plan.created';
const PLAN_DELETED = 'plan.deleted';
const PLAN_UPDATED = 'plan.updated';
const PRICE_CREATED = 'price.created';
const PRICE_DELETED = 'price.deleted';
const PRICE_UPDATED = 'price.updated';
const PRODUCT_CREATED = 'product.created';
const PRODUCT_DELETED = 'product.deleted';
const PRODUCT_UPDATED = 'product.updated';
const RECIPIENT_CREATED = 'recipient.created';
const RECIPIENT_DELETED = 'recipient.deleted';
const RECIPIENT_UPDATED = 'recipient.updated';
const REPORTING_REPORT_RUN_FAILED = 'reporting.report_run.failed';
const REPORTING_REPORT_RUN_SUCCEEDED = 'reporting.report_run.succeeded';
const REPORTING_REPORT_TYPE_UPDATED = 'reporting.report_type.updated';
const REVIEW_CLOSED = 'review.closed';
const REVIEW_OPENED = 'review.opened';
const SETUP_INTENT_CANCELED = 'setup_intent.canceled';
const SETUP_INTENT_CREATED = 'setup_intent.created';
const SETUP_INTENT_SETUP_FAILED = 'setup_intent.setup_failed';
const SETUP_INTENT_SUCCEEDED = 'setup_intent.succeeded';
const SIGMA_SCHEDULED_QUERY_RUN_CREATED = 'sigma.scheduled_query_run.created';
const SKU_CREATED = 'sku.created';
const SKU_DELETED = 'sku.deleted';
const SKU_UPDATED = 'sku.updated';
const SOURCE_CANCELED = 'source.canceled';
const SOURCE_CHARGEABLE = 'source.chargeable';
const SOURCE_FAILED = 'source.failed';
const SOURCE_MANDATE_NOTIFICATION = 'source.mandate_notification';
const SOURCE_REFUND_ATTRIBUTES_REQUIRED = 'source.refund_attributes_required';
const SOURCE_TRANSACTION_CREATED = 'source.transaction.created';
const SOURCE_TRANSACTION_UPDATED = 'source.transaction.updated';
const SUBSCRIPTION_SCHEDULE_ABORTED = 'subscription_schedule.aborted';
const SUBSCRIPTION_SCHEDULE_CANCELED = 'subscription_schedule.canceled';
const SUBSCRIPTION_SCHEDULE_COMPLETED = 'subscription_schedule.completed';
const SUBSCRIPTION_SCHEDULE_CREATED = 'subscription_schedule.created';
const SUBSCRIPTION_SCHEDULE_EXPIRING = 'subscription_schedule.expiring';
const SUBSCRIPTION_SCHEDULE_RELEASED = 'subscription_schedule.released';
const SUBSCRIPTION_SCHEDULE_UPDATED = 'subscription_schedule.updated';
const TAX_RATE_CREATED = 'tax_rate.created';
const TAX_RATE_UPDATED = 'tax_rate.updated';
const TOPUP_CANCELED = 'topup.canceled';
const TOPUP_CREATED = 'topup.created';
const TOPUP_FAILED = 'topup.failed';
const TOPUP_REVERSED = 'topup.reversed';
const TOPUP_SUCCEEDED = 'topup.succeeded';
const TRANSFER_CREATED = 'transfer.created';
const TRANSFER_REVERSED = 'transfer.reversed';
const TRANSFER_UPDATED = 'transfer.updated';
}

View File

@ -0,0 +1,12 @@
<?php
namespace Stripe\Exception;
/**
* ApiConnection is thrown in the event that the SDK can't connect to Stripe's
* servers. That can be for a variety of different reasons from a downed
* network to a bad TLS certificate.
*/
class ApiConnectionException extends ApiErrorException
{
}

View File

@ -0,0 +1,219 @@
<?php
namespace Stripe\Exception;
/**
* Implements properties and methods common to all (non-SPL) Stripe exceptions.
*/
abstract class ApiErrorException extends \Exception implements ExceptionInterface
{
protected $error;
protected $httpBody;
protected $httpHeaders;
protected $httpStatus;
protected $jsonBody;
protected $requestId;
protected $stripeCode;
/**
* Creates a new API error exception.
*
* @param string $message the exception message
* @param null|int $httpStatus the HTTP status code
* @param null|string $httpBody the HTTP body as a string
* @param null|array $jsonBody the JSON deserialized body
* @param null|array|\Stripe\Util\CaseInsensitiveArray $httpHeaders the HTTP headers array
* @param null|string $stripeCode the Stripe error code
*
* @return static
*/
public static function factory(
$message,
$httpStatus = null,
$httpBody = null,
$jsonBody = null,
$httpHeaders = null,
$stripeCode = null
) {
$instance = new static($message);
$instance->setHttpStatus($httpStatus);
$instance->setHttpBody($httpBody);
$instance->setJsonBody($jsonBody);
$instance->setHttpHeaders($httpHeaders);
$instance->setStripeCode($stripeCode);
$instance->setRequestId(null);
if ($httpHeaders && isset($httpHeaders['Request-Id'])) {
$instance->setRequestId($httpHeaders['Request-Id']);
}
$instance->setError($instance->constructErrorObject());
return $instance;
}
/**
* Gets the Stripe error object.
*
* @return null|\Stripe\ErrorObject
*/
public function getError()
{
return $this->error;
}
/**
* Sets the Stripe error object.
*
* @param null|\Stripe\ErrorObject $error
*/
public function setError($error)
{
$this->error = $error;
}
/**
* Gets the HTTP body as a string.
*
* @return null|string
*/
public function getHttpBody()
{
return $this->httpBody;
}
/**
* Sets the HTTP body as a string.
*
* @param null|string $httpBody
*/
public function setHttpBody($httpBody)
{
$this->httpBody = $httpBody;
}
/**
* Gets the HTTP headers array.
*
* @return null|array|\Stripe\Util\CaseInsensitiveArray
*/
public function getHttpHeaders()
{
return $this->httpHeaders;
}
/**
* Sets the HTTP headers array.
*
* @param null|array|\Stripe\Util\CaseInsensitiveArray $httpHeaders
*/
public function setHttpHeaders($httpHeaders)
{
$this->httpHeaders = $httpHeaders;
}
/**
* Gets the HTTP status code.
*
* @return null|int
*/
public function getHttpStatus()
{
return $this->httpStatus;
}
/**
* Sets the HTTP status code.
*
* @param null|int $httpStatus
*/
public function setHttpStatus($httpStatus)
{
$this->httpStatus = $httpStatus;
}
/**
* Gets the JSON deserialized body.
*
* @return null|array<string, mixed>
*/
public function getJsonBody()
{
return $this->jsonBody;
}
/**
* Sets the JSON deserialized body.
*
* @param null|array<string, mixed> $jsonBody
*/
public function setJsonBody($jsonBody)
{
$this->jsonBody = $jsonBody;
}
/**
* Gets the Stripe request ID.
*
* @return null|string
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* Sets the Stripe request ID.
*
* @param null|string $requestId
*/
public function setRequestId($requestId)
{
$this->requestId = $requestId;
}
/**
* Gets the Stripe error code.
*
* Cf. the `CODE_*` constants on {@see \Stripe\ErrorObject} for possible
* values.
*
* @return null|string
*/
public function getStripeCode()
{
return $this->stripeCode;
}
/**
* Sets the Stripe error code.
*
* @param null|string $stripeCode
*/
public function setStripeCode($stripeCode)
{
$this->stripeCode = $stripeCode;
}
/**
* Returns the string representation of the exception.
*
* @return string
*/
public function __toString()
{
$statusStr = (null === $this->getHttpStatus()) ? '' : "(Status {$this->getHttpStatus()}) ";
$idStr = (null === $this->getRequestId()) ? '' : "(Request {$this->getRequestId()}) ";
return "{$statusStr}{$idStr}{$this->getMessage()}";
}
protected function constructErrorObject()
{
if (null === $this->jsonBody || !\array_key_exists('error', $this->jsonBody)) {
return null;
}
return \Stripe\ErrorObject::constructFrom($this->jsonBody['error']);
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace Stripe\Exception;
/**
* AuthenticationException is thrown when invalid credentials are used to
* connect to Stripe's servers.
*/
class AuthenticationException extends ApiErrorException
{
}

View File

@ -0,0 +1,7 @@
<?php
namespace Stripe\Exception;
class BadMethodCallException extends \BadMethodCallException implements ExceptionInterface
{
}

View File

@ -0,0 +1,84 @@
<?php
namespace Stripe\Exception;
/**
* CardException is thrown when a user enters a card that can't be charged for
* some reason.
*/
class CardException extends ApiErrorException
{
protected $declineCode;
protected $stripeParam;
/**
* Creates a new CardException exception.
*
* @param string $message the exception message
* @param null|int $httpStatus the HTTP status code
* @param null|string $httpBody the HTTP body as a string
* @param null|array $jsonBody the JSON deserialized body
* @param null|array|\Stripe\Util\CaseInsensitiveArray $httpHeaders the HTTP headers array
* @param null|string $stripeCode the Stripe error code
* @param null|string $declineCode the decline code
* @param null|string $stripeParam the parameter related to the error
*
* @return CardException
*/
public static function factory(
$message,
$httpStatus = null,
$httpBody = null,
$jsonBody = null,
$httpHeaders = null,
$stripeCode = null,
$declineCode = null,
$stripeParam = null
) {
$instance = parent::factory($message, $httpStatus, $httpBody, $jsonBody, $httpHeaders, $stripeCode);
$instance->setDeclineCode($declineCode);
$instance->setStripeParam($stripeParam);
return $instance;
}
/**
* Gets the decline code.
*
* @return null|string
*/
public function getDeclineCode()
{
return $this->declineCode;
}
/**
* Sets the decline code.
*
* @param null|string $declineCode
*/
public function setDeclineCode($declineCode)
{
$this->declineCode = $declineCode;
}
/**
* Gets the parameter related to the error.
*
* @return null|string
*/
public function getStripeParam()
{
return $this->stripeParam;
}
/**
* Sets the parameter related to the error.
*
* @param null|string $stripeParam
*/
public function setStripeParam($stripeParam)
{
$this->stripeParam = $stripeParam;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace Stripe\Exception;
// TODO: remove this check once we drop support for PHP 5
if (\interface_exists(\Throwable::class, false)) {
/**
* The base interface for all Stripe exceptions.
*/
interface ExceptionInterface extends \Throwable
{
}
} else {
/**
* The base interface for all Stripe exceptions.
*/
// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
interface ExceptionInterface
{
}
// phpcs:enable
}

View File

@ -0,0 +1,11 @@
<?php
namespace Stripe\Exception;
/**
* IdempotencyException is thrown in cases where an idempotency key was used
* improperly.
*/
class IdempotencyException extends ApiErrorException
{
}

View File

@ -0,0 +1,7 @@
<?php
namespace Stripe\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}

View File

@ -0,0 +1,60 @@
<?php
namespace Stripe\Exception;
/**
* InvalidRequestException is thrown when a request is initiated with invalid
* parameters.
*/
class InvalidRequestException extends ApiErrorException
{
protected $stripeParam;
/**
* Creates a new InvalidRequestException exception.
*
* @param string $message the exception message
* @param null|int $httpStatus the HTTP status code
* @param null|string $httpBody the HTTP body as a string
* @param null|array $jsonBody the JSON deserialized body
* @param null|array|\Stripe\Util\CaseInsensitiveArray $httpHeaders the HTTP headers array
* @param null|string $stripeCode the Stripe error code
* @param null|string $stripeParam the parameter related to the error
*
* @return InvalidRequestException
*/
public static function factory(
$message,
$httpStatus = null,
$httpBody = null,
$jsonBody = null,
$httpHeaders = null,
$stripeCode = null,
$stripeParam = null
) {
$instance = parent::factory($message, $httpStatus, $httpBody, $jsonBody, $httpHeaders, $stripeCode);
$instance->setStripeParam($stripeParam);
return $instance;
}
/**
* Gets the parameter related to the error.
*
* @return null|string
*/
public function getStripeParam()
{
return $this->stripeParam;
}
/**
* Sets the parameter related to the error.
*
* @param null|string $stripeParam
*/
public function setStripeParam($stripeParam)
{
$this->stripeParam = $stripeParam;
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* The base interface for all Stripe OAuth exceptions.
*/
interface ExceptionInterface extends \Stripe\Exception\ExceptionInterface
{
}

View File

@ -0,0 +1,12 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* InvalidClientException is thrown when the client_id does not belong to you,
* the stripe_user_id does not exist or is not connected to your application,
* or the API key mode (live or test mode) does not match the client_id mode.
*/
class InvalidClientException extends OAuthErrorException
{
}

View File

@ -0,0 +1,13 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* InvalidGrantException is thrown when a specified code doesn't exist, is
* expired, has been used, or doesn't belong to you; a refresh token doesn't
* exist, or doesn't belong to you; or if an API key's mode (live or test)
* doesn't match the mode of a code or refresh token.
*/
class InvalidGrantException extends OAuthErrorException
{
}

View File

@ -0,0 +1,11 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* InvalidRequestException is thrown when a code, refresh token, or grant
* type parameter is not provided, but was required.
*/
class InvalidRequestException extends OAuthErrorException
{
}

View File

@ -0,0 +1,10 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* InvalidScopeException is thrown when an invalid scope parameter is provided.
*/
class InvalidScopeException extends OAuthErrorException
{
}

View File

@ -0,0 +1,19 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* Implements properties and methods common to all (non-SPL) Stripe OAuth
* exceptions.
*/
abstract class OAuthErrorException extends \Stripe\Exception\ApiErrorException
{
protected function constructErrorObject()
{
if (null === $this->jsonBody) {
return null;
}
return \Stripe\OAuthErrorObject::constructFrom($this->jsonBody);
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* UnknownApiErrorException is thrown when the client library receives an
* error from the OAuth API it doesn't know about. Receiving this error usually
* means that your client library is outdated and should be upgraded.
*/
class UnknownOAuthErrorException extends OAuthErrorException
{
}

View File

@ -0,0 +1,11 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* UnsupportedGrantTypeException is thrown when an unuspported grant type
* parameter is specified.
*/
class UnsupportedGrantTypeException extends OAuthErrorException
{
}

View File

@ -0,0 +1,11 @@
<?php
namespace Stripe\Exception\OAuth;
/**
* UnsupportedResponseTypeException is thrown when an unsupported response type
* parameter is specified.
*/
class UnsupportedResponseTypeException extends OAuthErrorException
{
}

View File

@ -0,0 +1,11 @@
<?php
namespace Stripe\Exception;
/**
* PermissionException is thrown in cases where access was attempted on a
* resource that wasn't allowed.
*/
class PermissionException extends ApiErrorException
{
}

View File

@ -0,0 +1,12 @@
<?php
namespace Stripe\Exception;
/**
* RateLimitException is thrown in cases where an account is putting too much
* load on Stripe's API servers (usually by performing too many requests).
* Please back off on request rate.
*/
class RateLimitException extends InvalidRequestException
{
}

View File

@ -0,0 +1,74 @@
<?php
namespace Stripe\Exception;
/**
* SignatureVerificationException is thrown when the signature verification for
* a webhook fails.
*/
class SignatureVerificationException extends \Exception implements ExceptionInterface
{
protected $httpBody;
protected $sigHeader;
/**
* Creates a new SignatureVerificationException exception.
*
* @param string $message the exception message
* @param null|string $httpBody the HTTP body as a string
* @param null|string $sigHeader the `Stripe-Signature` HTTP header
*
* @return SignatureVerificationException
*/
public static function factory(
$message,
$httpBody = null,
$sigHeader = null
) {
$instance = new static($message);
$instance->setHttpBody($httpBody);
$instance->setSigHeader($sigHeader);
return $instance;
}
/**
* Gets the HTTP body as a string.
*
* @return null|string
*/
public function getHttpBody()
{
return $this->httpBody;
}
/**
* Sets the HTTP body as a string.
*
* @param null|string $httpBody
*/
public function setHttpBody($httpBody)
{
$this->httpBody = $httpBody;
}
/**
* Gets the `Stripe-Signature` HTTP header.
*
* @return null|string
*/
public function getSigHeader()
{
return $this->sigHeader;
}
/**
* Sets the `Stripe-Signature` HTTP header.
*
* @param null|string $sigHeader
*/
public function setSigHeader($sigHeader)
{
$this->sigHeader = $sigHeader;
}
}

View File

@ -0,0 +1,7 @@
<?php
namespace Stripe\Exception;
class UnexpectedValueException extends \UnexpectedValueException implements ExceptionInterface
{
}

View File

@ -0,0 +1,12 @@
<?php
namespace Stripe\Exception;
/**
* UnknownApiErrorException is thrown when the client library receives an
* error from the API it doesn't know about. Receiving this error usually
* means that your client library is outdated and should be upgraded.
*/
class UnknownApiErrorException extends ApiErrorException
{
}

View File

@ -0,0 +1,30 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* <code>Exchange Rate</code> objects allow you to determine the rates that Stripe
* is currently using to convert from one currency to another. Since this number is
* variable throughout the day, there are various reasons why you might want to
* know the current rate (for example, to dynamically price an item for a user with
* a default payment in a foreign currency).
*
* If you want a guarantee that the charge is made with a certain exchange rate you
* expect is current, you can pass in <code>exchange_rate</code> to charges
* endpoints. If the value is no longer up to date, the charge won't go through.
* Please refer to our <a href="https://stripe.com/docs/exchange-rates">Exchange
* Rates API</a> guide for more details.
*
* @property string $id Unique identifier for the object. Represented as the three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a> in lowercase.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property \Stripe\StripeObject $rates Hash where the keys are supported currencies and the values are the exchange rate at which the base id currency converts to the key currency.
*/
class ExchangeRate extends ApiResource
{
const OBJECT_NAME = 'exchange_rate';
use ApiOperations\All;
use ApiOperations\Retrieve;
}

View File

@ -0,0 +1,80 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* This is an object representing a file hosted on Stripe's servers. The file may
* have been uploaded by yourself using the <a
* href="https://stripe.com/docs/api#create_file">create file</a> request (for
* example, when uploading dispute evidence) or it may have been created by Stripe
* (for example, the results of a <a href="#scheduled_queries">Sigma scheduled
* query</a>).
*
* Related guide: <a href="https://stripe.com/docs/file-upload">File Upload
* Guide</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property null|string $filename A filename for the file, suitable for saving to a filesystem.
* @property null|\Stripe\Collection $links A list of <a href="https://stripe.com/docs/api#file_links">file links</a> that point at this file.
* @property string $purpose The <a href="https://stripe.com/docs/file-upload#uploading-a-file">purpose</a> of the uploaded file.
* @property int $size The size in bytes of the file object.
* @property null|string $title A user friendly title for the document.
* @property null|string $type The type of the file returned (e.g., <code>csv</code>, <code>pdf</code>, <code>jpg</code>, or <code>png</code>).
* @property null|string $url The URL from which the file can be downloaded using your live secret API key.
*/
class File extends ApiResource
{
const OBJECT_NAME = 'file';
use ApiOperations\All;
use ApiOperations\Retrieve;
const PURPOSE_ADDITIONAL_VERIFICATION = 'additional_verification';
const PURPOSE_BUSINESS_ICON = 'business_icon';
const PURPOSE_BUSINESS_LOGO = 'business_logo';
const PURPOSE_CUSTOMER_SIGNATURE = 'customer_signature';
const PURPOSE_DISPUTE_EVIDENCE = 'dispute_evidence';
const PURPOSE_IDENTITY_DOCUMENT = 'identity_document';
const PURPOSE_PCI_DOCUMENT = 'pci_document';
const PURPOSE_TAX_DOCUMENT_USER_UPLOAD = 'tax_document_user_upload';
// This resource can have two different object names. In latter API
// versions, only `file` is used, but since stripe-php may be used with
// any API version, we need to support deserializing the older
// `file_upload` object into the same class.
const OBJECT_NAME_ALT = 'file_upload';
use ApiOperations\Create {
create as protected _create;
}
public static function classUrl()
{
return '/v1/files';
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\File the created file
*/
public static function create($params = null, $opts = null)
{
$opts = \Stripe\Util\RequestOptions::parse($opts);
if (null === $opts->apiBase) {
$opts->apiBase = Stripe::$apiUploadBase;
}
// Manually flatten params, otherwise curl's multipart encoder will
// choke on nested arrays.
$flatParams = \array_column(\Stripe\Util\Util::flattenParams($params), 1, 0);
return static::_create($flatParams, $opts);
}
}

View File

@ -0,0 +1,30 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* To share the contents of a <code>File</code> object with non-Stripe users, you
* can create a <code>FileLink</code>. <code>FileLink</code>s contain a URL that
* can be used to retrieve the contents of the file without authentication.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property bool $expired Whether this link is already expired.
* @property null|int $expires_at Time at which the link expires.
* @property string|\Stripe\File $file The file object this link points to.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|string $url The publicly accessible URL to download the file.
*/
class FileLink extends ApiResource
{
const OBJECT_NAME = 'file_link';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Retrieve;
use ApiOperations\Update;
}

View File

@ -0,0 +1,22 @@
<?php
namespace Stripe\HttpClient;
interface ClientInterface
{
/**
* @param string $method The HTTP method being used
* @param string $absUrl The URL being requested, including domain and protocol
* @param array $headers Headers to be used in the request (full strings, not KV pairs)
* @param array $params KV pairs for parameters. Can be nested for arrays and hashes
* @param bool $hasFile Whether or not $params references a file (via an @ prefix or
* CURLFile)
*
* @throws \Stripe\Exception\ApiConnectionException
* @throws \Stripe\Exception\UnexpectedValueException
*
* @return array an array whose first element is raw request body, second
* element is HTTP status code and third array of HTTP headers
*/
public function request($method, $absUrl, $headers, $params, $hasFile);
}

View File

@ -0,0 +1,546 @@
<?php
namespace Stripe\HttpClient;
use Stripe\Exception;
use Stripe\Stripe;
use Stripe\Util;
// @codingStandardsIgnoreStart
// PSR2 requires all constants be upper case. Sadly, the CURL_SSLVERSION
// constants do not abide by those rules.
// Note the values come from their position in the enums that
// defines them in cURL's source code.
// Available since PHP 5.5.19 and 5.6.3
if (!\defined('CURL_SSLVERSION_TLSv1_2')) {
\define('CURL_SSLVERSION_TLSv1_2', 6);
}
// @codingStandardsIgnoreEnd
// Available since PHP 7.0.7 and cURL 7.47.0
if (!\defined('CURL_HTTP_VERSION_2TLS')) {
\define('CURL_HTTP_VERSION_2TLS', 4);
}
class CurlClient implements ClientInterface
{
private static $instance;
public static function instance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
protected $defaultOptions;
/** @var \Stripe\Util\RandomGenerator */
protected $randomGenerator;
protected $userAgentInfo;
protected $enablePersistentConnections = true;
protected $enableHttp2;
protected $curlHandle;
protected $requestStatusCallback;
/**
* CurlClient constructor.
*
* Pass in a callable to $defaultOptions that returns an array of CURLOPT_* values to start
* off a request with, or an flat array with the same format used by curl_setopt_array() to
* provide a static set of options. Note that many options are overridden later in the request
* call, including timeouts, which can be set via setTimeout() and setConnectTimeout().
*
* Note that request() will silently ignore a non-callable, non-array $defaultOptions, and will
* throw an exception if $defaultOptions returns a non-array value.
*
* @param null|array|callable $defaultOptions
* @param null|\Stripe\Util\RandomGenerator $randomGenerator
*/
public function __construct($defaultOptions = null, $randomGenerator = null)
{
$this->defaultOptions = $defaultOptions;
$this->randomGenerator = $randomGenerator ?: new Util\RandomGenerator();
$this->initUserAgentInfo();
$this->enableHttp2 = $this->canSafelyUseHttp2();
}
public function __destruct()
{
$this->closeCurlHandle();
}
public function initUserAgentInfo()
{
$curlVersion = \curl_version();
$this->userAgentInfo = [
'httplib' => 'curl ' . $curlVersion['version'],
'ssllib' => $curlVersion['ssl_version'],
];
}
public function getDefaultOptions()
{
return $this->defaultOptions;
}
public function getUserAgentInfo()
{
return $this->userAgentInfo;
}
/**
* @return bool
*/
public function getEnablePersistentConnections()
{
return $this->enablePersistentConnections;
}
/**
* @param bool $enable
*/
public function setEnablePersistentConnections($enable)
{
$this->enablePersistentConnections = $enable;
}
/**
* @return bool
*/
public function getEnableHttp2()
{
return $this->enableHttp2;
}
/**
* @param bool $enable
*/
public function setEnableHttp2($enable)
{
$this->enableHttp2 = $enable;
}
/**
* @return null|callable
*/
public function getRequestStatusCallback()
{
return $this->requestStatusCallback;
}
/**
* Sets a callback that is called after each request. The callback will
* receive the following parameters:
* <ol>
* <li>string $rbody The response body</li>
* <li>integer $rcode The response status code</li>
* <li>\Stripe\Util\CaseInsensitiveArray $rheaders The response headers</li>
* <li>integer $errno The curl error number</li>
* <li>string|null $message The curl error message</li>
* <li>boolean $shouldRetry Whether the request will be retried</li>
* <li>integer $numRetries The number of the retry attempt</li>
* </ol>.
*
* @param null|callable $requestStatusCallback
*/
public function setRequestStatusCallback($requestStatusCallback)
{
$this->requestStatusCallback = $requestStatusCallback;
}
// USER DEFINED TIMEOUTS
const DEFAULT_TIMEOUT = 80;
const DEFAULT_CONNECT_TIMEOUT = 30;
private $timeout = self::DEFAULT_TIMEOUT;
private $connectTimeout = self::DEFAULT_CONNECT_TIMEOUT;
public function setTimeout($seconds)
{
$this->timeout = (int) \max($seconds, 0);
return $this;
}
public function setConnectTimeout($seconds)
{
$this->connectTimeout = (int) \max($seconds, 0);
return $this;
}
public function getTimeout()
{
return $this->timeout;
}
public function getConnectTimeout()
{
return $this->connectTimeout;
}
// END OF USER DEFINED TIMEOUTS
public function request($method, $absUrl, $headers, $params, $hasFile)
{
$method = \strtolower($method);
$opts = [];
if (\is_callable($this->defaultOptions)) { // call defaultOptions callback, set options to return value
$opts = \call_user_func_array($this->defaultOptions, \func_get_args());
if (!\is_array($opts)) {
throw new Exception\UnexpectedValueException('Non-array value returned by defaultOptions CurlClient callback');
}
} elseif (\is_array($this->defaultOptions)) { // set default curlopts from array
$opts = $this->defaultOptions;
}
$params = Util\Util::objectsToIds($params);
if ('get' === $method) {
if ($hasFile) {
throw new Exception\UnexpectedValueException(
'Issuing a GET request with a file parameter'
);
}
$opts[\CURLOPT_HTTPGET] = 1;
if (\count($params) > 0) {
$encoded = Util\Util::encodeParameters($params);
$absUrl = "{$absUrl}?{$encoded}";
}
} elseif ('post' === $method) {
$opts[\CURLOPT_POST] = 1;
$opts[\CURLOPT_POSTFIELDS] = $hasFile ? $params : Util\Util::encodeParameters($params);
} elseif ('delete' === $method) {
$opts[\CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (\count($params) > 0) {
$encoded = Util\Util::encodeParameters($params);
$absUrl = "{$absUrl}?{$encoded}";
}
} else {
throw new Exception\UnexpectedValueException("Unrecognized method {$method}");
}
// It is only safe to retry network failures on POST requests if we
// add an Idempotency-Key header
if (('post' === $method) && (Stripe::$maxNetworkRetries > 0)) {
if (!$this->hasHeader($headers, 'Idempotency-Key')) {
\array_push($headers, 'Idempotency-Key: ' . $this->randomGenerator->uuid());
}
}
// By default for large request body sizes (> 1024 bytes), cURL will
// send a request without a body and with a `Expect: 100-continue`
// header, which gives the server a chance to respond with an error
// status code in cases where one can be determined right away (say
// on an authentication problem for example), and saves the "large"
// request body from being ever sent.
//
// Unfortunately, the bindings don't currently correctly handle the
// success case (in which the server sends back a 100 CONTINUE), so
// we'll error under that condition. To compensate for that problem
// for the time being, override cURL's behavior by simply always
// sending an empty `Expect:` header.
\array_push($headers, 'Expect: ');
$absUrl = Util\Util::utf8($absUrl);
$opts[\CURLOPT_URL] = $absUrl;
$opts[\CURLOPT_RETURNTRANSFER] = true;
$opts[\CURLOPT_CONNECTTIMEOUT] = $this->connectTimeout;
$opts[\CURLOPT_TIMEOUT] = $this->timeout;
$opts[\CURLOPT_HTTPHEADER] = $headers;
$opts[\CURLOPT_CAINFO] = Stripe::getCABundlePath();
if (!Stripe::getVerifySslCerts()) {
$opts[\CURLOPT_SSL_VERIFYPEER] = false;
}
if (!isset($opts[\CURLOPT_HTTP_VERSION]) && $this->getEnableHttp2()) {
// For HTTPS requests, enable HTTP/2, if supported
$opts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2TLS;
}
list($rbody, $rcode, $rheaders) = $this->executeRequestWithRetries($opts, $absUrl);
return [$rbody, $rcode, $rheaders];
}
/**
* @param array $opts cURL options
* @param string $absUrl
*/
private function executeRequestWithRetries($opts, $absUrl)
{
$numRetries = 0;
$isPost = \array_key_exists(\CURLOPT_POST, $opts) && 1 === $opts[\CURLOPT_POST];
while (true) {
$rcode = 0;
$errno = 0;
$message = null;
// Create a callback to capture HTTP headers for the response
$rheaders = new Util\CaseInsensitiveArray();
$headerCallback = function ($curl, $header_line) use (&$rheaders) {
// Ignore the HTTP request line (HTTP/1.1 200 OK)
if (false === \strpos($header_line, ':')) {
return \strlen($header_line);
}
list($key, $value) = \explode(':', \trim($header_line), 2);
$rheaders[\trim($key)] = \trim($value);
return \strlen($header_line);
};
$opts[\CURLOPT_HEADERFUNCTION] = $headerCallback;
$this->resetCurlHandle();
\curl_setopt_array($this->curlHandle, $opts);
$rbody = \curl_exec($this->curlHandle);
if (false === $rbody) {
$errno = \curl_errno($this->curlHandle);
$message = \curl_error($this->curlHandle);
} else {
$rcode = \curl_getinfo($this->curlHandle, \CURLINFO_HTTP_CODE);
}
if (!$this->getEnablePersistentConnections()) {
$this->closeCurlHandle();
}
$shouldRetry = $this->shouldRetry($errno, $rcode, $rheaders, $numRetries);
if (\is_callable($this->getRequestStatusCallback())) {
\call_user_func_array(
$this->getRequestStatusCallback(),
[$rbody, $rcode, $rheaders, $errno, $message, $shouldRetry, $numRetries]
);
}
if ($shouldRetry) {
++$numRetries;
$sleepSeconds = $this->sleepTime($numRetries, $rheaders);
\usleep((int) ($sleepSeconds * 1000000));
} else {
break;
}
}
if (false === $rbody) {
$this->handleCurlError($absUrl, $errno, $message, $numRetries);
}
return [$rbody, $rcode, $rheaders];
}
/**
* @param string $url
* @param int $errno
* @param string $message
* @param int $numRetries
*
* @throws Exception\ApiConnectionException
*/
private function handleCurlError($url, $errno, $message, $numRetries)
{
switch ($errno) {
case \CURLE_COULDNT_CONNECT:
case \CURLE_COULDNT_RESOLVE_HOST:
case \CURLE_OPERATION_TIMEOUTED:
$msg = "Could not connect to Stripe ({$url}). 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';
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 {$url} in your browser.) "
. 'If this problem persists,';
break;
default:
$msg = 'Unexpected error communicating with Stripe. '
. 'If this problem persists,';
}
$msg .= ' let us know at support@stripe.com.';
$msg .= "\n\n(Network error [errno {$errno}]: {$message})";
if ($numRetries > 0) {
$msg .= "\n\nRequest was retried {$numRetries} times.";
}
throw new Exception\ApiConnectionException($msg);
}
/**
* Checks if an error is a problem that we should retry on. This includes both
* socket errors that may represent an intermittent problem and some special
* HTTP statuses.
*
* @param int $errno
* @param int $rcode
* @param array|\Stripe\Util\CaseInsensitiveArray $rheaders
* @param int $numRetries
*
* @return bool
*/
private function shouldRetry($errno, $rcode, $rheaders, $numRetries)
{
if ($numRetries >= Stripe::getMaxNetworkRetries()) {
return false;
}
// Retry on timeout-related problems (either on open or read).
if (\CURLE_OPERATION_TIMEOUTED === $errno) {
return true;
}
// Destination refused the connection, the connection was reset, or a
// variety of other connection failures. This could occur from a single
// saturated server, so retry in case it's intermittent.
if (\CURLE_COULDNT_CONNECT === $errno) {
return true;
}
// The API may ask us not to retry (eg; if doing so would be a no-op)
// or advise us to retry (eg; in cases of lock timeouts); we defer to that.
if (isset($rheaders['stripe-should-retry'])) {
if ('false' === $rheaders['stripe-should-retry']) {
return false;
}
if ('true' === $rheaders['stripe-should-retry']) {
return true;
}
}
// 409 Conflict
if (409 === $rcode) {
return true;
}
// Retry on 500, 503, and other internal errors.
//
// Note that we expect the stripe-should-retry header to be false
// in most cases when a 500 is returned, since our idempotency framework
// would typically replay it anyway.
if ($rcode >= 500) {
return true;
}
return false;
}
/**
* Provides the number of seconds to wait before retrying a request.
*
* @param int $numRetries
* @param array|\Stripe\Util\CaseInsensitiveArray $rheaders
*
* @return int
*/
private function sleepTime($numRetries, $rheaders)
{
// Apply exponential backoff with $initialNetworkRetryDelay on the
// number of $numRetries so far as inputs. Do not allow the number to exceed
// $maxNetworkRetryDelay.
$sleepSeconds = \min(
Stripe::getInitialNetworkRetryDelay() * 1.0 * 2 ** ($numRetries - 1),
Stripe::getMaxNetworkRetryDelay()
);
// Apply some jitter by randomizing the value in the range of
// ($sleepSeconds / 2) to ($sleepSeconds).
$sleepSeconds *= 0.5 * (1 + $this->randomGenerator->randFloat());
// But never sleep less than the base sleep seconds.
$sleepSeconds = \max(Stripe::getInitialNetworkRetryDelay(), $sleepSeconds);
// And never sleep less than the time the API asks us to wait, assuming it's a reasonable ask.
$retryAfter = isset($rheaders['retry-after']) ? (float) ($rheaders['retry-after']) : 0.0;
if (\floor($retryAfter) === $retryAfter && $retryAfter <= Stripe::getMaxRetryAfter()) {
$sleepSeconds = \max($sleepSeconds, $retryAfter);
}
return $sleepSeconds;
}
/**
* Initializes the curl handle. If already initialized, the handle is closed first.
*/
private function initCurlHandle()
{
$this->closeCurlHandle();
$this->curlHandle = \curl_init();
}
/**
* Closes the curl handle if initialized. Do nothing if already closed.
*/
private function closeCurlHandle()
{
if (null !== $this->curlHandle) {
\curl_close($this->curlHandle);
$this->curlHandle = null;
}
}
/**
* Resets the curl handle. If the handle is not already initialized, or if persistent
* connections are disabled, the handle is reinitialized instead.
*/
private function resetCurlHandle()
{
if (null !== $this->curlHandle && $this->getEnablePersistentConnections()) {
\curl_reset($this->curlHandle);
} else {
$this->initCurlHandle();
}
}
/**
* Indicates whether it is safe to use HTTP/2 or not.
*
* @return bool
*/
private function canSafelyUseHttp2()
{
// Versions of curl older than 7.60.0 don't respect GOAWAY frames
// (cf. https://github.com/curl/curl/issues/2416), which Stripe use.
$curlVersion = \curl_version()['version'];
return \version_compare($curlVersion, '7.60.0') >= 0;
}
/**
* Checks if a list of headers contains a specific header name.
*
* @param string[] $headers
* @param string $name
*
* @return bool
*/
private function hasHeader($headers, $name)
{
foreach ($headers as $header) {
if (0 === \strncasecmp($header, "{$name}: ", \strlen($name) + 2)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,258 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Invoices are statements of amounts owed by a customer, and are either generated
* one-off, or generated periodically from a subscription.
*
* They contain <a href="https://stripe.com/docs/api#invoiceitems">invoice
* items</a>, and proration adjustments that may be caused by subscription
* upgrades/downgrades (if necessary).
*
* If your invoice is configured to be billed through automatic charges, Stripe
* automatically finalizes your invoice and attempts payment. Note that finalizing
* the invoice, <a
* href="https://stripe.com/docs/billing/invoices/workflow/#auto_advance">when
* automatic</a>, does not happen immediately as the invoice is created. Stripe
* waits until one hour after the last webhook was successfully sent (or the last
* webhook timed out after failing). If you (and the platforms you may have
* connected to) have no webhooks configured, Stripe waits one hour after creation
* to finalize the invoice.
*
* If your invoice is configured to be billed by sending an email, then based on
* your <a href="https://dashboard.stripe.com/account/billing/automatic'">email
* settings</a>, Stripe will email the invoice to your customer and await payment.
* These emails can contain a link to a hosted page to pay the invoice.
*
* Stripe applies any customer credit on the account before determining the amount
* due for the invoice (i.e., the amount that will be actually charged). If the
* amount due for the invoice is less than Stripe's <a
* href="/docs/currencies#minimum-and-maximum-charge-amounts">minimum allowed
* charge per currency</a>, the invoice is automatically marked paid, and we add
* the amount due to the customer's running account balance which is applied to the
* next invoice.
*
* More details on the customer's account balance are <a
* href="https://stripe.com/docs/api/customers/object#customer_object-account_balance">here</a>.
*
* Related guide: <a href="https://stripe.com/docs/billing/invoices/sending">Send
* Invoices to Customers</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|string $account_country The country of the business associated with this invoice, most often the business creating the invoice.
* @property null|string $account_name The public name of the business associated with this invoice, most often the business creating the invoice.
* @property int $amount_due Final amount due at this time for this invoice. If the invoice's total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the <code>amount_due</code> may be 0. If there is a positive <code>starting_balance</code> for the invoice (the customer owes money), the <code>amount_due</code> will also take that into account. The charge that gets generated for the invoice will be for the amount specified in <code>amount_due</code>.
* @property int $amount_paid The amount, in %s, that was paid.
* @property int $amount_remaining The amount remaining, in %s, that is due.
* @property null|int $application_fee_amount The fee in %s that will be applied to the invoice and transferred to the application owner's Stripe account when the invoice is paid.
* @property int $attempt_count Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. In other words, manual payment attempts after the first attempt do not affect the retry schedule.
* @property bool $attempted Whether an attempt has been made to pay the invoice. An invoice is not attempted until 1 hour after the <code>invoice.created</code> webhook, for example, so you might not want to display that invoice as unpaid to your users.
* @property bool $auto_advance Controls whether Stripe will perform <a href="https://stripe.com/docs/billing/invoices/workflow/#auto_advance">automatic collection</a> of the invoice. When <code>false</code>, the invoice's state will not automatically advance without an explicit action.
* @property null|string $billing_reason Indicates the reason why the invoice was created. <code>subscription_cycle</code> indicates an invoice created by a subscription advancing into a new period. <code>subscription_create</code> indicates an invoice created due to creating a subscription. <code>subscription_update</code> indicates an invoice created due to updating a subscription. <code>subscription</code> is set for all old invoices to indicate either a change to a subscription or a period advancement. <code>manual</code> is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The <code>upcoming</code> value is reserved for simulated invoices per the upcoming invoice endpoint. <code>subscription_threshold</code> indicates an invoice created due to a billing threshold being reached.
* @property null|string|\Stripe\Charge $charge ID of the latest charge generated for this invoice, if any.
* @property null|string $collection_method Either <code>charge_automatically</code>, or <code>send_invoice</code>. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property null|\Stripe\StripeObject[] $custom_fields Custom fields displayed on the invoice.
* @property string|\Stripe\Customer $customer The ID of the customer who will be billed.
* @property null|\Stripe\StripeObject $customer_address The customer's address. Until the invoice is finalized, this field will equal <code>customer.address</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|string $customer_email The customer's email. Until the invoice is finalized, this field will equal <code>customer.email</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|string $customer_name The customer's name. Until the invoice is finalized, this field will equal <code>customer.name</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|string $customer_phone The customer's phone number. Until the invoice is finalized, this field will equal <code>customer.phone</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|\Stripe\StripeObject $customer_shipping The customer's shipping information. Until the invoice is finalized, this field will equal <code>customer.shipping</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|string $customer_tax_exempt The customer's tax exempt status. Until the invoice is finalized, this field will equal <code>customer.tax_exempt</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|\Stripe\StripeObject[] $customer_tax_ids The customer's tax IDs. Until the invoice is finalized, this field will contain the same tax IDs as <code>customer.tax_ids</code>. Once the invoice is finalized, this field will no longer be updated.
* @property null|string|\Stripe\PaymentMethod $default_payment_method ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings.
* @property null|string|\Stripe\StripeObject $default_source ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source.
* @property null|\Stripe\TaxRate[] $default_tax_rates The tax rates applied to this invoice, if any.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard.
* @property null|\Stripe\Discount $discount Describes the current discount applied to this invoice, if there is one.
* @property null|(string|\Stripe\Discount)[] $discounts The discounts applied to the invoice. Line item discounts are applied before invoice discounts. Use <code>expand[]=discounts</code> to expand each discount.
* @property null|int $due_date The date on which payment for this invoice is due. This value will be <code>null</code> for invoices where <code>collection_method=charge_automatically</code>.
* @property null|int $ending_balance Ending customer balance after the invoice is finalized. Invoices are finalized approximately an hour after successful webhook delivery or when payment collection is attempted for the invoice. If the invoice has not been finalized yet, this will be null.
* @property null|string $footer Footer displayed on the invoice.
* @property null|string $hosted_invoice_url The URL for the hosted invoice page, which allows customers to view and pay an invoice. If the invoice has not been finalized yet, this will be null.
* @property null|string $invoice_pdf The link to download the PDF for the invoice. If the invoice has not been finalized yet, this will be null.
* @property \Stripe\Collection $lines The individual line items that make up the invoice. <code>lines</code> is sorted as follows: invoice items in reverse chronological order, followed by the subscription, if any.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property null|\Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|int $next_payment_attempt The time at which payment will next be attempted. This value will be <code>null</code> for invoices where <code>collection_method=send_invoice</code>.
* @property null|string $number A unique, identifying string that appears on emails sent to the customer for this invoice. This starts with the customer's unique invoice_prefix if it is specified.
* @property bool $paid Whether payment was successfully collected for this invoice. An invoice can be paid (most commonly) with a charge or with credit from the customer's account balance.
* @property null|string|\Stripe\PaymentIntent $payment_intent The PaymentIntent associated with this invoice. The PaymentIntent is generated when the invoice is finalized, and can then be used to pay the invoice. Note that voiding an invoice will cancel the PaymentIntent.
* @property int $period_end End of the usage period during which invoice items were added to this invoice.
* @property int $period_start Start of the usage period during which invoice items were added to this invoice.
* @property int $post_payment_credit_notes_amount Total amount of all post-payment credit notes issued for this invoice.
* @property int $pre_payment_credit_notes_amount Total amount of all pre-payment credit notes issued for this invoice.
* @property null|string $receipt_number This is the transaction number that appears on email receipts sent for this invoice.
* @property int $starting_balance Starting customer balance before the invoice is finalized. If the invoice has not been finalized yet, this will be the current customer balance.
* @property null|string $statement_descriptor Extra information about an invoice for the customer's credit card statement.
* @property null|string $status The status of the invoice, one of <code>draft</code>, <code>open</code>, <code>paid</code>, <code>uncollectible</code>, or <code>void</code>. <a href="https://stripe.com/docs/billing/invoices/workflow#workflow-overview">Learn more</a>
* @property \Stripe\StripeObject $status_transitions
* @property null|string|\Stripe\Subscription $subscription The subscription that this invoice was prepared for, if any.
* @property int $subscription_proration_date Only set for upcoming invoices that preview prorations. The time used to calculate prorations.
* @property int $subtotal Total of all subscriptions, invoice items, and prorations on the invoice before any invoice level discount or tax is applied. Item discounts are already incorporated
* @property null|int $tax The amount of tax on this invoice. This is the sum of all the tax amounts on this invoice.
* @property null|float $tax_percent This percentage of the subtotal has been added to the total amount of the invoice, including invoice line items and discounts. This field is inherited from the subscription's <code>tax_percent</code> field, but can be changed before the invoice is paid. This field defaults to null.
* @property \Stripe\StripeObject $threshold_reason
* @property int $total Total after discounts and taxes.
* @property null|\Stripe\StripeObject[] $total_discount_amounts The aggregate amounts calculated per discount across all line items.
* @property null|\Stripe\StripeObject[] $total_tax_amounts The aggregate amounts calculated per tax rate for all line items.
* @property null|int $webhooks_delivered_at Invoices are automatically paid or sent 1 hour after webhooks are delivered, or until all webhook delivery attempts have <a href="https://stripe.com/docs/billing/webhooks#understand">been exhausted</a>. This field tracks the time when webhooks for this invoice were successfully delivered. If the invoice had no webhooks to deliver, this will be set while the invoice is being created.
*/
class Invoice extends ApiResource
{
const OBJECT_NAME = 'invoice';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\Retrieve;
use ApiOperations\Update;
const BILLING_CHARGE_AUTOMATICALLY = 'charge_automatically';
const BILLING_SEND_INVOICE = 'send_invoice';
const BILLING_REASON_MANUAL = 'manual';
const BILLING_REASON_SUBSCRIPTION = 'subscription';
const BILLING_REASON_SUBSCRIPTION_CREATE = 'subscription_create';
const BILLING_REASON_SUBSCRIPTION_CYCLE = 'subscription_cycle';
const BILLING_REASON_SUBSCRIPTION_THRESHOLD = 'subscription_threshold';
const BILLING_REASON_SUBSCRIPTION_UPDATE = 'subscription_update';
const BILLING_REASON_UPCOMING = 'upcoming';
const COLLECTION_METHOD_CHARGE_AUTOMATICALLY = 'charge_automatically';
const COLLECTION_METHOD_SEND_INVOICE = 'send_invoice';
const STATUS_DELETED = 'deleted';
const STATUS_DRAFT = 'draft';
const STATUS_OPEN = 'open';
const STATUS_PAID = 'paid';
const STATUS_UNCOLLECTIBLE = 'uncollectible';
const STATUS_VOID = 'void';
use ApiOperations\NestedResource;
const PATH_LINES = '/lines';
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Invoice the upcoming invoice
*/
public static function upcoming($params = null, $opts = null)
{
$url = static::classUrl() . '/upcoming';
list($response, $opts) = static::_staticRequest('get', $url, $params, $opts);
$obj = Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
/**
* @param string $id the ID of the invoice on which to retrieve the lines
* @param null|array $params
* @param null|array|string $opts
*
* @throws StripeExceptionApiErrorException if the request fails
*
* @return \Stripe\Collection the list of lines (InvoiceLineItem)
*/
public static function allLines($id, $params = null, $opts = null)
{
return self::_allNestedResources($id, static::PATH_LINES, $params, $opts);
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Invoice the finalized invoice
*/
public function finalizeInvoice($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/finalize';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Invoice the uncollectible invoice
*/
public function markUncollectible($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/mark_uncollectible';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Invoice the paid invoice
*/
public function pay($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/pay';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Invoice the sent invoice
*/
public function sendInvoice($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/send';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Invoice the voided invoice
*/
public function voidInvoice($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/void';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}

View File

@ -0,0 +1,50 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* Sometimes you want to add a charge or credit to a customer, but actually charge
* or credit the customer's card only at the end of a regular billing cycle. This
* is useful for combining several charges (to minimize per-transaction fees), or
* for having Stripe tabulate your usage-based billing totals.
*
* Related guide: <a
* href="https://stripe.com/docs/billing/invoices/subscription#adding-upcoming-invoice-items">Subscription
* Invoices</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount Amount (in the <code>currency</code> specified) of the invoice item. This should always be equal to <code>unit_amount * quantity</code>.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property string|\Stripe\Customer $customer The ID of the customer who will be billed when this invoice item is billed.
* @property int $date Time at which the object was created. Measured in seconds since the Unix epoch.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property bool $discountable If true, discounts will apply to this invoice item. Always false for prorations.
* @property null|(string|\Stripe\Discount)[] $discounts The discounts which apply to the invoice item. Item discounts are applied before invoice discounts. Use <code>expand[]=discounts</code> to expand each discount.
* @property null|string|\Stripe\Invoice $invoice The ID of the invoice this invoice item belongs to.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property \Stripe\StripeObject $period
* @property null|\Stripe\Plan $plan If the invoice item is a proration, the plan of the subscription that the proration was computed for.
* @property null|\Stripe\Price $price The price of the invoice item.
* @property bool $proration Whether the invoice item was created automatically as a proration adjustment when the customer switched plans.
* @property int $quantity Quantity of units for the invoice item. If the invoice item is a proration, the quantity of the subscription that the proration was computed for.
* @property null|string|\Stripe\Subscription $subscription The subscription that this invoice item has been created for, if any.
* @property string $subscription_item The subscription item that this invoice item has been created for, if any.
* @property null|\Stripe\TaxRate[] $tax_rates The tax rates which apply to the invoice item. When set, the <code>default_tax_rates</code> on the invoice do not apply to this invoice item.
* @property bool $unified_proration For prorations this indicates whether Stripe automatically grouped multiple related debit and credit line items into a single combined line item.
* @property null|int $unit_amount Unit Amount (in the <code>currency</code> specified) of the invoice item.
* @property null|string $unit_amount_decimal Same as <code>unit_amount</code>, but contains a decimal value with at most 12 decimal places.
*/
class InvoiceItem extends ApiResource
{
const OBJECT_NAME = 'invoiceitem';
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\Retrieve;
use ApiOperations\Update;
}

View File

@ -0,0 +1,34 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The amount, in %s.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property null|string $description An arbitrary string attached to the object. Often useful for displaying to users.
* @property null|\Stripe\StripeObject[] $discount_amounts The amount of discount calculated per discount for this line item.
* @property bool $discountable If true, discounts will apply to this line item. Always false for prorations.
* @property null|(string|\Stripe\Discount)[] $discounts The discounts applied to the invoice line item. Line item discounts are applied before invoice discounts. Use <code>expand[]=discounts</code> to expand each discount.
* @property string $invoice_item The ID of the <a href="https://stripe.com/docs/api/invoiceitems">invoice item</a> associated with this line item if any.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Note that for line items with <code>type=subscription</code> this will reflect the metadata of the subscription that caused the line item to be created.
* @property \Stripe\StripeObject $period
* @property null|\Stripe\Plan $plan The plan of the subscription, if the line item is a subscription or a proration.
* @property null|\Stripe\Price $price The price of the line item.
* @property bool $proration Whether this is a proration.
* @property null|int $quantity The quantity of the subscription, if the line item is a subscription or a proration.
* @property null|string $subscription The subscription that the invoice item pertains to, if any.
* @property string $subscription_item The subscription item that generated this invoice item. Left empty if the line item is not an explicit result of a subscription.
* @property null|\Stripe\StripeObject[] $tax_amounts The amount of tax calculated per tax rate for this line item
* @property null|\Stripe\TaxRate[] $tax_rates The tax rates which apply to the line item.
* @property string $type A string identifying the type of the source of this line item, either an <code>invoiceitem</code> or a <code>subscription</code>.
* @property bool $unified_proration For prorations this indicates whether Stripe automatically grouped multiple related debit and credit line items into a single combined line item.
*/
class InvoiceLineItem extends ApiResource
{
const OBJECT_NAME = 'line_item';
}

View File

@ -0,0 +1,80 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\Issuing;
/**
* When an <a href="https://stripe.com/docs/issuing">issued card</a> is used to
* make a purchase, an Issuing <code>Authorization</code> object is created. <a
* href="https://stripe.com/docs/issuing/purchases/authorizations">Authorizations</a>
* must be approved for the purchase to be completed successfully.
*
* Related guide: <a
* href="https://stripe.com/docs/issuing/purchases/authorizations">Issued Card
* Authorizations</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The total amount that was authorized or rejected. This amount is in the card's currency and in the <a href="https://stripe.com/docs/currencies#zero-decimal">smallest currency unit</a>.
* @property bool $approved Whether the authorization has been approved.
* @property string $authorization_method How the card details were provided.
* @property \Stripe\BalanceTransaction[] $balance_transactions List of balance transactions associated with this authorization.
* @property \Stripe\Issuing\Card $card You can <a href="https://stripe.com/docs/issuing/cards">create physical or virtual cards</a> that are issued to cardholders.
* @property null|string|\Stripe\Issuing\Cardholder $cardholder The cardholder to whom this authorization belongs.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property int $merchant_amount The total amount that was authorized or rejected. This amount is in the <code>merchant_currency</code> and in the <a href="https://stripe.com/docs/currencies#zero-decimal">smallest currency unit</a>.
* @property string $merchant_currency The currency that was presented to the cardholder for the authorization. Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property \Stripe\StripeObject $merchant_data
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|\Stripe\StripeObject $pending_request The pending authorization request. This field will only be non-null during an <code>issuing_authorization.request</code> webhook.
* @property \Stripe\StripeObject[] $request_history History of every time the authorization was approved/denied (whether approved/denied by you directly or by Stripe based on your <code>spending_controls</code>). If the merchant changes the authorization by performing an <a href="https://stripe.com/docs/issuing/purchases/authorizations">incremental authorization or partial capture</a>, you can look at this field to see the previous states of the authorization.
* @property string $status The current status of the authorization in its lifecycle.
* @property \Stripe\Issuing\Transaction[] $transactions List of <a href="https://stripe.com/docs/api/issuing/transactions">transactions</a> associated with this authorization.
* @property \Stripe\StripeObject $verification_data
* @property null|string $wallet What, if any, digital wallet was used for this authorization. One of <code>apple_pay</code>, <code>google_pay</code>, or <code>samsung_pay</code>.
*/
class Authorization extends \Stripe\ApiResource
{
const OBJECT_NAME = 'issuing.authorization';
use \Stripe\ApiOperations\All;
use \Stripe\ApiOperations\Retrieve;
use \Stripe\ApiOperations\Update;
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Authorization the approved authorization
*/
public function approve($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/approve';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return Authorization the declined authorization
*/
public function decline($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/decline';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}

View File

@ -0,0 +1,59 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\Issuing;
/**
* You can <a href="https://stripe.com/docs/issuing/cards">create physical or
* virtual cards</a> that are issued to cardholders.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property string $brand The brand of the card.
* @property null|string $cancellation_reason The reason why the card was canceled.
* @property \Stripe\Issuing\Cardholder $cardholder <p>An Issuing <code>Cardholder</code> object represents an individual or business entity who is <a href="https://stripe.com/docs/issuing">issued</a> cards.</p><p>Related guide: <a href="https://stripe.com/docs/issuing/cards#create-cardholder">How to create a Cardholder</a></p>
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property string $cvc The card's CVC. For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with <a href="https://stripe.com/docs/api/expanding_objects">the <code>expand</code> parameter</a>. Additionally, it's only available via the <a href="https://stripe.com/docs/api/issuing/cards/retrieve">&quot;Retrieve a card&quot; endpoint</a>, not via &quot;List all cards&quot; or any other endpoint.
* @property int $exp_month The expiration month of the card.
* @property int $exp_year The expiration year of the card.
* @property string $last4 The last 4 digits of the card number.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property string $number The full unredacted card number. For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with <a href="https://stripe.com/docs/api/expanding_objects">the <code>expand</code> parameter</a>. Additionally, it's only available via the <a href="https://stripe.com/docs/api/issuing/cards/retrieve">&quot;Retrieve a card&quot; endpoint</a>, not via &quot;List all cards&quot; or any other endpoint.
* @property null|string|\Stripe\Issuing\Card $replaced_by The latest card that replaces this card, if any.
* @property null|string|\Stripe\Issuing\Card $replacement_for The card this card replaces, if any.
* @property null|string $replacement_reason The reason why the previous card needed to be replaced.
* @property null|\Stripe\StripeObject $shipping Where and how the card will be shipped.
* @property \Stripe\StripeObject $spending_controls
* @property string $status Whether authorizations can be approved on this card.
* @property string $type The type of the card.
*/
class Card extends \Stripe\ApiResource
{
const OBJECT_NAME = 'issuing.card';
use \Stripe\ApiOperations\All;
use \Stripe\ApiOperations\Create;
use \Stripe\ApiOperations\Retrieve;
use \Stripe\ApiOperations\Update;
/**
* @param null|array $params
* @param null|array|string $opts
*
* @throws \Stripe\Exception\ApiErrorException if the request fails
*
* @return \Stripe\Issuing\CardDetails the card details associated with that issuing card
*/
public function details($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/details';
list($response, $opts) = $this->_request('get', $url, $params, $opts);
$obj = \Stripe\Util\Util::convertToStripeObject($response, $opts);
$obj->setLastResponse($response);
return $obj;
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Stripe\Issuing;
/**
* Class CardDetails.
*
* @property string $id
* @property string $object
* @property Card $card
* @property string $cvc
* @property int $exp_month
* @property int $exp_year
* @property string $number
*/
class CardDetails extends \Stripe\ApiResource
{
const OBJECT_NAME = 'issuing.card_details';
}

View File

@ -0,0 +1,39 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\Issuing;
/**
* An Issuing <code>Cardholder</code> object represents an individual or business
* entity who is <a href="https://stripe.com/docs/issuing">issued</a> cards.
*
* Related guide: <a
* href="https://stripe.com/docs/issuing/cards#create-cardholder">How to create a
* Cardholder</a>
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property \Stripe\StripeObject $billing
* @property null|\Stripe\StripeObject $company Additional information about a <code>company</code> cardholder.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property null|string $email The cardholder's email address.
* @property null|\Stripe\StripeObject $individual Additional information about an <code>individual</code> cardholder.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property string $name The cardholder's name. This will be printed on cards issued to them.
* @property null|string $phone_number The cardholder's phone number.
* @property \Stripe\StripeObject $requirements
* @property null|\Stripe\StripeObject $spending_controls Rules that control spending across this cardholder's cards. Refer to our <a href="https://stripe.com/docs/issuing/controls/spending-controls">documentation</a> for more details.
* @property string $status Specifies whether to permit authorizations on this cardholder's cards.
* @property string $type One of <code>individual</code> or <code>company</code>.
*/
class Cardholder extends \Stripe\ApiResource
{
const OBJECT_NAME = 'issuing.cardholder';
use \Stripe\ApiOperations\All;
use \Stripe\ApiOperations\Create;
use \Stripe\ApiOperations\Retrieve;
use \Stripe\ApiOperations\Update;
}

View File

@ -0,0 +1,31 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\Issuing;
/**
* As a <a href="https://stripe.com/docs/issuing">card issuer</a>, you can <a
* href="https://stripe.com/docs/issuing/purchases/disputes">dispute</a>
* transactions that you do not recognize, suspect to be fraudulent, or have some
* other issue.
*
* Related guide: <a
* href="https://stripe.com/docs/issuing/purchases/disputes">Disputing
* Transactions</a>
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|\Stripe\BalanceTransaction[] $balance_transactions List of balance transactions associated with this dispute.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property string|\Stripe\Issuing\Transaction $transaction The transaction being disputed.
*/
class Dispute extends \Stripe\ApiResource
{
const OBJECT_NAME = 'issuing.dispute';
use \Stripe\ApiOperations\All;
use \Stripe\ApiOperations\Create;
use \Stripe\ApiOperations\Retrieve;
use \Stripe\ApiOperations\Update;
}

View File

@ -0,0 +1,41 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe\Issuing;
/**
* Any use of an <a href="https://stripe.com/docs/issuing">issued card</a> that
* results in funds entering or leaving your Stripe account, such as a completed
* purchase or refund, is represented by an Issuing <code>Transaction</code>
* object.
*
* Related guide: <a
* href="https://stripe.com/docs/issuing/purchases/transactions">Issued Card
* Transactions</a>.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $amount The transaction amount, which will be reflected in your balance. This amount is in your currency and in the <a href="https://stripe.com/docs/currencies#zero-decimal">smallest currency unit</a>.
* @property null|string|\Stripe\Issuing\Authorization $authorization The <code>Authorization</code> object that led to this transaction.
* @property null|string|\Stripe\BalanceTransaction $balance_transaction ID of the <a href="https://stripe.com/docs/api/balance_transactions">balance transaction</a> associated with this transaction.
* @property string|\Stripe\Issuing\Card $card The card used to make this transaction.
* @property null|string|\Stripe\Issuing\Cardholder $cardholder The cardholder to whom this transaction belongs.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property int $merchant_amount The amount that the merchant will receive, denominated in <code>merchant_currency</code> and in the <a href="https://stripe.com/docs/currencies#zero-decimal">smallest currency unit</a>. It will be different from <code>amount</code> if the merchant is taking payment in a different currency.
* @property string $merchant_currency The currency with which the merchant is taking payment.
* @property \Stripe\StripeObject $merchant_data
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|\Stripe\StripeObject $purchase_details Additional purchase information that is optionally provided by the merchant.
* @property string $type The nature of the transaction.
*/
class Transaction extends \Stripe\ApiResource
{
const OBJECT_NAME = 'issuing.transaction';
use \Stripe\ApiOperations\All;
use \Stripe\ApiOperations\Retrieve;
use \Stripe\ApiOperations\Update;
}

View File

@ -0,0 +1,26 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* A line item.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property null|int $amount_subtotal Total before any discounts or taxes is applied.
* @property null|int $amount_total Total after discounts and taxes.
* @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
* @property string $description An arbitrary string attached to the object. Often useful for displaying to users. Defaults to product name.
* @property \Stripe\StripeObject[] $discounts The discounts applied to the line item.
* @property \Stripe\Price $price <p>Prices define the unit cost, currency, and (optional) billing cycle for both recurring and one-time purchases of products. <a href="https://stripe.com/docs/api#products">Products</a> help you track inventory or provisioning, and prices help you track payment terms. Different physical goods or levels of service should be represented by products, and pricing options should be represented by prices. This approach lets you change prices without having to change your provisioning scheme.</p><p>For example, you might have a single &quot;gold&quot; product that has prices for $10/month, $100/year, and €9 once.</p><p>Related guides: <a href="https://stripe.com/docs/billing/subscriptions/set-up-subscription">Set up a subscription</a>, <a href="https://stripe.com/docs/billing/invoices/create">create an invoice</a>, and more about <a href="https://stripe.com/docs/billing/prices-guide">products and prices</a>.</p>
* @property null|int $quantity The quantity of products being purchased.
* @property \Stripe\StripeObject[] $taxes The taxes applied to the line item.
*/
class LineItem extends ApiResource
{
const OBJECT_NAME = 'item';
use ApiOperations\All;
}

View File

@ -0,0 +1,15 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
* @property string $url The URL for the login link.
*/
class LoginLink extends ApiResource
{
const OBJECT_NAME = 'login_link';
}

View File

@ -0,0 +1,27 @@
<?php
// File generated from our OpenAPI spec
namespace Stripe;
/**
* A Mandate is a record of the permission a customer has given you to debit their
* payment method.
*
* @property string $id Unique identifier for the object.
* @property string $object String representing the object's type. Objects of the same type share the same value.
* @property \Stripe\StripeObject $customer_acceptance
* @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
* @property \Stripe\StripeObject $multi_use
* @property string|\Stripe\PaymentMethod $payment_method ID of the payment method associated with this mandate.
* @property \Stripe\StripeObject $payment_method_details
* @property \Stripe\StripeObject $single_use
* @property string $status The status of the mandate, which indicates whether it can be used to initiate a payment.
* @property string $type The type of the mandate.
*/
class Mandate extends ApiResource
{
const OBJECT_NAME = 'mandate';
use ApiOperations\Retrieve;
}

Some files were not shown because too many files have changed in this diff Show More