diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index 5d88f3e26ea..db5740d277b 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -150,7 +150,7 @@ function showOnlinePaymentUrl($type, $ref) * @param string $localorexternal 0=Url for browser, 1=Url for external access * @return string Url string */ -function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_free_tag', $localorexternal = 0) +function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_tag', $localorexternal = 0) { global $conf, $dolibarr_main_url_root; diff --git a/htdocs/includes/stripe/.coveralls.yml b/htdocs/includes/stripe/.coveralls.yml deleted file mode 100644 index a343c9a7466..00000000000 --- a/htdocs/includes/stripe/.coveralls.yml +++ /dev/null @@ -1,4 +0,0 @@ -service_name: travis-ci -src_dir: . -coverage_clover: clover.xml -json_path: coveralls-upload.json diff --git a/htdocs/includes/stripe/.travis.yml b/htdocs/includes/stripe/.travis.yml deleted file mode 100644 index d575ed51a7d..00000000000 --- a/htdocs/includes/stripe/.travis.yml +++ /dev/null @@ -1,40 +0,0 @@ -sudo: false - -language: php - -php: - - 5.4 - - 5.5 - - 5.6 - - 7.0 - - 7.1 - - 7.2 - - hhvm - -env: - global: - - STRIPE_MOCK_VERSION=0.8.0 - matrix: - - AUTOLOAD=1 - - AUTOLOAD=0 - -cache: - directories: - - $HOME/.composer/cache/files - - stripe-mock - -before_install: - # Unpack and start stripe-mock so that the test suite can talk to it - - | - if [ ! -d "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}" ]; then - mkdir -p stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}/ - curl -L "https://github.com/stripe/stripe-mock/releases/download/v${STRIPE_MOCK_VERSION}/stripe-mock_${STRIPE_MOCK_VERSION}_linux_amd64.tar.gz" -o "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}_linux_amd64.tar.gz" - tar -zxf "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}_linux_amd64.tar.gz" -C "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}/" - fi - - | - stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}/stripe-mock > /dev/null & - STRIPE_MOCK_PID=$! - -script: ./build.php ${AUTOLOAD} - -after_script: ./vendor/bin/coveralls -v diff --git a/htdocs/includes/stripe/CHANGELOG.md b/htdocs/includes/stripe/CHANGELOG.md index 3f0fdfce153..727ac3d1b43 100644 --- a/htdocs/includes/stripe/CHANGELOG.md +++ b/htdocs/includes/stripe/CHANGELOG.md @@ -1,5 +1,221 @@ # Changelog +## 6.34.3 - 2019-05-01 +* [#644](https://github.com/stripe/stripe-php/pull/644) Update return type to `static` to improve static analysis +* [#645](https://github.com/stripe/stripe-php/pull/645) Fix constant for `payment_intent.payment_failed` + +## 6.34.2 - 2019-04-26 +* [#642](https://github.com/stripe/stripe-php/pull/642) Fix an issue where existing idempotency keys would be overwritten when using automatic retries + +## 6.34.1 - 2019-04-25 +* [#640](https://github.com/stripe/stripe-php/pull/640) Add missing phpdocs + +## 6.34.0 - 2019-04-24 +* [#626](https://github.com/stripe/stripe-php/pull/626) Add support for the `TaxRate` resource and APIs +* [#639](https://github.com/stripe/stripe-php/pull/639) Fix multiple phpdoc issues + +## 6.33.0 - 2019-04-22 +* [#630](https://github.com/stripe/stripe-php/pull/630) Add support for the `TaxId` resource and APIs + +## 6.32.1 - 2019-04-19 +* [#636](https://github.com/stripe/stripe-php/pull/636) Correct type of `$personId` in PHPDoc + +## 6.32.0 - 2019-04-18 +* [#621](https://github.com/stripe/stripe-php/pull/621) Add support for `CreditNote` + +## 6.31.5 - 2019-04-12 +* [#628](https://github.com/stripe/stripe-php/pull/628) Add constants for `person.*` event types +* [#628](https://github.com/stripe/stripe-php/pull/628) Add missing constants for `Account` and `Person` + +## 6.31.4 - 2019-04-05 +* [#624](https://github.com/stripe/stripe-php/pull/624) Fix encoding of nested parameters in multipart requests + +## 6.31.3 - 2019-04-02 +* [#623](https://github.com/stripe/stripe-php/pull/623) Only use HTTP/2 with curl >= 7.60.0 + +## 6.31.2 - 2019-03-25 +* [#619](https://github.com/stripe/stripe-php/pull/619) Fix PHPDoc return types for list methods for nested resources + +## 6.31.1 - 2019-03-22 +* [#612](https://github.com/stripe/stripe-php/pull/612) Add a lot of constants +* [#614](https://github.com/stripe/stripe-php/pull/614) Add missing subscription status constants + +## 6.31.0 - 2019-03-18 +* [#600](https://github.com/stripe/stripe-php/pull/600) Add support for the `PaymentMethod` resource and APIs +* [#606](https://github.com/stripe/stripe-php/pull/606) Add support for retrieving a Checkout `Session` +* [#611](https://github.com/stripe/stripe-php/pull/611) Add support for deleting a Terminal `Location` and `Reader` + +## 6.30.5 - 2019-03-11 +* [#607](https://github.com/stripe/stripe-php/pull/607) Correctly handle case where a metadata key is called `metadata` + +## 6.30.4 - 2019-02-27 +* [#602](https://github.com/stripe/stripe-php/pull/602) Add `subscription_schedule` to `Subscription` for PHPDoc. + +## 6.30.3 - 2019-02-26 +* [#603](https://github.com/stripe/stripe-php/pull/603) Improve PHPDoc on the `Source` object to cover all types of Sources currently supported. + +## 6.30.2 - 2019-02-25 +* [#601](https://github.com/stripe/stripe-php/pull/601) Fix PHPDoc across multiple resources and add support for new events. + +## 6.30.1 - 2019-02-16 +* [#599](https://github.com/stripe/stripe-php/pull/599) Fix PHPDoc for `SubscriptionSchedule` and `SubscriptionScheduleRevision` + +## 6.30.0 - 2019-02-12 +* [#590](https://github.com/stripe/stripe-php/pull/590) Add support for `SubscriptionSchedule` and `SubscriptionScheduleRevision` + +## 6.29.3 - 2019-01-31 +* [#592](https://github.com/stripe/stripe-php/pull/592) Some more PHPDoc fixes + +## 6.29.2 - 2019-01-31 +* [#591](https://github.com/stripe/stripe-php/pull/591) Fix PHPDoc for nested resources + +## 6.29.1 - 2019-01-25 +* [#566](https://github.com/stripe/stripe-php/pull/566) Fix dangling message contents +* [#586](https://github.com/stripe/stripe-php/pull/586) Don't overwrite `CURLOPT_HTTP_VERSION` option + +## 6.29.0 - 2019-01-23 +* [#579](https://github.com/stripe/stripe-php/pull/579) Rename `CheckoutSession` to `Session` and move it under the `Checkout` namespace. This is a breaking change, but we've reached out to affected merchants and all new merchants would use the new approach. + +## 6.28.1 - 2019-01-21 +* [#580](https://github.com/stripe/stripe-php/pull/580) Properly serialize `individual` on `Account` objects + +## 6.28.0 - 2019-01-03 +* [#576](https://github.com/stripe/stripe-php/pull/576) Add support for iterating directly over `Collection` instances + +## 6.27.0 - 2018-12-21 +* [#571](https://github.com/stripe/stripe-php/pull/571) Add support for the `CheckoutSession` resource + +## 6.26.0 - 2018-12-11 +* [#568](https://github.com/stripe/stripe-php/pull/568) Enable persistent connections + +## 6.25.0 - 2018-12-10 +* [#567](https://github.com/stripe/stripe-php/pull/567) Add support for account links + +## 6.24.0 - 2018-11-28 +* [#562](https://github.com/stripe/stripe-php/pull/562) Add support for the Review resource +* [#564](https://github.com/stripe/stripe-php/pull/564) Add event name constants for subscription schedule aborted/expiring + +## 6.23.0 - 2018-11-27 +* [#542](https://github.com/stripe/stripe-php/pull/542) Add support for `ValueList` and `ValueListItem` for Radar + +## 6.22.1 - 2018-11-20 +* [#561](https://github.com/stripe/stripe-php/pull/561) Add cast and some docs to telemetry introduced in 6.22.0/#549 + +## 6.22.0 - 2018-11-15 +* [#549](https://github.com/stripe/stripe-php/pull/549) Add support for client telemetry + +## 6.21.1 - 2018-11-12 +* [#548](https://github.com/stripe/stripe-php/pull/548) Don't mutate `Exception` class properties from `OAuthBase` error + +## 6.21.0 - 2018-11-08 +* [#537](https://github.com/stripe/stripe-php/pull/537) Add new API endpoints for the `Invoice` resource. + +## 6.20.1 - 2018-11-07 +* [#546](https://github.com/stripe/stripe-php/pull/546) Drop files from the Composer package that aren't needed in the release + +## 6.20.0 - 2018-10-30 +* [#536](https://github.com/stripe/stripe-php/pull/536) Add support for the `Person` resource +* [#541](https://github.com/stripe/stripe-php/pull/541) Add support for the `WebhookEndpoint` resource + +## 6.19.5 - 2018-10-17 +* [#539](https://github.com/stripe/stripe-php/pull/539) Fix methods on `\Stripe\PaymentIntent` to properly pass arguments to the API. + +## 6.19.4 - 2018-10-11 +* [#534](https://github.com/stripe/stripe-php/pull/534) Fix PSR-4 autoloading for `\Stripe\FileUpload` class alias + +## 6.19.3 - 2018-10-09 +* [#530](https://github.com/stripe/stripe-php/pull/530) Add constants for `flow` (`FLOW_*`), `status` (`STATUS_*`) and `usage` (`USAGE_*`) on `\Stripe\Source` + +## 6.19.2 - 2018-10-08 +* [#531](https://github.com/stripe/stripe-php/pull/531) Store HTTP response headers in case-insensitive array + +## 6.19.1 - 2018-09-25 +* [#526](https://github.com/stripe/stripe-php/pull/526) Ignore null values in request parameters + +## 6.19.0 - 2018-09-24 +* [#523](https://github.com/stripe/stripe-php/pull/523) Add support for Stripe Terminal + +## 6.18.0 - 2018-09-24 +* [#520](https://github.com/stripe/stripe-php/pull/520) Rename `\Stripe\FileUpload` to `\Stripe\File` + +## 6.17.2 - 2018-09-18 +* [#522](https://github.com/stripe/stripe-php/pull/522) Fix warning when adding a new additional owner to an existing array + +## 6.17.1 - 2018-09-14 +* [#517](https://github.com/stripe/stripe-php/pull/517) Integer-index encode all sequential arrays + +## 6.17.0 - 2018-09-05 +* [#514](https://github.com/stripe/stripe-php/pull/514) Add support for reporting resources + +## 6.16.0 - 2018-08-23 +* [#509](https://github.com/stripe/stripe-php/pull/509) Add support for usage record summaries + +## 6.15.0 - 2018-08-03 +* [#504](https://github.com/stripe/stripe-php/pull/504) Add cancel support for topups + +## 6.14.0 - 2018-08-02 +* [#505](https://github.com/stripe/stripe-php/pull/505) Add support for file links + +## 6.13.0 - 2018-07-31 +* [#502](https://github.com/stripe/stripe-php/pull/502) Add `isDeleted()` method to `\Stripe\StripeObject` + +## 6.12.0 - 2018-07-28 +* [#501](https://github.com/stripe/stripe-php/pull/501) Add support for scheduled query runs (`\Stripe\Sigma\ScheduledQueryRun`) for Sigma + +## 6.11.0 - 2018-07-26 +* [#500](https://github.com/stripe/stripe-php/pull/500) Add support for Stripe Issuing + +## 6.10.4 - 2018-07-19 +* [#498](https://github.com/stripe/stripe-php/pull/498) Internal improvements to the `\Stripe\ApiResource.classUrl()` method + +## 6.10.3 - 2018-07-16 +* [#497](https://github.com/stripe/stripe-php/pull/497) Use HTTP/2 only for HTTPS requests + +## 6.10.2 - 2018-07-11 +* [#494](https://github.com/stripe/stripe-php/pull/494) Enable HTTP/2 support + +## 6.10.1 - 2018-07-10 +* [#493](https://github.com/stripe/stripe-php/pull/493) Add PHPDoc for `auto_advance` on `\Stripe\Invoice` + +## 6.10.0 - 2018-06-28 +* [#488](https://github.com/stripe/stripe-php/pull/488) Add support for `$appPartnerId` to `Stripe::setAppInfo()` + +## 6.9.0 - 2018-06-28 +* [#487](https://github.com/stripe/stripe-php/pull/487) Add support for payment intents + +## 6.8.2 - 2018-06-24 +* [#486](https://github.com/stripe/stripe-php/pull/486) Make `Account.deauthorize()` return the `StripeObject` from the API + +## 6.8.1 - 2018-06-13 +* [#472](https://github.com/stripe/stripe-php/pull/472) Added phpDoc for `ApiRequestor` and others, especially regarding thrown errors + +## 6.8.0 - 2018-06-13 +* [#481](https://github.com/stripe/stripe-php/pull/481) Add new `\Stripe\Discount` and `\Stripe\OrderItem` classes, add more PHPDoc describing object attributes + +## 6.7.4 - 2018-05-29 +* [#480](https://github.com/stripe/stripe-php/pull/480) PHPDoc changes for API version 2018-05-21 and the addition of the new `CHARGE_EXPIRED` event type + +## 6.7.3 - 2018-05-28 +* [#479](https://github.com/stripe/stripe-php/pull/479) Fix unnecessary traits on `\Stripe\InvoiceLineItem` + +## 6.7.2 - 2018-05-28 +* [#471](https://github.com/stripe/stripe-php/pull/471) Add `OBJECT_NAME` constant to all API resource classes, add `\Stripe\InvoiceLineItem` class + +## 6.7.1 - 2018-05-13 +* [#468](https://github.com/stripe/stripe-php/pull/468) Update fields in PHP docs for accuracy + +## 6.7.0 - 2018-05-09 +* [#466](https://github.com/stripe/stripe-php/pull/466) Add support for issuer fraud records + +## 6.6.0 - 2018-04-11 +* [#460](https://github.com/stripe/stripe-php/pull/460) Add support for flexible billing primitives + +## 6.5.0 - 2018-04-05 +* [#461](https://github.com/stripe/stripe-php/pull/461) Don't zero keys on non-`metadata` subobjects + +## 6.4.2 - 2018-03-17 +* [#458](https://github.com/stripe/stripe-php/pull/458) Add PHPDoc for `account` on `\Stripe\Event` + ## 6.4.1 - 2018-03-02 * [#455](https://github.com/stripe/stripe-php/pull/455) Fix namespaces in PHPDoc * [#456](https://github.com/stripe/stripe-php/pull/456) Fix namespaces for some exceptions diff --git a/htdocs/includes/stripe/LICENSE b/htdocs/includes/stripe/LICENSE index a21757e4fcd..847c705ad35 100644 --- a/htdocs/includes/stripe/LICENSE +++ b/htdocs/includes/stripe/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2010-2015 Stripe +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 diff --git a/htdocs/includes/stripe/README.md b/htdocs/includes/stripe/README.md index fa492c45cc4..8dca764d7d1 100644 --- a/htdocs/includes/stripe/README.md +++ b/htdocs/includes/stripe/README.md @@ -62,7 +62,7 @@ Please see https://stripe.com/docs/api for up-to-date documentation. ### PHP 5.3 -If you are using PHP 5.3, you can download v5.8.0 ([zip](https://github.com/stripe/stripe-php/archive/v5.8.0.zip), [tar.gz](https://github.com/stripe/stripe-php/archive/v5.8.0.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. +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. ### PHP 5.2 @@ -181,9 +181,15 @@ retries are safe. ## Development +Get [Composer][composer]. For example, on Mac OS: + +```bash +brew install composer +``` + Install dependencies: -``` bash +```bash composer install ``` @@ -191,8 +197,10 @@ 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): - go get -u github.com/stripe/stripe-mock - stripe-mock +```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: @@ -226,6 +234,7 @@ The method should be called once, before any request is sent to the API. The sec 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 [psr3]: http://www.php-fig.org/psr/psr-3/ diff --git a/htdocs/includes/stripe/VERSION b/htdocs/includes/stripe/VERSION index 4c77920fd2c..a547a9b46f8 100644 --- a/htdocs/includes/stripe/VERSION +++ b/htdocs/includes/stripe/VERSION @@ -1 +1 @@ -6.4.1 +6.34.3 diff --git a/htdocs/includes/stripe/build.php b/htdocs/includes/stripe/build.php index cd053e2baea..6ce0ca38d11 100644 --- a/htdocs/includes/stripe/build.php +++ b/htdocs/includes/stripe/build.php @@ -13,7 +13,7 @@ if (!$autoload) { file_put_contents('composer.json', json_encode($composer, JSON_PRETTY_PRINT)); } -passthru('composer install', $returnStatus); +passthru('composer update', $returnStatus); if ($returnStatus !== 0) { exit(1); } diff --git a/htdocs/includes/stripe/composer.json b/htdocs/includes/stripe/composer.json index 67473fca421..eb92b76fb31 100644 --- a/htdocs/includes/stripe/composer.json +++ b/htdocs/includes/stripe/composer.json @@ -22,8 +22,9 @@ }, "require-dev": { "phpunit/phpunit": "~4.0", - "satooshi/php-coveralls": "~0.6.1", - "squizlabs/php_codesniffer": "~2.0" + "php-coveralls/php-coveralls": "1.*", + "squizlabs/php_codesniffer": "~2.0", + "symfony/process": "~2.8" }, "autoload": { "psr-4": { "Stripe\\" : "lib/" } diff --git a/htdocs/includes/stripe/init.php b/htdocs/includes/stripe/init.php index 79cf657a7eb..5ccf3327c0b 100644 --- a/htdocs/includes/stripe/init.php +++ b/htdocs/includes/stripe/init.php @@ -5,6 +5,7 @@ require(dirname(__FILE__) . '/lib/Stripe.php'); // Utilities require(dirname(__FILE__) . '/lib/Util/AutoPagingIterator.php'); +require(dirname(__FILE__) . '/lib/Util/CaseInsensitiveArray.php'); require(dirname(__FILE__) . '/lib/Util/LoggerInterface.php'); require(dirname(__FILE__) . '/lib/Util/DefaultLogger.php'); require(dirname(__FILE__) . '/lib/Util/RandomGenerator.php'); @@ -48,6 +49,7 @@ require(dirname(__FILE__) . '/lib/ApiOperations/Update.php'); // Plumbing require(dirname(__FILE__) . '/lib/ApiResponse.php'); +require(dirname(__FILE__) . '/lib/RequestTelemetry.php'); require(dirname(__FILE__) . '/lib/StripeObject.php'); require(dirname(__FILE__) . '/lib/ApiRequestor.php'); require(dirname(__FILE__) . '/lib/ApiResource.php'); @@ -55,6 +57,7 @@ require(dirname(__FILE__) . '/lib/SingletonApiResource.php'); // Stripe API Resources require(dirname(__FILE__) . '/lib/Account.php'); +require(dirname(__FILE__) . '/lib/AccountLink.php'); require(dirname(__FILE__) . '/lib/AlipayAccount.php'); require(dirname(__FILE__) . '/lib/ApplePayDomain.php'); require(dirname(__FILE__) . '/lib/ApplicationFee.php'); @@ -66,40 +69,73 @@ require(dirname(__FILE__) . '/lib/BitcoinReceiver.php'); require(dirname(__FILE__) . '/lib/BitcoinTransaction.php'); require(dirname(__FILE__) . '/lib/Card.php'); require(dirname(__FILE__) . '/lib/Charge.php'); +require(dirname(__FILE__) . '/lib/Checkout/Session.php'); require(dirname(__FILE__) . '/lib/Collection.php'); require(dirname(__FILE__) . '/lib/CountrySpec.php'); require(dirname(__FILE__) . '/lib/Coupon.php'); +require(dirname(__FILE__) . '/lib/CreditNote.php'); require(dirname(__FILE__) . '/lib/Customer.php'); +require(dirname(__FILE__) . '/lib/Discount.php'); require(dirname(__FILE__) . '/lib/Dispute.php'); require(dirname(__FILE__) . '/lib/EphemeralKey.php'); require(dirname(__FILE__) . '/lib/Event.php'); require(dirname(__FILE__) . '/lib/ExchangeRate.php'); +require(dirname(__FILE__) . '/lib/File.php'); +require(dirname(__FILE__) . '/lib/FileLink.php'); require(dirname(__FILE__) . '/lib/FileUpload.php'); require(dirname(__FILE__) . '/lib/Invoice.php'); require(dirname(__FILE__) . '/lib/InvoiceItem.php'); +require(dirname(__FILE__) . '/lib/InvoiceLineItem.php'); +require(dirname(__FILE__) . '/lib/IssuerFraudRecord.php'); +require(dirname(__FILE__) . '/lib/Issuing/Authorization.php'); +require(dirname(__FILE__) . '/lib/Issuing/Card.php'); +require(dirname(__FILE__) . '/lib/Issuing/CardDetails.php'); +require(dirname(__FILE__) . '/lib/Issuing/Cardholder.php'); +require(dirname(__FILE__) . '/lib/Issuing/Dispute.php'); +require(dirname(__FILE__) . '/lib/Issuing/Transaction.php'); require(dirname(__FILE__) . '/lib/LoginLink.php'); require(dirname(__FILE__) . '/lib/Order.php'); +require(dirname(__FILE__) . '/lib/OrderItem.php'); require(dirname(__FILE__) . '/lib/OrderReturn.php'); +require(dirname(__FILE__) . '/lib/PaymentIntent.php'); +require(dirname(__FILE__) . '/lib/PaymentMethod.php'); require(dirname(__FILE__) . '/lib/Payout.php'); +require(dirname(__FILE__) . '/lib/Person.php'); require(dirname(__FILE__) . '/lib/Plan.php'); require(dirname(__FILE__) . '/lib/Product.php'); +require(dirname(__FILE__) . '/lib/Radar/ValueList.php'); +require(dirname(__FILE__) . '/lib/Radar/ValueListItem.php'); require(dirname(__FILE__) . '/lib/Recipient.php'); require(dirname(__FILE__) . '/lib/RecipientTransfer.php'); require(dirname(__FILE__) . '/lib/Refund.php'); +require(dirname(__FILE__) . '/lib/Reporting/ReportRun.php'); +require(dirname(__FILE__) . '/lib/Reporting/ReportType.php'); +require(dirname(__FILE__) . '/lib/Review.php'); require(dirname(__FILE__) . '/lib/SKU.php'); +require(dirname(__FILE__) . '/lib/Sigma/ScheduledQueryRun.php'); require(dirname(__FILE__) . '/lib/Source.php'); require(dirname(__FILE__) . '/lib/SourceTransaction.php'); require(dirname(__FILE__) . '/lib/Subscription.php'); require(dirname(__FILE__) . '/lib/SubscriptionItem.php'); +require(dirname(__FILE__) . '/lib/SubscriptionSchedule.php'); +require(dirname(__FILE__) . '/lib/SubscriptionScheduleRevision.php'); +require(dirname(__FILE__) . '/lib/TaxId.php'); +require(dirname(__FILE__) . '/lib/TaxRate.php'); +require(dirname(__FILE__) . '/lib/Terminal/ConnectionToken.php'); +require(dirname(__FILE__) . '/lib/Terminal/Location.php'); +require(dirname(__FILE__) . '/lib/Terminal/Reader.php'); require(dirname(__FILE__) . '/lib/ThreeDSecure.php'); require(dirname(__FILE__) . '/lib/Token.php'); require(dirname(__FILE__) . '/lib/Topup.php'); require(dirname(__FILE__) . '/lib/Transfer.php'); require(dirname(__FILE__) . '/lib/TransferReversal.php'); +require(dirname(__FILE__) . '/lib/UsageRecord.php'); +require(dirname(__FILE__) . '/lib/UsageRecordSummary.php'); // OAuth require(dirname(__FILE__) . '/lib/OAuth.php'); // Webhooks require(dirname(__FILE__) . '/lib/Webhook.php'); +require(dirname(__FILE__) . '/lib/WebhookEndpoint.php'); require(dirname(__FILE__) . '/lib/WebhookSignature.php'); diff --git a/htdocs/includes/stripe/lib/Account.php b/htdocs/includes/stripe/lib/Account.php index d77d60dedbc..1c10fa2f3a1 100644 --- a/htdocs/includes/stripe/lib/Account.php +++ b/htdocs/includes/stripe/lib/Account.php @@ -7,37 +7,32 @@ namespace Stripe; * * @property string $id * @property string $object - * @property string $business_logo - * @property string $business_name - * @property string $business_primary_color - * @property string $business_url + * @property mixed $business_profile + * @property string $business_type + * @property mixed $capabilities * @property bool $charges_enabled + * @property mixed $company * @property string $country * @property int $created - * @property bool $debit_negative_balances - * @property mixed $decline_charge_on * @property string $default_currency * @property bool $details_submitted - * @property string $display_name * @property string $email - * @property mixed $external_accounts - * @property mixed $legal_entity + * @property Collection $external_accounts + * @property mixed $individual * @property StripeObject $metadata - * @property mixed $payout_schedule - * @property string $payout_statement_descriptor * @property bool $payouts_enabled - * @property string $product_description - * @property string $statement_descriptor - * @property string $support_email - * @property string $support_phone - * @property string $timezone + * @property mixed $requirements + * @property mixed $settings * @property mixed $tos_acceptance - * @property mixed $verification + * @property string $type * * @package Stripe */ class Account extends ApiResource { + + const OBJECT_NAME = "account"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; @@ -47,6 +42,37 @@ class Account extends ApiResource } use ApiOperations\Update; + /** + * Possible string representations of an account's business type. + * @link https://stripe.com/docs/api/accounts/object#account_object-business_type + */ + const BUSINESS_TYPE_COMPANY = 'company'; + const BUSINESS_TYPE_INDIVIDUAL = 'individual'; + + /** + * Possible string representations of an account's capabilities. + * @link https://stripe.com/docs/api/accounts/object#account_object-capabilities + */ + const CAPABILITY_CARD_PAYMENTS = 'card_payments'; + const CAPABILITY_LEGACY_PAYMENTS = 'legacy_payments'; + const CAPABILITY_PLATFORM_PAYMENTS = 'platform_payments'; + + /** + * Possible string representations of an account's capability status. + * @link https://stripe.com/docs/api/accounts/object#account_object-capabilities + */ + const CAPABILITY_STATUS_ACTIVE = 'active'; + const CAPABILITY_STATUS_INACTIVE = 'inactive'; + const CAPABILITY_STATUS_PENDING = 'pending'; + + /** + * Possible string representations of an account's type. + * @link https://stripe.com/docs/api/accounts/object#account_object-type + */ + const TYPE_CUSTOM = 'custom'; + const TYPE_EXPRESS = 'express'; + const TYPE_STANDARD = 'standard'; + public static function getSavedNestedResources() { static $savedNestedResources = null; @@ -61,6 +87,7 @@ class Account extends ApiResource const PATH_EXTERNAL_ACCOUNTS = '/external_accounts'; const PATH_LOGIN_LINKS = '/login_links'; + const PATH_PERSONS = '/persons'; public function instanceUrl() { @@ -101,6 +128,21 @@ class Account extends ApiResource return $this; } + /** + * @param array|null $params + * @param array|string|null $options + * + * @return Collection The list of persons. + */ + public function persons($params = null, $options = null) + { + $url = $this->instanceUrl() . '/persons'; + list($response, $opts) = $this->_request('get', $url, $params, $options); + $obj = Util\Util::convertToStripeObject($response, $opts); + $obj->setLastResponse($response); + return $obj; + } + /** * @param array|null $clientId * @param array|string|null $opts @@ -113,11 +155,11 @@ class Account extends ApiResource 'client_id' => $clientId, 'stripe_user_id' => $this->id, ]; - OAuth::deauthorize($params, $opts); + return OAuth::deauthorize($params, $opts); } /** - * @param array|null $id The ID of the account on which to create the external account. + * @param string|null $id The ID of the account on which to create the external account. * @param array|null $params * @param array|string|null $opts * @@ -129,7 +171,7 @@ class Account extends ApiResource } /** - * @param array|null $id The ID of the account to which the external account belongs. + * @param string|null $id The ID of the account to which the external account belongs. * @param array|null $externalAccountId The ID of the external account to retrieve. * @param array|null $params * @param array|string|null $opts @@ -142,7 +184,7 @@ class Account extends ApiResource } /** - * @param array|null $id The ID of the account to which the external account belongs. + * @param string|null $id The ID of the account to which the external account belongs. * @param array|null $externalAccountId The ID of the external account to update. * @param array|null $params * @param array|string|null $opts @@ -155,7 +197,7 @@ class Account extends ApiResource } /** - * @param array|null $id The ID of the account to which the external account belongs. + * @param string|null $id The ID of the account to which the external account belongs. * @param array|null $externalAccountId The ID of the external account to delete. * @param array|null $params * @param array|string|null $opts @@ -168,11 +210,11 @@ class Account extends ApiResource } /** - * @param array|null $id The ID of the account on which to retrieve the external accounts. + * @param string|null $id The ID of the account on which to retrieve the external accounts. * @param array|null $params * @param array|string|null $opts * - * @return BankAccount|Card + * @return Collection The list of external accounts (BankAccount or Card). */ public static function allExternalAccounts($id, $params = null, $opts = null) { @@ -180,7 +222,7 @@ class Account extends ApiResource } /** - * @param array|null $id The ID of the account on which to create the login link. + * @param string|null $id The ID of the account on which to create the login link. * @param array|null $params * @param array|string|null $opts * @@ -191,6 +233,69 @@ class Account extends ApiResource return self::_createNestedResource($id, static::PATH_LOGIN_LINKS, $params, $opts); } + /** + * @param string|null $id The ID of the account on which to create the person. + * @param array|null $params + * @param array|string|null $opts + * + * @return Person + */ + public static function createPerson($id, $params = null, $opts = null) + { + return self::_createNestedResource($id, static::PATH_PERSONS, $params, $opts); + } + + /** + * @param string|null $id The ID of the account to which the person belongs. + * @param string|null $personId The ID of the person to retrieve. + * @param array|null $params + * @param array|string|null $opts + * + * @return Person + */ + public static function retrievePerson($id, $personId, $params = null, $opts = null) + { + return self::_retrieveNestedResource($id, static::PATH_PERSONS, $personId, $params, $opts); + } + + /** + * @param string|null $id The ID of the account to which the person belongs. + * @param string|null $personId The ID of the person to update. + * @param array|null $params + * @param array|string|null $opts + * + * @return Person + */ + public static function updatePerson($id, $personId, $params = null, $opts = null) + { + return self::_updateNestedResource($id, static::PATH_PERSONS, $personId, $params, $opts); + } + + /** + * @param string|null $id The ID of the account to which the person belongs. + * @param string|null $personId The ID of the person to delete. + * @param array|null $params + * @param array|string|null $opts + * + * @return Person + */ + public static function deletePerson($id, $personId, $params = null, $opts = null) + { + return self::_deleteNestedResource($id, static::PATH_PERSONS, $personId, $params, $opts); + } + + /** + * @param string|null $id The ID of the account on which to retrieve the persons. + * @param array|null $params + * @param array|string|null $opts + * + * @return Collection The list of persons. + */ + public static function allPersons($id, $params = null, $opts = null) + { + return self::_allNestedResources($id, static::PATH_PERSONS, $params, $opts); + } + public function serializeParameters($force = false) { $update = parent::serializeParameters($force); @@ -203,6 +308,12 @@ class Account extends ApiResource $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; } @@ -224,7 +335,9 @@ class Account extends ApiResource $update = ($v instanceof StripeObject) ? $v->serializeParameters() : $v; if ($update !== []) { - if (!$originalValue || ($update != $legalEntity->serializeParamsValue($originalValue[$i], null, false, true))) { + if (!$originalValue || + !array_key_exists($i, $originalValue) || + ($update != $legalEntity->serializeParamsValue($originalValue[$i], null, false, true))) { $updateArr[$i] = $update; } } diff --git a/htdocs/includes/stripe/lib/AccountLink.php b/htdocs/includes/stripe/lib/AccountLink.php new file mode 100644 index 00000000000..f2975ae3834 --- /dev/null +++ b/htdocs/includes/stripe/lib/AccountLink.php @@ -0,0 +1,21 @@ +setLastResponse($response); $obj->setRequestParams($params); diff --git a/htdocs/includes/stripe/lib/ApiOperations/NestedResource.php b/htdocs/includes/stripe/lib/ApiOperations/NestedResource.php index 1c3a73f45de..2122354362f 100644 --- a/htdocs/includes/stripe/lib/ApiOperations/NestedResource.php +++ b/htdocs/includes/stripe/lib/ApiOperations/NestedResource.php @@ -60,6 +60,7 @@ trait NestedResource /** * @param string $id * @param string $nestedPath + * @param string|null $nestedId * @param array|null $params * @param array|string|null $options * @@ -74,6 +75,7 @@ trait NestedResource /** * @param string $id * @param string $nestedPath + * @param string|null $nestedId * @param array|null $params * @param array|string|null $options * @@ -88,6 +90,7 @@ trait NestedResource /** * @param string $id * @param string $nestedPath + * @param string|null $nestedId * @param array|null $params * @param array|string|null $options * diff --git a/htdocs/includes/stripe/lib/ApiOperations/Request.php b/htdocs/includes/stripe/lib/ApiOperations/Request.php index c6b06585ad2..dd048dc5f5c 100644 --- a/htdocs/includes/stripe/lib/ApiOperations/Request.php +++ b/htdocs/includes/stripe/lib/ApiOperations/Request.php @@ -52,7 +52,8 @@ trait Request protected static function _staticRequest($method, $url, $params, $options) { $opts = \Stripe\Util\RequestOptions::parse($options); - $requestor = new \Stripe\ApiRequestor($opts->apiKey, static::baseUrl()); + $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]; diff --git a/htdocs/includes/stripe/lib/ApiOperations/Retrieve.php b/htdocs/includes/stripe/lib/ApiOperations/Retrieve.php index a037326b3e8..ed52296b75b 100644 --- a/htdocs/includes/stripe/lib/ApiOperations/Retrieve.php +++ b/htdocs/includes/stripe/lib/ApiOperations/Retrieve.php @@ -15,7 +15,7 @@ trait Retrieve * or an options array containing an `id` key. * @param array|string|null $opts * - * @return \Stripe\StripeObject + * @return static */ public static function retrieve($id, $opts = null) { diff --git a/htdocs/includes/stripe/lib/ApiRequestor.php b/htdocs/includes/stripe/lib/ApiRequestor.php index 334d84425b3..7cf851877de 100644 --- a/htdocs/includes/stripe/lib/ApiRequestor.php +++ b/htdocs/includes/stripe/lib/ApiRequestor.php @@ -9,12 +9,32 @@ namespace Stripe; */ class ApiRequestor { + /** + * @var string|null + */ private $_apiKey; + /** + * @var string + */ private $_apiBase; + /** + * @var HttpClient\ClientInterface + */ private static $_httpClient; + /** + * @var RequestTelemetry + */ + private static $requestTelemetry; + + /** + * ApiRequestor constructor. + * + * @param string|null $apiKey + * @param string|null $apiBase + */ public function __construct($apiKey = null, $apiBase = null) { $this->_apiKey = $apiKey; @@ -24,6 +44,37 @@ class ApiRequestor $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 = array( + 'last_request_metrics' => array( + 'request_id' => $requestTelemetry->requestId, + 'request_duration_ms' => $requestTelemetry->requestDuration, + )); + + $result = json_encode($payload); + if ($result != false) { + return $result; + } else { + Stripe::getLogger()->error("Serializing telemetry payload failed!"); + return "{}"; + } + } + + /** + * @static + * + * @param ApiResource|bool|array|mixed $d + * + * @return ApiResource|array|string|mixed + */ private static function _encodeObjects($d) { if ($d instanceof ApiResource) { @@ -44,13 +95,27 @@ class ApiRequestor } /** - * @param string $method - * @param string $url + * @param string $method + * @param string $url * @param array|null $params * @param array|null $headers * * @return array An array whose first element is an API response and second * element is the API key used to make the request. + * @throws Error\Api + * @throws Error\Authentication + * @throws Error\Card + * @throws Error\InvalidRequest + * @throws Error\OAuth\InvalidClient + * @throws Error\OAuth\InvalidGrant + * @throws Error\OAuth\InvalidRequest + * @throws Error\OAuth\InvalidScope + * @throws Error\OAuth\UnsupportedGrantType + * @throws Error\OAuth\UnsupportedResponseType + * @throws Error\Permission + * @throws Error\RateLimit + * @throws Error\Idempotency + * @throws Error\ApiConnection */ public function request($method, $url, $params = null, $headers = null) { @@ -70,13 +135,22 @@ class ApiRequestor * @param array $resp * * @throws Error\InvalidRequest if the error is caused by the user. - * @throws Error\Idempotency if the error is caused by an idempotency key. * @throws Error\Authentication if the error is caused by a lack of * permissions. * @throws Error\Permission if the error is caused by insufficient * permissions. * @throws Error\Card if the error is the error code is 402 (payment * required) + * @throws Error\InvalidRequest if the error is caused by the user. + * @throws Error\Idempotency if the error is caused by an idempotency key. + * @throws Error\OAuth\InvalidClient + * @throws Error\OAuth\InvalidGrant + * @throws Error\OAuth\InvalidRequest + * @throws Error\OAuth\InvalidScope + * @throws Error\OAuth\UnsupportedGrantType + * @throws Error\OAuth\UnsupportedResponseType + * @throws Error\Permission if the error is caused by insufficient + * permissions. * @throws Error\RateLimit if the error is caused by too many requests * hitting the API. * @throws Error\Api otherwise. @@ -102,6 +176,17 @@ class ApiRequestor throw $error; } + /** + * @static + * + * @param string $rbody + * @param int $rcode + * @param array $rheaders + * @param array $resp + * @param array $errorData + * + * @return Error\RateLimit|Error\Idempotency|Error\InvalidRequest|Error\Authentication|Error\Card|Error\Permission|Error\Api + */ private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData) { $msg = isset($errorData['message']) ? $errorData['message'] : null; @@ -136,6 +221,17 @@ class ApiRequestor } } + /** + * @static + * + * @param string|bool $rbody + * @param int $rcode + * @param array $rheaders + * @param array $resp + * @param string $errorCode + * + * @return null|Error\OAuth\InvalidClient|Error\OAuth\InvalidGrant|Error\OAuth\InvalidRequest|Error\OAuth\InvalidScope|Error\OAuth\UnsupportedGrantType|Error\OAuth\UnsupportedResponseType + */ private static function _specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorCode) { $description = isset($resp['error_description']) ? $resp['error_description'] : $errorCode; @@ -158,6 +254,13 @@ class ApiRequestor return null; } + /** + * @static + * + * @param null|array $appInfo + * + * @return null|string + */ private static function _formatAppInfo($appInfo) { if ($appInfo !== null) { @@ -174,6 +277,14 @@ class ApiRequestor } } + /** + * @static + * + * @param string $apiKey + * @param null $clientInfo + * + * @return array + */ private static function _defaultHeaders($apiKey, $clientInfo = null) { $uaString = 'Stripe/v1 PhpBindings/' . Stripe::VERSION; @@ -205,6 +316,17 @@ class ApiRequestor return $defaultHeaders; } + /** + * @param string $method + * @param string $url + * @param array $params + * @param array $headers + * + * @return array + * @throws Error\Api + * @throws Error\ApiConnection + * @throws Error\Authentication + */ private function _requestRaw($method, $url, $params, $headers) { $myApiKey = $this->_apiKey; @@ -239,6 +361,10 @@ class ApiRequestor $defaultHeaders['Stripe-Account'] = Stripe::$accountId; } + if (Stripe::$enableTelemetry && self::$requestTelemetry != null) { + $defaultHeaders["X-Stripe-Client-Telemetry"] = self::_telemetryJson(self::$requestTelemetry); + } + $hasFile = false; $hasCurlFile = class_exists('\CURLFile', false); foreach ($params as $k => $v) { @@ -263,6 +389,8 @@ class ApiRequestor $rawHeaders[] = $header . ': ' . $value; } + $requestStartMs = Util\Util::currentTimeMillis(); + list($rbody, $rcode, $rheaders) = $this->httpClient()->request( $method, $absUrl, @@ -270,9 +398,24 @@ class ApiRequestor $params, $hasFile ); + + if (array_key_exists('request-id', $rheaders)) { + self::$requestTelemetry = new RequestTelemetry( + $rheaders['request-id'], + Util\Util::currentTimeMillis() - $requestStartMs + ); + } + return [$rbody, $rcode, $rheaders, $myApiKey]; } + /** + * @param resource $resource + * @param bool $hasCurlFile + * + * @return \CURLFile|string + * @throws Error\Api + */ private function _processResourceParam($resource, $hasCurlFile) { if (get_resource_type($resource) !== 'stream') { @@ -296,6 +439,26 @@ class ApiRequestor } } + /** + * @param string $rbody + * @param int $rcode + * @param array $rheaders + * + * @return mixed + * @throws Error\Api + * @throws Error\Authentication + * @throws Error\Card + * @throws Error\InvalidRequest + * @throws Error\OAuth\InvalidClient + * @throws Error\OAuth\InvalidGrant + * @throws Error\OAuth\InvalidRequest + * @throws Error\OAuth\InvalidScope + * @throws Error\OAuth\UnsupportedGrantType + * @throws Error\OAuth\UnsupportedResponseType + * @throws Error\Permission + * @throws Error\RateLimit + * @throws Error\Idempotency + */ private function _interpretResponse($rbody, $rcode, $rheaders) { $resp = json_decode($rbody, true); @@ -312,11 +475,29 @@ class ApiRequestor 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) { diff --git a/htdocs/includes/stripe/lib/ApiResource.php b/htdocs/includes/stripe/lib/ApiResource.php index f73b22c9663..fe594321687 100644 --- a/htdocs/includes/stripe/lib/ApiResource.php +++ b/htdocs/includes/stripe/lib/ApiResource.php @@ -66,30 +66,6 @@ abstract class ApiResource extends StripeObject return $this; } - /** - * @return string The name of the class, with namespacing and underscores - * stripped. - */ - public static function className() - { - $class = get_called_class(); - // Useful for namespaces: Foo\Charge - if ($postfixNamespaces = strrchr($class, '\\')) { - $class = substr($postfixNamespaces, 1); - } - // Useful for underscored 'namespaces': Foo_Charge - if ($postfixFakeNamespaces = strrchr($class, '')) { - $class = $postfixFakeNamespaces; - } - if (substr($class, 0, strlen('Stripe')) == 'Stripe') { - $class = substr($class, strlen('Stripe')); - } - $class = str_replace('_', '', $class); - $name = urlencode($class); - $name = strtolower($name); - return $name; - } - /** * @return string The base URL for the given class. */ @@ -103,7 +79,9 @@ abstract class ApiResource extends StripeObject */ public static function classUrl() { - $base = static::className(); + // 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"; } diff --git a/htdocs/includes/stripe/lib/ApplePayDomain.php b/htdocs/includes/stripe/lib/ApplePayDomain.php index 124c5dc0632..ea84220a7a9 100644 --- a/htdocs/includes/stripe/lib/ApplePayDomain.php +++ b/htdocs/includes/stripe/lib/ApplePayDomain.php @@ -9,6 +9,9 @@ namespace Stripe; */ class ApplePayDomain extends ApiResource { + + const OBJECT_NAME = "apple_pay_domain"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; diff --git a/htdocs/includes/stripe/lib/ApplicationFee.php b/htdocs/includes/stripe/lib/ApplicationFee.php index 05b94ea9235..0d9fde4c521 100644 --- a/htdocs/includes/stripe/lib/ApplicationFee.php +++ b/htdocs/includes/stripe/lib/ApplicationFee.php @@ -24,23 +24,15 @@ namespace Stripe; */ class ApplicationFee extends ApiResource { + + const OBJECT_NAME = "application_fee"; + use ApiOperations\All; use ApiOperations\NestedResource; use ApiOperations\Retrieve; const PATH_REFUNDS = '/refunds'; - /** - * This is a special case because the application fee endpoint has an - * underscore in it. The parent `className` function strips underscores. - * - * @return string The name of the class. - */ - public static function className() - { - return 'application_fee'; - } - /** * @param array|null $params * @param array|string|null $opts @@ -55,7 +47,7 @@ class ApplicationFee extends ApiResource } /** - * @param array|null $id The ID of the application fee on which to create the refund. + * @param string|null $id The ID of the application fee on which to create the refund. * @param array|null $params * @param array|string|null $opts * @@ -67,7 +59,7 @@ class ApplicationFee extends ApiResource } /** - * @param array|null $id The ID of the application fee to which the refund belongs. + * @param string|null $id The ID of the application fee to which the refund belongs. * @param array|null $refundId The ID of the refund to retrieve. * @param array|null $params * @param array|string|null $opts @@ -80,7 +72,7 @@ class ApplicationFee extends ApiResource } /** - * @param array|null $id The ID of the application fee to which the refund belongs. + * @param string|null $id The ID of the application fee to which the refund belongs. * @param array|null $refundId The ID of the refund to update. * @param array|null $params * @param array|string|null $opts @@ -93,11 +85,11 @@ class ApplicationFee extends ApiResource } /** - * @param array|null $id The ID of the application fee on which to retrieve the refunds. + * @param string|null $id The ID of the application fee on which to retrieve the refunds. * @param array|null $params * @param array|string|null $opts * - * @return ApplicationFeeRefund + * @return Collection The list of refunds. */ public static function allRefunds($id, $params = null, $opts = null) { diff --git a/htdocs/includes/stripe/lib/ApplicationFeeRefund.php b/htdocs/includes/stripe/lib/ApplicationFeeRefund.php index 4b1c425a8ee..91d7e9d2bc6 100644 --- a/htdocs/includes/stripe/lib/ApplicationFeeRefund.php +++ b/htdocs/includes/stripe/lib/ApplicationFeeRefund.php @@ -18,6 +18,9 @@ namespace Stripe; */ class ApplicationFeeRefund extends ApiResource { + + const OBJECT_NAME = "fee_refund"; + use ApiOperations\Update { save as protected _save; } diff --git a/htdocs/includes/stripe/lib/Balance.php b/htdocs/includes/stripe/lib/Balance.php index 115307f843b..25f88ae74c7 100644 --- a/htdocs/includes/stripe/lib/Balance.php +++ b/htdocs/includes/stripe/lib/Balance.php @@ -7,6 +7,7 @@ namespace Stripe; * * @property string $object * @property array $available + * @property array $connect_reserved * @property bool $livemode * @property array $pending * @@ -14,6 +15,9 @@ namespace Stripe; */ class Balance extends SingletonApiResource { + + const OBJECT_NAME = "balance"; + /** * @param array|string|null $opts * diff --git a/htdocs/includes/stripe/lib/BalanceTransaction.php b/htdocs/includes/stripe/lib/BalanceTransaction.php index f82888ab1dd..cd9b79ae675 100644 --- a/htdocs/includes/stripe/lib/BalanceTransaction.php +++ b/htdocs/includes/stripe/lib/BalanceTransaction.php @@ -24,6 +24,9 @@ namespace Stripe; */ class BalanceTransaction extends ApiResource { + + const OBJECT_NAME = "balance_transaction"; + use ApiOperations\All; use ApiOperations\Retrieve; diff --git a/htdocs/includes/stripe/lib/BankAccount.php b/htdocs/includes/stripe/lib/BankAccount.php index 2afc312d003..019a4d87cbd 100644 --- a/htdocs/includes/stripe/lib/BankAccount.php +++ b/htdocs/includes/stripe/lib/BankAccount.php @@ -25,6 +25,9 @@ namespace Stripe; */ class BankAccount extends ApiResource { + + const OBJECT_NAME = "bank_account"; + use ApiOperations\Delete; use ApiOperations\Update; diff --git a/htdocs/includes/stripe/lib/BitcoinReceiver.php b/htdocs/includes/stripe/lib/BitcoinReceiver.php index 8d04256b5db..b4cc5291b56 100644 --- a/htdocs/includes/stripe/lib/BitcoinReceiver.php +++ b/htdocs/includes/stripe/lib/BitcoinReceiver.php @@ -12,6 +12,9 @@ namespace Stripe; */ class BitcoinReceiver extends ApiResource { + + const OBJECT_NAME = "bitcoin_receiver"; + use ApiOperations\All; use ApiOperations\Retrieve; diff --git a/htdocs/includes/stripe/lib/BitcoinTransaction.php b/htdocs/includes/stripe/lib/BitcoinTransaction.php index 6b8e5421124..8269fd216eb 100644 --- a/htdocs/includes/stripe/lib/BitcoinTransaction.php +++ b/htdocs/includes/stripe/lib/BitcoinTransaction.php @@ -10,4 +10,5 @@ namespace Stripe; class BitcoinTransaction extends ApiResource { + const OBJECT_NAME = "bitcoin_transaction"; } diff --git a/htdocs/includes/stripe/lib/Card.php b/htdocs/includes/stripe/lib/Card.php index 7e57423601a..40de733e780 100644 --- a/htdocs/includes/stripe/lib/Card.php +++ b/htdocs/includes/stripe/lib/Card.php @@ -7,6 +7,7 @@ namespace Stripe; * * @property string $id * @property string $object + * @property string $account * @property string $address_city * @property string $address_country * @property string $address_line1 @@ -15,10 +16,13 @@ namespace Stripe; * @property string $address_state * @property string $address_zip * @property string $address_zip_check + * @property string[] $available_payout_methods * @property string $brand * @property string $country + * @property string $currency * @property string $customer * @property string $cvc_check + * @property bool $default_for_currency * @property string $dynamic_last4 * @property int $exp_month * @property int $exp_year @@ -27,15 +31,44 @@ namespace Stripe; * @property string $last4 * @property StripeObject $metadata * @property string $name + * @property string $recipient * @property string $tokenization_method * * @package Stripe */ class Card extends ApiResource { + + const OBJECT_NAME = "card"; + use ApiOperations\Delete; use ApiOperations\Update; + /** + * Possible string representations of the CVC check status. + * @link 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. + * @link 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. + * @link 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 @@ -74,7 +107,7 @@ class Card extends ApiResource { $msg = "Cards cannot be accessed without a customer, recipient or account ID. " . "Retrieve a card using \$customer->sources->retrieve('card_id'), " . - "\$recipient->cards->retrieve('card_id'), or"; + "\$recipient->cards->retrieve('card_id'), or " . "\$account->external_accounts->retrieve('card_id') instead."; throw new Error\InvalidRequest($msg, null); } @@ -90,7 +123,7 @@ class Card extends ApiResource { $msg = "Cards cannot be accessed without a customer, recipient or account ID. " . "Call save() on \$customer->sources->retrieve('card_id'), " . - "\$recipient->cards->retrieve('card_id'), or"; + "\$recipient->cards->retrieve('card_id'), or " . "\$account->external_accounts->retrieve('card_id') instead."; throw new Error\InvalidRequest($msg, null); } diff --git a/htdocs/includes/stripe/lib/Charge.php b/htdocs/includes/stripe/lib/Charge.php index 6d448022877..832a07c7c04 100644 --- a/htdocs/includes/stripe/lib/Charge.php +++ b/htdocs/includes/stripe/lib/Charge.php @@ -29,8 +29,10 @@ namespace Stripe; * @property string $order * @property mixed $outcome * @property bool $paid + * @property string $payment_intent * @property string $receipt_email * @property string $receipt_number + * @property string $receipt_url * @property bool $refunded * @property Collection $refunds * @property string $review @@ -40,17 +42,77 @@ namespace Stripe; * @property string $statement_descriptor * @property string $status * @property string $transfer + * @property mixed $transfer_data * @property string $transfer_group * * @package Stripe */ class Charge extends ApiResource { + + const OBJECT_NAME = "charge"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Retrieve; use ApiOperations\Update; + /** + * Possible string representations of decline codes. + * These strings are applicable to the decline_code property of the \Stripe\Error\Card exception. + * @link https://stripe.com/docs/declines/codes + */ + 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_NEW_ACCOUNT_INFORMATION_AVAILABLE = 'new_account_information_available'; + const DECLINED_NO_ACTION_TAKEN = 'no_action_taken'; + const DECLINED_NOT_PERMITTED = 'not_permitted'; + 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'; + + /** + * Possible string representations of the status of the charge. + * @link https://stripe.com/docs/api/charges/object#charge_object-status + */ + const STATUS_FAILED = 'failed'; + const STATUS_PENDING = 'pending'; + const STATUS_SUCCEEDED = 'succeeded'; + /** * @param array|null $params * @param array|string|null $options diff --git a/htdocs/includes/stripe/lib/Checkout/Session.php b/htdocs/includes/stripe/lib/Checkout/Session.php new file mode 100644 index 00000000000..968d58cf632 --- /dev/null +++ b/htdocs/includes/stripe/lib/Checkout/Session.php @@ -0,0 +1,30 @@ +data); + } + /** * @return Util\AutoPagingIterator An iterator that can be used to iterate * across all objects across all pages. As page boundaries are diff --git a/htdocs/includes/stripe/lib/CountrySpec.php b/htdocs/includes/stripe/lib/CountrySpec.php index cdaa4e84d89..668bfe62ed9 100644 --- a/htdocs/includes/stripe/lib/CountrySpec.php +++ b/htdocs/includes/stripe/lib/CountrySpec.php @@ -11,23 +11,16 @@ namespace Stripe; * @property mixed $supported_bank_account_currencies * @property string[] $supported_payment_currencies * @property string[] $supported_payment_methods + * @property string[] $supported_transfer_countries * @property mixed $verification_fields * * @package Stripe */ class CountrySpec extends ApiResource { + + const OBJECT_NAME = "country_spec"; + use ApiOperations\All; use ApiOperations\Retrieve; - - /** - * This is a special case because the country specs endpoint has an - * underscore in it. The parent `className` function strips underscores. - * - * @return string The name of the class. - */ - public static function className() - { - return 'country_spec'; - } } diff --git a/htdocs/includes/stripe/lib/Coupon.php b/htdocs/includes/stripe/lib/Coupon.php index a2d44443ce5..51d4fd86593 100644 --- a/htdocs/includes/stripe/lib/Coupon.php +++ b/htdocs/includes/stripe/lib/Coupon.php @@ -15,7 +15,8 @@ namespace Stripe; * @property bool $livemode * @property int $max_redemptions * @property StripeObject $metadata - * @property int $percent_off + * @property string $name + * @property float $percent_off * @property int $redeem_by * @property int $times_redeemed * @property bool $valid @@ -24,6 +25,9 @@ namespace Stripe; */ class Coupon extends ApiResource { + + const OBJECT_NAME = "coupon"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; diff --git a/htdocs/includes/stripe/lib/CreditNote.php b/htdocs/includes/stripe/lib/CreditNote.php new file mode 100644 index 00000000000..169ed0815c3 --- /dev/null +++ b/htdocs/includes/stripe/lib/CreditNote.php @@ -0,0 +1,73 @@ +instanceUrl() . '/void'; + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/htdocs/includes/stripe/lib/Customer.php b/htdocs/includes/stripe/lib/Customer.php index 8d31b5ac0aa..44f5e6e2f09 100644 --- a/htdocs/includes/stripe/lib/Customer.php +++ b/htdocs/includes/stripe/lib/Customer.php @@ -8,24 +8,33 @@ namespace Stripe; * @property string $id * @property string $object * @property int $account_balance - * @property string $business_vat_id + * @property mixed $address * @property string $created * @property string $currency * @property string $default_source * @property bool $delinquent * @property string $description - * @property mixed $discount + * @property Discount $discount * @property string $email + * @property string $invoice_prefix + * @property mixed $invoice_settings * @property bool $livemode * @property StripeObject $metadata + * @property string $name + * @property string $phone + * @property string[] preferred_locales * @property mixed $shipping * @property Collection $sources * @property Collection $subscriptions + * @property Collection $tax_ids * * @package Stripe */ class Customer extends ApiResource { + + const OBJECT_NAME = "customer"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; @@ -33,6 +42,14 @@ class Customer extends ApiResource use ApiOperations\Retrieve; use ApiOperations\Update; + /** + * Possible string representations of the customer's type of tax exemption. + * @link https://stripe.com/docs/api/customers/object#customer_object-tax_exempt + */ + const TAX_EXEMPT_NONE = 'none'; + const TAX_EXEMPT_EXEMPT = 'exempt'; + const TAX_EXEMPT_REVERSE = 'reverse'; + public static function getSavedNestedResources() { static $savedNestedResources = null; @@ -45,6 +62,7 @@ class Customer extends ApiResource } const PATH_SOURCES = '/sources'; + const PATH_TAX_IDS = '/tax_ids'; /** * @param array|null $params @@ -135,7 +153,7 @@ class Customer extends ApiResource } /** - * @param array|null $id The ID of the customer on which to create the source. + * @param string|null $id The ID of the customer on which to create the source. * @param array|null $params * @param array|string|null $opts * @@ -147,8 +165,8 @@ class Customer extends ApiResource } /** - * @param array|null $id The ID of the customer to which the source belongs. - * @param array|null $sourceId The ID of the source to retrieve. + * @param string|null $id The ID of the customer to which the source belongs. + * @param string|null $sourceId The ID of the source to retrieve. * @param array|null $params * @param array|string|null $opts * @@ -160,8 +178,8 @@ class Customer extends ApiResource } /** - * @param array|null $id The ID of the customer to which the source belongs. - * @param array|null $sourceId The ID of the source to update. + * @param string|null $id The ID of the customer to which the source belongs. + * @param string|null $sourceId The ID of the source to update. * @param array|null $params * @param array|string|null $opts * @@ -173,8 +191,8 @@ class Customer extends ApiResource } /** - * @param array|null $id The ID of the customer to which the source belongs. - * @param array|null $sourceId The ID of the source to delete. + * @param string|null $id The ID of the customer to which the source belongs. + * @param string|null $sourceId The ID of the source to delete. * @param array|null $params * @param array|string|null $opts * @@ -186,14 +204,64 @@ class Customer extends ApiResource } /** - * @param array|null $id The ID of the customer on which to retrieve the sources. + * @param string|null $id The ID of the customer on which to retrieve the sources. * @param array|null $params * @param array|string|null $opts * - * @return ApiResource + * @return Collection The list of sources. */ public static function allSources($id, $params = null, $opts = null) { return self::_allNestedResources($id, static::PATH_SOURCES, $params, $opts); } + + /** + * @param string|null $id The ID of the customer on which to create the tax id. + * @param array|null $params + * @param array|string|null $opts + * + * @return ApiResource + */ + public static function createTaxId($id, $params = null, $opts = null) + { + return self::_createNestedResource($id, static::PATH_TAX_IDS, $params, $opts); + } + + /** + * @param string|null $id The ID of the customer to which the tax id belongs. + * @param string|null $taxIdId The ID of the tax id to retrieve. + * @param array|null $params + * @param array|string|null $opts + * + * @return ApiResource + */ + public static function retrieveTaxId($id, $taxIdId, $params = null, $opts = null) + { + return self::_retrieveNestedResource($id, static::PATH_TAX_IDS, $taxIdId, $params, $opts); + } + + /** + * @param string|null $id The ID of the customer to which the tax id belongs. + * @param string|null $taxIdId The ID of the tax id to delete. + * @param array|null $params + * @param array|string|null $opts + * + * @return ApiResource + */ + public static function deleteTaxId($id, $taxIdId, $params = null, $opts = null) + { + return self::_deleteNestedResource($id, static::PATH_TAX_IDS, $taxIdId, $params, $opts); + } + + /** + * @param string|null $id The ID of the customer on which to retrieve the tax ids. + * @param array|null $params + * @param array|string|null $opts + * + * @return 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); + } } diff --git a/htdocs/includes/stripe/lib/Discount.php b/htdocs/includes/stripe/lib/Discount.php new file mode 100644 index 00000000000..a72d12bc6e3 --- /dev/null +++ b/htdocs/includes/stripe/lib/Discount.php @@ -0,0 +1,21 @@ +code = $code; + $this->errorCode = $code; } public function getErrorCode() { - return $this->code; + return $this->errorCode; } } diff --git a/htdocs/includes/stripe/lib/Event.php b/htdocs/includes/stripe/lib/Event.php index 2add5ce11be..90b55c75151 100644 --- a/htdocs/includes/stripe/lib/Event.php +++ b/htdocs/includes/stripe/lib/Event.php @@ -7,107 +7,152 @@ namespace Stripe; * * @property string $id * @property string $object + * @property string $account * @property string $api_version - * @property int $created - * @property mixed $data - * @property bool $livemode - * @property int $pending_webhooks - * @property mixed $request + * @property int $created + * @property mixed $data + * @property bool $livemode + * @property int $pending_webhooks + * @property mixed $request * @property string $type * * @package Stripe */ class Event extends ApiResource { - /** + + const OBJECT_NAME = "event"; + + /** * Possible string representations of event types. * @link https://stripe.com/docs/api#event_types */ - const ACCOUNT_UPDATED = 'account.updated'; - 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_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 COUPON_CREATED = 'coupon.created'; - const COUPON_DELETED = 'coupon.deleted'; - const COUPON_UPDATED = 'coupon.updated'; - 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_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 INVOICEITEM_CREATED = 'invoiceitem.created'; - const INVOICEITEM_DELETED = 'invoiceitem.deleted'; - const INVOICEITEM_UPDATED = 'invoiceitem.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 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 PING = 'ping'; - const PLAN_CREATED = 'plan.created'; - const PLAN_DELETED = 'plan.deleted'; - const PLAN_UPDATED = 'plan.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 REVIEW_CLOSED = 'review.closed'; - const REVIEW_OPENED = 'review.opened'; - 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_TRANSACTION_CREATED = 'source.transaction.created'; - const TOPUP_CREATED = 'topup.created'; - const TOPUP_FAILED = 'topup.failed'; - const TOPUP_SUCCEEDED = 'topup.succeeded'; - const TRANSFER_CREATED = 'transfer.created'; - const TRANSFER_REVERSED = 'transfer.reversed'; - const TRANSFER_UPDATED = 'transfer.updated'; + 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 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_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_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_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_CREATED = 'payment_intent.created'; + const PAYMENT_INTENT_PAYMENT_FAILED = 'payment_intent.payment_failed'; + const PAYMENT_INTENT_SUCCEEDED = 'payment_intent.succeeded'; + 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 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 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'; use ApiOperations\All; use ApiOperations\Retrieve; diff --git a/htdocs/includes/stripe/lib/ExchangeRate.php b/htdocs/includes/stripe/lib/ExchangeRate.php index 40763261834..803a5f87700 100644 --- a/htdocs/includes/stripe/lib/ExchangeRate.php +++ b/htdocs/includes/stripe/lib/ExchangeRate.php @@ -9,17 +9,9 @@ namespace Stripe; */ class ExchangeRate extends ApiResource { + + const OBJECT_NAME = "exchange_rate"; + use ApiOperations\All; use ApiOperations\Retrieve; - - /** - * This is a special case because the exchange rates endpoint has an - * underscore in it. The parent `className` function strips underscores. - * - * @return string The name of the class. - */ - public static function className() - { - return 'exchange_rate'; - } } diff --git a/htdocs/includes/stripe/lib/File.php b/htdocs/includes/stripe/lib/File.php new file mode 100644 index 00000000000..76109ad38cf --- /dev/null +++ b/htdocs/includes/stripe/lib/File.php @@ -0,0 +1,62 @@ +apiBase)) { + $opts->apiBase = Stripe::$apiUploadBase; + } + // Manually flatten params, otherwise curl's multipart encoder will + // choke on nested arrays. + // TODO: use array_column() once we drop support for PHP 5.4 + $flatParams = []; + foreach (\Stripe\Util\Util::flattenParams($params) as $pair) { + $flatParams[$pair[0]] = $pair[1]; + } + return static::_create($flatParams, $opts); + } +} diff --git a/htdocs/includes/stripe/lib/FileLink.php b/htdocs/includes/stripe/lib/FileLink.php new file mode 100644 index 00000000000..2a012b36105 --- /dev/null +++ b/htdocs/includes/stripe/lib/FileLink.php @@ -0,0 +1,29 @@ +defaultOptions = $defaultOptions; $this->randomGenerator = $randomGenerator ?: new Util\RandomGenerator(); $this->initUserAgentInfo(); + + // TODO: curl_reset requires PHP >= 5.5.0. Once we drop support for PHP 5.4, we can simply + // initialize this to true. + $this->enablePersistentConnections = function_exists('curl_reset'); + + $this->enableHttp2 = $this->canSafelyUseHttp2(); + } + + public function __destruct() + { + $this->closeCurlHandle(); } public function initUserAgentInfo() @@ -77,6 +98,38 @@ class CurlClient implements ClientInterface return $this->userAgentInfo; } + /** + * @return boolean + */ + public function getEnablePersistentConnections() + { + return $this->enablePersistentConnections; + } + + /** + * @param boolean $enable + */ + public function setEnablePersistentConnections($enable) + { + $this->enablePersistentConnections = $enable; + } + + /** + * @return boolean + */ + public function getEnableHttp2() + { + return $this->enableHttp2; + } + + /** + * @param boolean $enable + */ + public function setEnableHttp2($enable) + { + $this->enableHttp2 = $enable; + } + // USER DEFINED TIMEOUTS const DEFAULT_TIMEOUT = 80; @@ -123,6 +176,8 @@ class CurlClient implements ClientInterface $opts = $this->defaultOptions; } + $params = Util\Util::objectsToIds($params); + if ($method == 'get') { if ($hasFile) { throw new Error\Api( @@ -131,16 +186,16 @@ class CurlClient implements ClientInterface } $opts[CURLOPT_HTTPGET] = 1; if (count($params) > 0) { - $encoded = Util\Util::urlEncode($params); + $encoded = Util\Util::encodeParameters($params); $absUrl = "$absUrl?$encoded"; } } elseif ($method == 'post') { $opts[CURLOPT_POST] = 1; - $opts[CURLOPT_POSTFIELDS] = $hasFile ? $params : Util\Util::urlEncode($params); + $opts[CURLOPT_POSTFIELDS] = $hasFile ? $params : Util\Util::encodeParameters($params); } elseif ($method == 'delete') { $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; if (count($params) > 0) { - $encoded = Util\Util::urlEncode($params); + $encoded = Util\Util::encodeParameters($params); $absUrl = "$absUrl?$encoded"; } } else { @@ -150,13 +205,13 @@ class CurlClient implements ClientInterface // It is only safe to retry network failures on POST requests if we // add an Idempotency-Key header if (($method == 'post') && (Stripe::$maxNetworkRetries > 0)) { - if (!isset($headers['Idempotency-Key'])) { + if (!$this->hasHeader($headers, "Idempotency-Key")) { array_push($headers, 'Idempotency-Key: ' . $this->randomGenerator->uuid()); } } // Create a callback to capture HTTP headers for the response - $rheaders = []; + $rheaders = new Util\CaseInsensitiveArray(); $headerCallback = function ($curl, $header_line) use (&$rheaders) { // Ignore the HTTP request line (HTTP/1.1 200 OK) if (strpos($header_line, ":") === false) { @@ -193,6 +248,11 @@ class CurlClient implements ClientInterface $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) = $this->executeRequestWithRetries($opts, $absUrl); return [$rbody, $rcode, $rheaders]; @@ -209,17 +269,19 @@ class CurlClient implements ClientInterface $rcode = 0; $errno = 0; - $curl = curl_init(); - curl_setopt_array($curl, $opts); - $rbody = curl_exec($curl); + $this->resetCurlHandle(); + curl_setopt_array($this->curlHandle, $opts); + $rbody = curl_exec($this->curlHandle); if ($rbody === false) { - $errno = curl_errno($curl); - $message = curl_error($curl); + $errno = curl_errno($this->curlHandle); + $message = curl_error($this->curlHandle); } else { - $rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $rcode = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE); + } + if (!$this->getEnablePersistentConnections()) { + $this->closeCurlHandle(); } - curl_close($curl); if ($this->shouldRetry($errno, $rcode, $numRetries)) { $numRetries += 1; @@ -331,4 +393,68 @@ class CurlClient implements ClientInterface 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 (!is_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 (!is_null($this->curlHandle) && $this->getEnablePersistentConnections()) { + curl_reset($this->curlHandle); + } else { + $this->initCurlHandle(); + } + } + + /** + * Indicates whether it is safe to use HTTP/2 or not. + * + * @return boolean + */ + 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 boolean + */ + private function hasHeader($headers, $name) + { + foreach ($headers as $header) { + if (strncasecmp($header, "{$name}: ", strlen($name) + 2) === 0) { + return true; + } + } + + return false; + } } diff --git a/htdocs/includes/stripe/lib/Invoice.php b/htdocs/includes/stripe/lib/Invoice.php index 07d67f74a8a..6e0ec9d6b6c 100644 --- a/htdocs/includes/stripe/lib/Invoice.php +++ b/htdocs/includes/stripe/lib/Invoice.php @@ -7,51 +7,161 @@ namespace Stripe; * * @property string $id * @property string $object + * @property string $account_country + * @property string $account_name * @property int $amount_due * @property int $amount_paid * @property int $amount_remaining - * @property int $application_fee + * @property int $application_fee_amount * @property int $attempt_count * @property bool $attempted + * @property bool $auto_advance * @property string $billing + * @property string $billing_reason * @property string $charge - * @property bool $closed + * @property int $created * @property string $currency + * @property array $custom_fields * @property string $customer - * @property int $date + * @property mixed $customer_address + * @property string $customer_email + * @property string $customer_name + * @property string $customer_phone + * @property mixed $customer_shipping + * @property array $customer_tax_ids + * @property string $default_payment_method + * @property string $default_source + * @property array $default_tax_rates * @property string $description - * @property mixed $discount + * @property Discount $discount * @property int $due_date * @property int $ending_balance - * @property bool $forgiven + * @property string $footer + * @property string $hosted_invoice_url + * @property string $invoice_pdf * @property Collection $lines * @property bool $livemode * @property StripeObject $metadata * @property int $next_payment_attempt * @property string $number * @property bool $paid + * @property string $payment_intent * @property int $period_end * @property int $period_start + * @property int $post_payment_credit_notes_amount + * @property int $pre_payment_credit_notes_amount * @property string $receipt_number * @property int $starting_balance * @property string $statement_descriptor + * @property string $status + * @property mixed $status_transitions * @property string $subscription * @property int $subscription_proration_date * @property int $subtotal * @property int $tax - * @property float $tax_percent + * @property mixed $threshold_reason * @property int $total + * @property array $total_tax_amounts * @property int $webhooks_delivered_at * * @package Stripe */ class Invoice extends ApiResource { + + const OBJECT_NAME = "invoice"; + use ApiOperations\All; use ApiOperations\Create; + use ApiOperations\Delete; use ApiOperations\Retrieve; use ApiOperations\Update; + /** + * Possible string representations of the invoice status. + * @link https://stripe.com/docs/api/invoices/object#invoice_object-status + */ + const STATUS_DRAFT = 'draft'; + const STATUS_OPEN = 'open'; + const STATUS_PAID = 'paid'; + const STATUS_UNCOLLECTIBLE = 'uncollectible'; + const STATUS_VOID = 'void'; + + /** + * Possible string representations of the billing. + * @link https://stripe.com/docs/api/invoices/object#invoice_object-billing + */ + const BILLING_SEND_INVOICE = 'send_invoice'; + const BILLING_CHARGE_AUTOMATICALLY = 'charge_automatically'; + + /** + * Possible string representations of the billing reason. + * @link https://stripe.com/docs/api/invoices/object#invoice_object-billing_reason + */ + const BILLING_REASON_SUBSCRIPTION = 'subscription'; + const BILLING_REASON_SUBSCRIPTION_CREATE = 'subscription_create'; + const BILLING_REASON_SUBSCRIPTION_CYCLE = 'subscription_cycle'; + const BILLING_REASON_SUBSCRIPTION_UPDATE = 'subscription_update'; + const BILLING_REASON_SUBSCRIPTION_THRESHOLD = 'subscription_threshold'; + const BILLING_REASON_MANUAL = 'manual'; + const BILLING_REASON_UPCOMING = 'upcoming'; + + /** + * @param array|null $params + * @param array|string|null $opts + * + * @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 array|null $params + * @param array|string|null $opts + * + * @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 array|null $params + * @param array|string|null $opts + * + * @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 array|null $params + * @param array|string|null $opts + * + * @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 array|null $params * @param array|string|null $opts @@ -68,11 +178,14 @@ class Invoice extends ApiResource } /** - * @return Invoice The paid invoice. + * @param array|null $params + * @param array|string|null $opts + * + * @return Invoice The voided invoice. */ - public function pay($params = null, $opts = null) + public function voidInvoice($params = null, $opts = null) { - $url = $this->instanceUrl() . '/pay'; + $url = $this->instanceUrl() . '/void'; list($response, $opts) = $this->_request('post', $url, $params, $opts); $this->refreshFrom($response, $opts); return $this; diff --git a/htdocs/includes/stripe/lib/InvoiceItem.php b/htdocs/includes/stripe/lib/InvoiceItem.php index 37e39f3e105..02ca0f2d7ee 100644 --- a/htdocs/includes/stripe/lib/InvoiceItem.php +++ b/htdocs/includes/stripe/lib/InvoiceItem.php @@ -22,11 +22,16 @@ namespace Stripe; * @property int $quantity * @property string $subscription * @property string $subscription_item + * @property array $tax_rates + * @property int $unit_amount * * @package Stripe */ class InvoiceItem extends ApiResource { + + const OBJECT_NAME = "invoiceitem"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; diff --git a/htdocs/includes/stripe/lib/InvoiceLineItem.php b/htdocs/includes/stripe/lib/InvoiceLineItem.php new file mode 100644 index 00000000000..e8e8c881d5a --- /dev/null +++ b/htdocs/includes/stripe/lib/InvoiceLineItem.php @@ -0,0 +1,32 @@ +instanceUrl() . '/approve'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return Authorization The declined authorization. + */ + public function decline($params = null, $options = null) + { + $url = $this->instanceUrl() . '/decline'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/htdocs/includes/stripe/lib/Issuing/Card.php b/htdocs/includes/stripe/lib/Issuing/Card.php new file mode 100644 index 00000000000..60cc5b4e1bf --- /dev/null +++ b/htdocs/includes/stripe/lib/Issuing/Card.php @@ -0,0 +1,51 @@ +instanceUrl() . '/details'; + list($response, $opts) = $this->_request('get', $url, $params, $options); + $obj = \Stripe\Util\Util::convertToStripeObject($response, $opts); + $obj->setLastResponse($response); + return $obj; + } +} diff --git a/htdocs/includes/stripe/lib/Issuing/CardDetails.php b/htdocs/includes/stripe/lib/Issuing/CardDetails.php new file mode 100644 index 00000000000..65d3919caa4 --- /dev/null +++ b/htdocs/includes/stripe/lib/Issuing/CardDetails.php @@ -0,0 +1,21 @@ +instanceUrl() . '/cancel'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return PaymentIntent The captured payment intent. + */ + public function capture($params = null, $options = null) + { + $url = $this->instanceUrl() . '/capture'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return PaymentIntent The confirmed payment intent. + */ + public function confirm($params = null, $options = null) + { + $url = $this->instanceUrl() . '/confirm'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/htdocs/includes/stripe/lib/PaymentMethod.php b/htdocs/includes/stripe/lib/PaymentMethod.php new file mode 100644 index 00000000000..1a0bc371d5d --- /dev/null +++ b/htdocs/includes/stripe/lib/PaymentMethod.php @@ -0,0 +1,60 @@ +instanceUrl() . '/attach'; + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $opts + * + * @return PaymentMethod The detached payment method. + */ + public function detach($params = null, $opts = null) + { + $url = $this->instanceUrl() . '/detach'; + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/htdocs/includes/stripe/lib/Payout.php b/htdocs/includes/stripe/lib/Payout.php index 0849cae3f61..365d7e47ee9 100644 --- a/htdocs/includes/stripe/lib/Payout.php +++ b/htdocs/includes/stripe/lib/Payout.php @@ -8,18 +8,19 @@ namespace Stripe; * @property string $id * @property string $object * @property int $amount + * @property int $arrival_date + * @property bool $automatic * @property string $balance_transaction - * @property string $cancellation_balance_transaction * @property int $created * @property string $currency - * @property int $arrival_date + * @property string $description * @property string $destination + * @property string $failure_balance_transaction * @property string $failure_code * @property string $failure_message * @property bool $livemode * @property StripeObject $metadata * @property string $method - * @property string $recipient * @property string $source_type * @property string $statement_descriptor * @property string $status @@ -29,11 +30,56 @@ namespace Stripe; */ class Payout extends ApiResource { + + const OBJECT_NAME = "payout"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Retrieve; use ApiOperations\Update; + /** + * Types of payout failure codes. + * @link https://stripe.com/docs/api#payout_failures + */ + const FAILURE_ACCOUNT_CLOSED = 'account_closed'; + const FAILURE_ACCOUNT_FROZEN = 'account_frozen'; + const FAILURE_BANK_ACCOUNT_RESTRICTED = 'bank_account_restricted'; + const FAILURE_BANK_OWNERSHIP_CHANGED = 'bank_ownership_changed'; + const FAILURE_COULD_NOT_PROCESS = 'could_not_process'; + const FAILURE_DEBIT_NOT_AUTHORIZED = 'debit_not_authorized'; + const FAILURE_DECLINED = 'declined'; + const FAILURE_INCORRECT_ACCOUNT_HOLDER_NAME = 'incorrect_account_holder_name'; + const FAILURE_INSUFFICIENT_FUNDS = 'insufficient_funds'; + const FAILURE_INVALID_ACCOUNT_NUMBER = 'invalid_account_number'; + const FAILURE_INVALID_CURRENCY = 'invalid_currency'; + const FAILURE_NO_ACCOUNT = 'no_account'; + const FAILURE_UNSUPPORTED_CARD = 'unsupported_card'; + + /** + * Possible string representations of the payout methods. + * @link https://stripe.com/docs/api/payouts/object#payout_object-method + */ + const METHOD_STANDARD = 'standard'; + const METHOD_INSTANT = 'instant'; + + /** + * Possible string representations of the status of the payout. + * @link https://stripe.com/docs/api/payouts/object#payout_object-status + */ + const STATUS_CANCELED = 'canceled'; + const STATUS_IN_TRANSIT = 'in_transit'; + const STATUS_FAILED = 'failed'; + const STATUS_PAID = 'paid'; + const STATUS_PENDING = 'pending'; + + /** + * Possible string representations of the type of payout. + * @link https://stripe.com/docs/api/payouts/object#payout_object-type + */ + const TYPE_BANK_ACCOUNT = 'bank_account'; + const TYPE_CARD = 'card'; + /** * @return Payout The canceled payout. */ diff --git a/htdocs/includes/stripe/lib/Person.php b/htdocs/includes/stripe/lib/Person.php new file mode 100644 index 00000000000..56241c4c426 --- /dev/null +++ b/htdocs/includes/stripe/lib/Person.php @@ -0,0 +1,108 @@ +retrievePerson('person_id') instead."; + throw new Error\InvalidRequest($msg, null); + } + + /** + * @param string $_id + * @param array|null $_params + * @param array|string|null $_options + * + * @throws \Stripe\Error\InvalidRequest + */ + public static function update($_id, $_params = null, $_options = null) + { + $msg = "Persons cannot be accessed without an account ID. " . + "Retrieve a Person using \$account->retrievePerson('person_id') instead."; + throw new Error\InvalidRequest($msg, null); + } +} diff --git a/htdocs/includes/stripe/lib/Plan.php b/htdocs/includes/stripe/lib/Plan.php index 8b0126b6f2d..54a2b58eb35 100644 --- a/htdocs/includes/stripe/lib/Plan.php +++ b/htdocs/includes/stripe/lib/Plan.php @@ -9,7 +9,10 @@ namespace Stripe; * * @property string $id * @property string $object + * @property bool $active + * @property string $aggregate_usage * @property int $amount + * @property string $billing_scheme * @property int $created * @property string $currency * @property string $interval @@ -18,10 +21,17 @@ namespace Stripe; * @property StripeObject $metadata * @property string $nickname * @property string $product + * @property mixed $tiers + * @property string $tiers_mode + * @property mixed $transform_usage * @property int $trial_period_days + * @property string $usage_type */ class Plan extends ApiResource { + + const OBJECT_NAME = "plan"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; diff --git a/htdocs/includes/stripe/lib/Product.php b/htdocs/includes/stripe/lib/Product.php index 20bd4e1ae44..cb27ef42d8c 100644 --- a/htdocs/includes/stripe/lib/Product.php +++ b/htdocs/includes/stripe/lib/Product.php @@ -13,15 +13,15 @@ namespace Stripe; * @property int $created * @property string[] $deactivate_on * @property string $description - * @property array $images + * @property string[] $images * @property bool $livemode * @property StripeObject $metadata * @property string $name * @property mixed $package_dimensions * @property bool $shippable - * @property Collection $skus * @property string $statement_descriptor * @property string $type + * @property string $unit_label * @property int $updated * @property string $url * @@ -29,9 +29,19 @@ namespace Stripe; */ class Product extends ApiResource { + + const OBJECT_NAME = "product"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; use ApiOperations\Retrieve; use ApiOperations\Update; + + /** + * Possible string representations of the type of product. + * @link https://stripe.com/docs/api/service_products/object#service_product_object-type + */ + const TYPE_GOOD = 'good'; + const TYPE_SERVICE = 'service'; } diff --git a/htdocs/includes/stripe/lib/Radar/ValueList.php b/htdocs/includes/stripe/lib/Radar/ValueList.php new file mode 100644 index 00000000000..d267429b272 --- /dev/null +++ b/htdocs/includes/stripe/lib/Radar/ValueList.php @@ -0,0 +1,32 @@ +requestId = $requestId; + $this->requestDuration = $requestDuration; + } +} diff --git a/htdocs/includes/stripe/lib/Review.php b/htdocs/includes/stripe/lib/Review.php new file mode 100644 index 00000000000..a2fd5d06db3 --- /dev/null +++ b/htdocs/includes/stripe/lib/Review.php @@ -0,0 +1,57 @@ +instanceUrl() . '/approve'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/htdocs/includes/stripe/lib/SKU.php b/htdocs/includes/stripe/lib/SKU.php index 1f35da4c759..5b50df8a847 100644 --- a/htdocs/includes/stripe/lib/SKU.php +++ b/htdocs/includes/stripe/lib/SKU.php @@ -24,6 +24,9 @@ namespace Stripe; */ class SKU extends ApiResource { + + const OBJECT_NAME = "sku"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; diff --git a/htdocs/includes/stripe/lib/Sigma/ScheduledQueryRun.php b/htdocs/includes/stripe/lib/Sigma/ScheduledQueryRun.php new file mode 100644 index 00000000000..4d97bf7ce28 --- /dev/null +++ b/htdocs/includes/stripe/lib/Sigma/ScheduledQueryRun.php @@ -0,0 +1,33 @@ + "old_value"] + * + * If we update the object with `metadata[new]=new_value`, the server side + * object now has *both* fields: + * + * metadata = ["old" => "old_value", "new" => "new_value"] + * + * This is okay in itself because usually users will want to treat it as + * additive: + * + * $obj->metadata["new"] = "new_value"; + * $obj->save(); + * + * However, in other cases, they may want to replace the entire existing + * contents: + * + * $obj->metadata = ["new" => "new_value"]; + * $obj->save(); + * + * This is where things get a little bit tricky because in order to clear + * any old keys that may have existed, we actually have to send an explicit + * empty string to the server. So the operation above would have to send + * this form to get the intended behavior: + * + * metadata[old]=&metadata[new]=new_value + * + * This method allows us to track which parameters are considered additive, + * and lets us behave correctly where appropriate when serializing + * parameters to be sent. + * + * @return Util\Set Set of additive parameters + */ + public static function getAdditiveParams() + { + static $additiveParams = null; + if ($additiveParams === null) { + // Set `metadata` as additive so that when it's set directly we remember + // to clear keys that may have been previously set by sending empty + // values for them. + // + // It's possible that not every object has `metadata`, but having this + // option set when there is no `metadata` field is not harmful. + $additiveParams = new Util\Set([ + 'metadata', + ]); + } + return $additiveParams; + } + public function __construct($id = null, $opts = null) { list($id, $this->_retrieveOptions) = Util\Util::normalizeId($id); @@ -153,7 +220,7 @@ class StripeObject implements \ArrayAccess, \Countable, \JsonSerializable * @param array $values * @param null|string|array|Util\RequestOptions $opts * - * @return StripeObject The object constructed from the given values. + * @return static The object constructed from the given values. */ public static function constructFrom($values, $opts = null) { @@ -213,7 +280,7 @@ class StripeObject implements \ArrayAccess, \Countable, \JsonSerializable // This is necessary in case metadata is empty, as PHP arrays do // not differentiate between lists and hashes, and we consider // empty arrays to be lists. - if ($k === "metadata") { + if (($k === "metadata") && (is_array($v))) { $this->_values[$k] = StripeObject::constructFrom($v, $opts); } else { $this->_values[$k] = Util\Util::convertToStripeObject($v, $opts); @@ -323,7 +390,7 @@ class StripeObject implements \ArrayAccess, \Countable, \JsonSerializable } } elseif ($value instanceof StripeObject) { $update = $value->serializeParameters($force); - if ($original && $unsaved) { + if ($original && $unsaved && $key && static::getAdditiveParams()->includes($key)) { $update = array_merge(self::emptyValues($original), $update); } return $update; @@ -432,12 +499,25 @@ class StripeObject implements \ArrayAccess, \Countable, \JsonSerializable } /** - * @param ApiResponse + * Sets the last response from the Stripe API * - * @return void Set the last response from the Stripe API + * @param ApiResponse $resp + * @return void */ public function setLastResponse($resp) { $this->_lastResponse = $resp; } + + /** + * Indicates whether or not the resource has been deleted on the server. + * Note that some, but not all, resources can indicate whether they have + * been deleted. + * + * @return bool Whether the resource is deleted. + */ + public function isDeleted() + { + return isset($this->_values['deleted']) ? $this->_values['deleted'] : false; + } } diff --git a/htdocs/includes/stripe/lib/Subscription.php b/htdocs/includes/stripe/lib/Subscription.php index a5a8da1beb5..8b57d46b625 100644 --- a/htdocs/includes/stripe/lib/Subscription.php +++ b/htdocs/includes/stripe/lib/Subscription.php @@ -9,20 +9,27 @@ namespace Stripe; * @property string $object * @property float $application_fee_percent * @property string $billing + * @property int $billing_cycle_anchor + * @property mixed $billing_thresholds * @property bool $cancel_at_period_end * @property int $canceled_at * @property int $created - * @property int current_period_end - * @property int current_period_start + * @property int $current_period_end + * @property int $current_period_start * @property string $customer * @property int $days_until_due - * @property mixed $discount + * @property string $default_payment_method + * @property string $default_source + * @property array $default_tax_rates + * @property Discount $discount * @property int $ended_at * @property Collection $items + * @property string $latest_invoice * @property boolean $livemode * @property StripeObject $metadata * @property Plan $plan * @property int $quantity + * @property SubscriptionSchedule $schedule * @property int $start * @property string $status * @property float $tax_percent @@ -33,6 +40,9 @@ namespace Stripe; */ class Subscription extends ApiResource { + + const OBJECT_NAME = "subscription"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete { @@ -46,11 +56,13 @@ class Subscription extends ApiResource * * @link https://stripe.com/docs/api#subscription_object-status */ - const STATUS_ACTIVE = 'active'; - const STATUS_CANCELED = 'canceled'; - const STATUS_PAST_DUE = 'past_due'; - const STATUS_TRIALING = 'trialing'; - const STATUS_UNPAID = 'unpaid'; + const STATUS_ACTIVE = 'active'; + const STATUS_CANCELED = 'canceled'; + const STATUS_PAST_DUE = 'past_due'; + const STATUS_TRIALING = 'trialing'; + const STATUS_UNPAID = 'unpaid'; + const STATUS_INCOMPLETE = 'incomplete'; + const STATUS_INCOMPLETE_EXPIRED = 'incomplete_expired'; public static function getSavedNestedResources() { @@ -82,13 +94,4 @@ class Subscription extends ApiResource list($response, $opts) = $this->_request('delete', $url); $this->refreshFrom(['discount' => null], $opts, true); } - - public function serializeParameters($force = false) - { - $update = parent::serializeParameters($force); - if ($this->_unsavedValues->includes('items')) { - $update['items'] = $this->serializeParamsValue($this->items, null, true, $force, 'items'); - } - return $update; - } } diff --git a/htdocs/includes/stripe/lib/SubscriptionItem.php b/htdocs/includes/stripe/lib/SubscriptionItem.php index 9efc726aa66..5baa540fe98 100644 --- a/htdocs/includes/stripe/lib/SubscriptionItem.php +++ b/htdocs/includes/stripe/lib/SubscriptionItem.php @@ -7,16 +7,21 @@ namespace Stripe; * * @property string $id * @property string $object + * @property mixed $billing_thresholds * @property int $created * @property StripeObject $metadata * @property Plan $plan * @property int $quantity * @property string $subscription + * @property array $tax_rates * * @package Stripe */ class SubscriptionItem extends ApiResource { + + const OBJECT_NAME = "subscription_item"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\Delete; @@ -24,13 +29,17 @@ class SubscriptionItem extends ApiResource use ApiOperations\Update; /** - * This is a special case because the subscription items endpoint has an - * underscore in it. The parent `className` function strips underscores. + * @param array|null $params + * @param array|string|null $options * - * @return string The name of the class. + * @return Collection The list of source transactions. */ - public static function className() + public function usageRecordSummaries($params = null, $options = null) { - return 'subscription_item'; + $url = $this->instanceUrl() . '/usage_record_summaries'; + list($response, $opts) = $this->_request('get', $url, $params, $options); + $obj = Util\Util::convertToStripeObject($response, $opts); + $obj->setLastResponse($response); + return $obj; } } diff --git a/htdocs/includes/stripe/lib/SubscriptionSchedule.php b/htdocs/includes/stripe/lib/SubscriptionSchedule.php new file mode 100644 index 00000000000..ac3686f1db8 --- /dev/null +++ b/htdocs/includes/stripe/lib/SubscriptionSchedule.php @@ -0,0 +1,111 @@ +instanceUrl() . '/cancel'; + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $opts + * + * @return SubscriptionSchedule The released subscription schedule. + */ + public function release($params = null, $opts = null) + { + $url = $this->instanceUrl() . '/release'; + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return Collection The list of subscription schedule revisions. + */ + public function revisions($params = null, $options = null) + { + $url = $this->instanceUrl() . '/revisions'; + list($response, $opts) = $this->_request('get', $url, $params, $options); + $obj = Util\Util::convertToStripeObject($response, $opts); + $obj->setLastResponse($response); + return $obj; + } + + /** + * @param array|null $id The ID of the subscription schedule to which the person belongs. + * @param array|null $personId The ID of the person to retrieve. + * @param array|null $params + * @param array|string|null $opts + * + * @return Revision + */ + public static function retrieveRevision($id, $personId, $params = null, $opts = null) + { + return self::_retrieveNestedResource($id, static::PATH_REVISIONS, $personId, $params, $opts); + } + + /** + * @param array|null $id The ID of the subscription schedule on which to retrieve the persons. + * @param array|null $params + * @param array|string|null $opts + * + * @return Collection The list of revisions. + */ + public static function allRevisions($id, $params = null, $opts = null) + { + return self::_allNestedResources($id, static::PATH_REVISIONS, $params, $opts); + } +} diff --git a/htdocs/includes/stripe/lib/SubscriptionScheduleRevision.php b/htdocs/includes/stripe/lib/SubscriptionScheduleRevision.php new file mode 100644 index 00000000000..12177236530 --- /dev/null +++ b/htdocs/includes/stripe/lib/SubscriptionScheduleRevision.php @@ -0,0 +1,77 @@ +retrieveRevision('revision_id') instead."; + throw new Error\InvalidRequest($msg, null); + } + + /** + * @param array|string $_id + * @param array|string|null $_opts + * + * @throws \Stripe\Error\InvalidRequest + */ + public static function all($params = null, $opts = null) + { + $msg = "Subscription Schedule Revisions cannot be listed without a Subscription Schedule ID. " . + "List those using \$schedule->allRevisions('revision_id') instead."; + throw new Error\InvalidRequest($msg, null); + } +} diff --git a/htdocs/includes/stripe/lib/TaxId.php b/htdocs/includes/stripe/lib/TaxId.php new file mode 100644 index 00000000000..2993e2d1375 --- /dev/null +++ b/htdocs/includes/stripe/lib/TaxId.php @@ -0,0 +1,80 @@ +instanceUrl() . '/cancel'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } } diff --git a/htdocs/includes/stripe/lib/Transfer.php b/htdocs/includes/stripe/lib/Transfer.php index 87d8b79cbf3..dff2faa3329 100644 --- a/htdocs/includes/stripe/lib/Transfer.php +++ b/htdocs/includes/stripe/lib/Transfer.php @@ -12,6 +12,7 @@ namespace Stripe; * @property string $balance_transaction * @property int $created * @property string $currency + * @property string $description * @property string $destination * @property string $destination_payment * @property bool $livemode @@ -26,6 +27,9 @@ namespace Stripe; */ class Transfer extends ApiResource { + + const OBJECT_NAME = "transfer"; + use ApiOperations\All; use ApiOperations\Create; use ApiOperations\NestedResource; @@ -34,6 +38,15 @@ class Transfer extends ApiResource const PATH_REVERSALS = '/reversals'; + /** + * Possible string representations of the source type of the transfer. + * @link https://stripe.com/docs/api/transfers/object#transfer_object-source_type + */ + const SOURCE_TYPE_ALIPAY_ACCOUNT = 'alipay_account'; + const SOURCE_TYPE_BANK_ACCOUNT = 'bank_account'; + const SOURCE_TYPE_CARD = 'card'; + const SOURCE_TYPE_FINANCING = 'financing'; + /** * @return TransferReversal The created transfer reversal. */ @@ -57,7 +70,7 @@ class Transfer extends ApiResource } /** - * @param array|null $id The ID of the transfer on which to create the reversal. + * @param string|null $id The ID of the transfer on which to create the reversal. * @param array|null $params * @param array|string|null $opts * @@ -69,7 +82,7 @@ class Transfer extends ApiResource } /** - * @param array|null $id The ID of the transfer to which the reversal belongs. + * @param string|null $id The ID of the transfer to which the reversal belongs. * @param array|null $reversalId The ID of the reversal to retrieve. * @param array|null $params * @param array|string|null $opts @@ -82,7 +95,7 @@ class Transfer extends ApiResource } /** - * @param array|null $id The ID of the transfer to which the reversal belongs. + * @param string|null $id The ID of the transfer to which the reversal belongs. * @param array|null $reversalId The ID of the reversal to update. * @param array|null $params * @param array|string|null $opts @@ -95,11 +108,11 @@ class Transfer extends ApiResource } /** - * @param array|null $id The ID of the transfer on which to retrieve the reversals. + * @param string|null $id The ID of the transfer on which to retrieve the reversals. * @param array|null $params * @param array|string|null $opts * - * @return TransferReversal + * @return Collection The list of reversals. */ public static function allReversals($id, $params = null, $opts = null) { diff --git a/htdocs/includes/stripe/lib/TransferReversal.php b/htdocs/includes/stripe/lib/TransferReversal.php index cf2a3946d85..c945e5a9360 100644 --- a/htdocs/includes/stripe/lib/TransferReversal.php +++ b/htdocs/includes/stripe/lib/TransferReversal.php @@ -11,13 +11,18 @@ namespace Stripe; * @property string $balance_transaction * @property int $created * @property string $currency + * @property string $destination_payment_refund * @property StripeObject $metadata + * @property string $source_refund * @property string $transfer * * @package Stripe */ class TransferReversal extends ApiResource { + + const OBJECT_NAME = "transfer_reversal"; + use ApiOperations\Update { save as protected _save; } diff --git a/htdocs/includes/stripe/lib/UsageRecord.php b/htdocs/includes/stripe/lib/UsageRecord.php new file mode 100644 index 00000000000..a9e3a25e3e9 --- /dev/null +++ b/htdocs/includes/stripe/lib/UsageRecord.php @@ -0,0 +1,44 @@ +json, $opts); + $obj->setLastResponse($response); + return $obj; + } +} diff --git a/htdocs/includes/stripe/lib/UsageRecordSummary.php b/htdocs/includes/stripe/lib/UsageRecordSummary.php new file mode 100644 index 00000000000..b8f4aebe974 --- /dev/null +++ b/htdocs/includes/stripe/lib/UsageRecordSummary.php @@ -0,0 +1,22 @@ +container = array_map("strtolower", $initial_array); + } + + public function offsetSet($offset, $value) + { + $offset = static::maybeLowercase($offset); + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + public function offsetExists($offset) + { + $offset = static::maybeLowercase($offset); + return isset($this->container[$offset]); + } + + public function offsetUnset($offset) + { + $offset = static::maybeLowercase($offset); + unset($this->container[$offset]); + } + + public function offsetGet($offset) + { + $offset = static::maybeLowercase($offset); + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + private static function maybeLowercase($v) + { + if (is_string($v)) { + return strtolower($v); + } else { + return $v; + } + } +} diff --git a/htdocs/includes/stripe/lib/Util/RequestOptions.php b/htdocs/includes/stripe/lib/Util/RequestOptions.php index a31f4d322d9..495236224d8 100644 --- a/htdocs/includes/stripe/lib/Util/RequestOptions.php +++ b/htdocs/includes/stripe/lib/Util/RequestOptions.php @@ -16,11 +16,13 @@ class RequestOptions public $headers; public $apiKey; + public $apiBase; - public function __construct($key = null, $headers = []) + public function __construct($key = null, $headers = [], $base = null) { $this->apiKey = $key; $this->headers = $headers; + $this->apiBase = $base; } /** @@ -36,6 +38,9 @@ class RequestOptions if ($other_options->apiKey === null) { $other_options->apiKey = $this->apiKey; } + if ($other_options->apiBase === null) { + $other_options->apiBase = $this->apiBase; + } $other_options->headers = array_merge($this->headers, $other_options->headers); return $other_options; } @@ -65,16 +70,17 @@ class RequestOptions } if (is_null($options)) { - return new RequestOptions(null, []); + return new RequestOptions(null, [], null); } if (is_string($options)) { - return new RequestOptions($options, []); + return new RequestOptions($options, [], null); } if (is_array($options)) { $headers = []; $key = null; + $base = null; if (array_key_exists('api_key', $options)) { $key = $options['api_key']; } @@ -87,7 +93,10 @@ class RequestOptions if (array_key_exists('stripe_version', $options)) { $headers['Stripe-Version'] = $options['stripe_version']; } - return new RequestOptions($key, $headers); + if (array_key_exists('api_base', $options)) { + $base = $options['api_base']; + } + return new RequestOptions($key, $headers, $base); } $message = 'The second argument to Stripe API method calls is an ' diff --git a/htdocs/includes/stripe/lib/Util/Util.php b/htdocs/includes/stripe/lib/Util/Util.php index 82fd337dd34..c9cfa9fcbd2 100644 --- a/htdocs/includes/stripe/lib/Util/Util.php +++ b/htdocs/includes/stripe/lib/Util/Util.php @@ -67,50 +67,84 @@ abstract class Util { $types = [ // data structures - 'list' => 'Stripe\\Collection', + \Stripe\Collection::OBJECT_NAME => 'Stripe\\Collection', // business objects - 'account' => 'Stripe\\Account', - 'alipay_account' => 'Stripe\\AlipayAccount', - 'apple_pay_domain' => 'Stripe\\ApplePayDomain', - 'application_fee' => 'Stripe\\ApplicationFee', - 'balance' => 'Stripe\\Balance', - 'balance_transaction' => 'Stripe\\BalanceTransaction', - 'bank_account' => 'Stripe\\BankAccount', - 'bitcoin_receiver' => 'Stripe\\BitcoinReceiver', - 'bitcoin_transaction' => 'Stripe\\BitcoinTransaction', - 'card' => 'Stripe\\Card', - 'charge' => 'Stripe\\Charge', - 'country_spec' => 'Stripe\\CountrySpec', - 'coupon' => 'Stripe\\Coupon', - 'customer' => 'Stripe\\Customer', - 'dispute' => 'Stripe\\Dispute', - 'ephemeral_key' => 'Stripe\\EphemeralKey', - 'event' => 'Stripe\\Event', - 'exchange_rate' => 'Stripe\\ExchangeRate', - 'fee_refund' => 'Stripe\\ApplicationFeeRefund', - 'file_upload' => 'Stripe\\FileUpload', - 'invoice' => 'Stripe\\Invoice', - 'invoiceitem' => 'Stripe\\InvoiceItem', - 'login_link' => 'Stripe\\LoginLink', - 'order' => 'Stripe\\Order', - 'order_return' => 'Stripe\\OrderReturn', - 'payout' => 'Stripe\\Payout', - 'plan' => 'Stripe\\Plan', - 'product' => 'Stripe\\Product', - 'recipient' => 'Stripe\\Recipient', - 'recipient_transfer' => 'Stripe\\RecipientTransfer', - 'refund' => 'Stripe\\Refund', - 'sku' => 'Stripe\\SKU', - 'source' => 'Stripe\\Source', - 'source_transaction' => 'Stripe\\SourceTransaction', - 'subscription' => 'Stripe\\Subscription', - 'subscription_item' => 'Stripe\\SubscriptionItem', - 'three_d_secure' => 'Stripe\\ThreeDSecure', - 'token' => 'Stripe\\Token', - 'topup' => 'Stripe\\Topup', - 'transfer' => 'Stripe\\Transfer', - 'transfer_reversal' => 'Stripe\\TransferReversal', + \Stripe\Account::OBJECT_NAME => 'Stripe\\Account', + \Stripe\AccountLink::OBJECT_NAME => 'Stripe\\AccountLink', + \Stripe\AlipayAccount::OBJECT_NAME => 'Stripe\\AlipayAccount', + \Stripe\ApplePayDomain::OBJECT_NAME => 'Stripe\\ApplePayDomain', + \Stripe\ApplicationFee::OBJECT_NAME => 'Stripe\\ApplicationFee', + \Stripe\Balance::OBJECT_NAME => 'Stripe\\Balance', + \Stripe\BalanceTransaction::OBJECT_NAME => 'Stripe\\BalanceTransaction', + \Stripe\BankAccount::OBJECT_NAME => 'Stripe\\BankAccount', + \Stripe\BitcoinReceiver::OBJECT_NAME => 'Stripe\\BitcoinReceiver', + \Stripe\BitcoinTransaction::OBJECT_NAME => 'Stripe\\BitcoinTransaction', + \Stripe\Card::OBJECT_NAME => 'Stripe\\Card', + \Stripe\Charge::OBJECT_NAME => 'Stripe\\Charge', + \Stripe\Checkout\Session::OBJECT_NAME => 'Stripe\\Checkout\\Session', + \Stripe\CountrySpec::OBJECT_NAME => 'Stripe\\CountrySpec', + \Stripe\Coupon::OBJECT_NAME => 'Stripe\\Coupon', + \Stripe\CreditNote::OBJECT_NAME => 'Stripe\\CreditNote', + \Stripe\Customer::OBJECT_NAME => 'Stripe\\Customer', + \Stripe\Discount::OBJECT_NAME => 'Stripe\\Discount', + \Stripe\Dispute::OBJECT_NAME => 'Stripe\\Dispute', + \Stripe\EphemeralKey::OBJECT_NAME => 'Stripe\\EphemeralKey', + \Stripe\Event::OBJECT_NAME => 'Stripe\\Event', + \Stripe\ExchangeRate::OBJECT_NAME => 'Stripe\\ExchangeRate', + \Stripe\ApplicationFeeRefund::OBJECT_NAME => 'Stripe\\ApplicationFeeRefund', + \Stripe\File::OBJECT_NAME => 'Stripe\\File', + \Stripe\File::OBJECT_NAME_ALT => 'Stripe\\File', + \Stripe\FileLink::OBJECT_NAME => 'Stripe\\FileLink', + \Stripe\Invoice::OBJECT_NAME => 'Stripe\\Invoice', + \Stripe\InvoiceItem::OBJECT_NAME => 'Stripe\\InvoiceItem', + \Stripe\InvoiceLineItem::OBJECT_NAME => 'Stripe\\InvoiceLineItem', + \Stripe\IssuerFraudRecord::OBJECT_NAME => 'Stripe\\IssuerFraudRecord', + \Stripe\Issuing\Authorization::OBJECT_NAME => 'Stripe\\Issuing\\Authorization', + \Stripe\Issuing\Card::OBJECT_NAME => 'Stripe\\Issuing\\Card', + \Stripe\Issuing\CardDetails::OBJECT_NAME => 'Stripe\\Issuing\\CardDetails', + \Stripe\Issuing\Cardholder::OBJECT_NAME => 'Stripe\\Issuing\\Cardholder', + \Stripe\Issuing\Dispute::OBJECT_NAME => 'Stripe\\Issuing\\Dispute', + \Stripe\Issuing\Transaction::OBJECT_NAME => 'Stripe\\Issuing\\Transaction', + \Stripe\LoginLink::OBJECT_NAME => 'Stripe\\LoginLink', + \Stripe\Order::OBJECT_NAME => 'Stripe\\Order', + \Stripe\OrderItem::OBJECT_NAME => 'Stripe\\OrderItem', + \Stripe\OrderReturn::OBJECT_NAME => 'Stripe\\OrderReturn', + \Stripe\PaymentIntent::OBJECT_NAME => 'Stripe\\PaymentIntent', + \Stripe\PaymentMethod::OBJECT_NAME => 'Stripe\\PaymentMethod', + \Stripe\Payout::OBJECT_NAME => 'Stripe\\Payout', + \Stripe\Person::OBJECT_NAME => 'Stripe\\Person', + \Stripe\Plan::OBJECT_NAME => 'Stripe\\Plan', + \Stripe\Product::OBJECT_NAME => 'Stripe\\Product', + \Stripe\Radar\ValueList::OBJECT_NAME => 'Stripe\\Radar\\ValueList', + \Stripe\Radar\ValueListItem::OBJECT_NAME => 'Stripe\\Radar\\ValueListItem', + \Stripe\Recipient::OBJECT_NAME => 'Stripe\\Recipient', + \Stripe\RecipientTransfer::OBJECT_NAME => 'Stripe\\RecipientTransfer', + \Stripe\Refund::OBJECT_NAME => 'Stripe\\Refund', + \Stripe\Reporting\ReportRun::OBJECT_NAME => 'Stripe\\Reporting\\ReportRun', + \Stripe\Reporting\ReportType::OBJECT_NAME => 'Stripe\\Reporting\\ReportType', + \Stripe\Review::OBJECT_NAME => 'Stripe\\Review', + \Stripe\SKU::OBJECT_NAME => 'Stripe\\SKU', + \Stripe\Sigma\ScheduledQueryRun::OBJECT_NAME => 'Stripe\\Sigma\\ScheduledQueryRun', + \Stripe\Source::OBJECT_NAME => 'Stripe\\Source', + \Stripe\SourceTransaction::OBJECT_NAME => 'Stripe\\SourceTransaction', + \Stripe\Subscription::OBJECT_NAME => 'Stripe\\Subscription', + \Stripe\SubscriptionItem::OBJECT_NAME => 'Stripe\\SubscriptionItem', + \Stripe\SubscriptionSchedule::OBJECT_NAME => 'Stripe\\SubscriptionSchedule', + \Stripe\SubscriptionScheduleRevision::OBJECT_NAME => 'Stripe\\SubscriptionScheduleRevision', + \Stripe\TaxId::OBJECT_NAME => 'Stripe\\TaxId', + \Stripe\TaxRate::OBJECT_NAME => 'Stripe\\TaxRate', + \Stripe\ThreeDSecure::OBJECT_NAME => 'Stripe\\ThreeDSecure', + \Stripe\Terminal\ConnectionToken::OBJECT_NAME => 'Stripe\\Terminal\\ConnectionToken', + \Stripe\Terminal\Location::OBJECT_NAME => 'Stripe\\Terminal\\Location', + \Stripe\Terminal\Reader::OBJECT_NAME => 'Stripe\\Terminal\\Reader', + \Stripe\Token::OBJECT_NAME => 'Stripe\\Token', + \Stripe\Topup::OBJECT_NAME => 'Stripe\\Topup', + \Stripe\Transfer::OBJECT_NAME => 'Stripe\\Transfer', + \Stripe\TransferReversal::OBJECT_NAME => 'Stripe\\TransferReversal', + \Stripe\UsageRecord::OBJECT_NAME => 'Stripe\\UsageRecord', + \Stripe\UsageRecordSummary::OBJECT_NAME => 'Stripe\\UsageRecordSummary', + \Stripe\WebhookEndpoint::OBJECT_NAME => 'Stripe\\WebhookEndpoint', ]; if (self::isList($resp)) { $mapped = []; @@ -186,42 +220,117 @@ abstract class Util } /** - * @param array $arr A map of param keys to values. - * @param string|null $prefix + * Recursively goes through an array of parameters. If a parameter is an instance of + * ApiResource, then it is replaced by the resource's ID. + * Also clears out null values. * - * @return string A querystring, essentially. + * @param mixed $h + * @return mixed */ - public static function urlEncode($arr, $prefix = null) + public static function objectsToIds($h) { - if (!is_array($arr)) { - return $arr; + if ($h instanceof \Stripe\ApiResource) { + return $h->id; + } elseif (static::isList($h)) { + $results = []; + foreach ($h as $v) { + array_push($results, static::objectsToIds($v)); + } + return $results; + } elseif (is_array($h)) { + $results = []; + foreach ($h as $k => $v) { + if (is_null($v)) { + continue; + } + $results[$k] = static::objectsToIds($v); + } + return $results; + } else { + return $h; } + } - $r = []; - foreach ($arr as $k => $v) { - if (is_null($v)) { - continue; - } + /** + * @param array $params + * + * @return string + */ + public static function encodeParameters($params) + { + $flattenedParams = self::flattenParams($params); + $pieces = []; + foreach ($flattenedParams as $param) { + list($k, $v) = $param; + array_push($pieces, self::urlEncode($k) . '=' . self::urlEncode($v)); + } + return implode('&', $pieces); + } - if ($prefix) { - if ($k !== null && (!is_int($k) || is_array($v))) { - $k = $prefix."[".$k."]"; - } else { - $k = $prefix."[]"; - } - } + /** + * @param array $params + * @param string|null $parentKey + * + * @return array + */ + public static function flattenParams($params, $parentKey = null) + { + $result = []; - if (is_array($v)) { - $enc = self::urlEncode($v, $k); - if ($enc) { - $r[] = $enc; - } + foreach ($params as $key => $value) { + $calculatedKey = $parentKey ? "{$parentKey}[{$key}]" : $key; + + if (self::isList($value)) { + $result = array_merge($result, self::flattenParamsList($value, $calculatedKey)); + } elseif (is_array($value)) { + $result = array_merge($result, self::flattenParams($value, $calculatedKey)); } else { - $r[] = urlencode($k)."=".urlencode($v); + array_push($result, [$calculatedKey, $value]); } } - return implode("&", $r); + return $result; + } + + /** + * @param array $value + * @param string $calculatedKey + * + * @return array + */ + public static function flattenParamsList($value, $calculatedKey) + { + $result = []; + + foreach ($value as $i => $elem) { + if (self::isList($elem)) { + $result = array_merge($result, self::flattenParamsList($elem, $calculatedKey)); + } elseif (is_array($elem)) { + $result = array_merge($result, self::flattenParams($elem, "{$calculatedKey}[{$i}]")); + } else { + array_push($result, ["{$calculatedKey}[{$i}]", $elem]); + } + } + + return $result; + } + + /** + * @param string $key A string to URL-encode. + * + * @return string The URL-encoded string. + */ + public static function urlEncode($key) + { + $s = urlencode($key); + + // Don't use strict form encoding by changing the square bracket control + // characters back to their literals. This is fine by the server, and + // makes these parameter strings easier to read. + $s = str_replace('%5B', '[', $s); + $s = str_replace('%5D', ']', $s); + + return $s; } public static function normalizeId($id) @@ -235,4 +344,14 @@ abstract class Util } return [$id, $params]; } + + /** + * Returns UNIX timestamp in milliseconds + * + * @return integer current time in millis + */ + public static function currentTimeMillis() + { + return (int) round(microtime(true) * 1000); + } } diff --git a/htdocs/includes/stripe/lib/WebhookEndpoint.php b/htdocs/includes/stripe/lib/WebhookEndpoint.php new file mode 100644 index 00000000000..27ecacf690c --- /dev/null +++ b/htdocs/includes/stripe/lib/WebhookEndpoint.php @@ -0,0 +1,29 @@ + - - - tests - - - - - lib - - - - - - diff --git a/htdocs/includes/stripe/phpunit.xml b/htdocs/includes/stripe/phpunit.xml deleted file mode 100644 index 7a73276d0b1..00000000000 --- a/htdocs/includes/stripe/phpunit.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - tests - - - - - lib - - - - - - diff --git a/htdocs/includes/stripe/tests/Stripe/AccountTest.php b/htdocs/includes/stripe/tests/Stripe/AccountTest.php deleted file mode 100644 index 4c621690dcf..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/AccountTest.php +++ /dev/null @@ -1,365 +0,0 @@ -expectsRequest( - 'get', - '/v1/accounts' - ); - $resources = Account::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Account", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/accounts/' . self::TEST_RESOURCE_ID - ); - $resource = Account::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Account", $resource); - } - - public function testIsRetrievableWithoutId() - { - $this->expectsRequest( - 'get', - '/v1/account' - ); - $resource = Account::retrieve(); - $this->assertInstanceOf("Stripe\\Account", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/accounts' - ); - $resource = Account::create(["type" => "custom"]); - $this->assertInstanceOf("Stripe\\Account", $resource); - } - - public function testIsSaveable() - { - $resource = Account::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/accounts/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Account", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/accounts/' . self::TEST_RESOURCE_ID - ); - $resource = Account::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Account", $resource); - } - - public function testIsDeletable() - { - $resource = Account::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/accounts/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Account", $resource); - } - - public function testIsRejectable() - { - $account = Account::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/accounts/' . $account->id . '/reject' - ); - $resource = $account->reject(["reason" => "fraud"]); - $this->assertInstanceOf("Stripe\\Account", $resource); - $this->assertSame($resource, $account); - } - - public function testIsDeauthorizable() - { - $resource = Account::retrieve(self::TEST_RESOURCE_ID); - $this->stubRequest( - 'post', - '/oauth/deauthorize', - [ - 'client_id' => Stripe::getClientId(), - 'stripe_user_id' => $resource->id, - ], - null, - false, - [ - 'stripe_user_id' => $resource->id, - ], - 200, - Stripe::$connectBase - ); - $resource->deauthorize(); - } - - public function testCanCreateExternalAccount() - { - $this->expectsRequest( - 'post', - '/v1/accounts/' . self::TEST_RESOURCE_ID . '/external_accounts' - ); - $resource = Account::createExternalAccount(self::TEST_RESOURCE_ID, [ - "external_account" => "btok_123", - ]); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanRetrieveExternalAccount() - { - $this->expectsRequest( - 'get', - '/v1/accounts/' . self::TEST_RESOURCE_ID . '/external_accounts/' . self::TEST_EXTERNALACCOUNT_ID - ); - $resource = Account::retrieveExternalAccount(self::TEST_RESOURCE_ID, self::TEST_EXTERNALACCOUNT_ID); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanUpdateExternalAccount() - { - $this->expectsRequest( - 'post', - '/v1/accounts/' . self::TEST_RESOURCE_ID . '/external_accounts/' . self::TEST_EXTERNALACCOUNT_ID - ); - $resource = Account::updateExternalAccount(self::TEST_RESOURCE_ID, self::TEST_EXTERNALACCOUNT_ID, [ - "name" => "name", - ]); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanDeleteExternalAccount() - { - $this->expectsRequest( - 'delete', - '/v1/accounts/' . self::TEST_RESOURCE_ID . '/external_accounts/' . self::TEST_EXTERNALACCOUNT_ID - ); - $resource = Account::deleteExternalAccount(self::TEST_RESOURCE_ID, self::TEST_EXTERNALACCOUNT_ID); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanListExternalAccounts() - { - $this->expectsRequest( - 'get', - '/v1/accounts/' . self::TEST_RESOURCE_ID . '/external_accounts' - ); - $resources = Account::allExternalAccounts(self::TEST_RESOURCE_ID); - $this->assertTrue(is_array($resources->data)); - } - - public function testCanCreateLoginLink() - { - $this->expectsRequest( - 'post', - '/v1/accounts/' . self::TEST_RESOURCE_ID . '/login_links' - ); - $resource = Account::createLoginLink(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\LoginLink", $resource); - } - - public function testSerializeNewAdditionalOwners() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - 'legal_entity' => StripeObject::constructFrom([]), - ], null); - $obj->legal_entity->additional_owners = [ - ['first_name' => 'Joe'], - ['first_name' => 'Jane'], - ]; - - $expected = [ - 'legal_entity' => [ - 'additional_owners' => [ - 0 => ['first_name' => 'Joe'], - 1 => ['first_name' => 'Jane'], - ], - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializePartiallyChangedAdditionalOwners() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - 'legal_entity' => [ - 'additional_owners' => [ - StripeObject::constructFrom(['first_name' => 'Joe']), - StripeObject::constructFrom(['first_name' => 'Jane']), - ], - ], - ], null); - $obj->legal_entity->additional_owners[1]->first_name = 'Stripe'; - - $expected = [ - 'legal_entity' => [ - 'additional_owners' => [ - 1 => ['first_name' => 'Stripe'], - ], - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializeUnchangedAdditionalOwners() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - 'legal_entity' => [ - 'additional_owners' => [ - StripeObject::constructFrom(['first_name' => 'Joe']), - StripeObject::constructFrom(['first_name' => 'Jane']), - ], - ], - ], null); - - $expected = [ - 'legal_entity' => [ - 'additional_owners' => [], - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializeUnsetAdditionalOwners() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - 'legal_entity' => [ - 'additional_owners' => [ - StripeObject::constructFrom(['first_name' => 'Joe']), - StripeObject::constructFrom(['first_name' => 'Jane']), - ], - ], - ], null); - $obj->legal_entity->additional_owners = null; - - // Note that the empty string that we send for this one has a special - // meaning for the server, which interprets it as an array unset. - $expected = [ - 'legal_entity' => [ - 'additional_owners' => '', - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testSerializeAdditionalOwnersDeletedItem() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - 'legal_entity' => [ - 'additional_owners' => [ - StripeObject::constructFrom(['first_name' => 'Joe']), - StripeObject::constructFrom(['first_name' => 'Jane']), - ], - ], - ], null); - unset($obj->legal_entity->additional_owners[0]); - - $obj->serializeParameters(); - } - - public function testSerializeExternalAccountString() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - ], null); - $obj->external_account = 'btok_123'; - - $expected = [ - 'external_account' => 'btok_123', - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializeExternalAccountHash() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - ], null); - $obj->external_account = [ - 'object' => 'bank_account', - 'routing_number' => '110000000', - 'account_number' => '000123456789', - 'country' => 'US', - 'currency' => 'usd', - ]; - - $expected = [ - 'external_account' => [ - 'object' => 'bank_account', - 'routing_number' => '110000000', - 'account_number' => '000123456789', - 'country' => 'US', - 'currency' => 'usd', - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializeBankAccountString() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - ], null); - $obj->bank_account = 'btok_123'; - - $expected = [ - 'bank_account' => 'btok_123', - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializeBankAccountHash() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'account', - ], null); - $obj->bank_account = [ - 'object' => 'bank_account', - 'routing_number' => '110000000', - 'account_number' => '000123456789', - 'country' => 'US', - 'currency' => 'usd', - ]; - - $expected = [ - 'bank_account' => [ - 'object' => 'bank_account', - 'routing_number' => '110000000', - 'account_number' => '000123456789', - 'country' => 'US', - 'currency' => 'usd', - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/AlipayAccountTest.php b/htdocs/includes/stripe/tests/Stripe/AlipayAccountTest.php deleted file mode 100644 index 7159f5444df..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/AlipayAccountTest.php +++ /dev/null @@ -1,76 +0,0 @@ - self::TEST_RESOURCE_ID, - 'object' => 'card', - 'metadata' => [], - ]; - return AlipayAccount::constructFrom( - array_merge($params, $base), - new Util\RequestOptions() - ); - } - - public function testHasCorrectUrlForCustomer() - { - $resource = $this->createFixture(['customer' => 'cus_123']); - $this->assertSame( - "/v1/customers/cus_123/sources/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - /** - * @expectedException \Stripe\Error\InvalidRequest - */ - public function testIsNotDirectlyRetrievable() - { - AlipayAccount::retrieve(self::TEST_RESOURCE_ID); - } - - public function testIsSaveable() - { - $resource = $this->createFixture(); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID - ); - $resource->save(); - $this->assertSame("Stripe\\AlipayAccount", get_class($resource)); - } - - /** - * @expectedException \Stripe\Error\InvalidRequest - */ - public function testIsNotDirectlyUpdatable() - { - AlipayAccount::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - } - - public function testIsDeletable() - { - $resource = $this->createFixture(); - $this->expectsRequest( - 'delete', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID - ); - $resource->delete(); - $this->assertSame("Stripe\\AlipayAccount", get_class($resource)); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ApiRequestorTest.php b/htdocs/includes/stripe/tests/Stripe/ApiRequestorTest.php deleted file mode 100644 index 6fb8229c57d..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ApiRequestorTest.php +++ /dev/null @@ -1,572 +0,0 @@ -getMethod('_encodeObjects'); - $method->setAccessible(true); - - $a = ['customer' => new Customer('abcd')]; - $enc = $method->invoke(null, $a); - $this->assertSame($enc, ['customer' => 'abcd']); - - // Preserves UTF-8 - $v = ['customer' => "☃"]; - $enc = $method->invoke(null, $v); - $this->assertSame($enc, $v); - - // Encodes latin-1 -> UTF-8 - $v = ['customer' => "\xe9"]; - $enc = $method->invoke(null, $v); - $this->assertSame($enc, ['customer' => "\xc3\xa9"]); - - // Encodes booleans - $v = true; - $enc = $method->invoke(null, $v); - $this->assertSame('true', $enc); - - $v = false; - $enc = $method->invoke(null, $v); - $this->assertSame('false', $enc); - } - - public function testHttpClientInjection() - { - $reflector = new \ReflectionClass('Stripe\\ApiRequestor'); - $method = $reflector->getMethod('httpClient'); - $method->setAccessible(true); - - $curl = new CurlClient(); - $curl->setTimeout(10); - ApiRequestor::setHttpClient($curl); - - $injectedCurl = $method->invoke(new ApiRequestor()); - $this->assertSame($injectedCurl, $curl); - } - - public function testDefaultHeaders() - { - $reflector = new \ReflectionClass('Stripe\\ApiRequestor'); - $method = $reflector->getMethod('_defaultHeaders'); - $method->setAccessible(true); - - // no way to stub static methods with PHPUnit 4.x :( - Stripe::setAppInfo('MyTestApp', '1.2.34', 'https://mytestapp.example'); - $apiKey = 'sk_test_notarealkey'; - $clientInfo = ['httplib' => 'testlib 0.1.2']; - - $headers = $method->invoke(null, $apiKey, $clientInfo); - - $ua = json_decode($headers['X-Stripe-Client-User-Agent']); - $this->assertSame($ua->application->name, 'MyTestApp'); - $this->assertSame($ua->application->version, '1.2.34'); - $this->assertSame($ua->application->url, 'https://mytestapp.example'); - - $this->assertSame($ua->httplib, 'testlib 0.1.2'); - - $this->assertSame( - $headers['User-Agent'], - 'Stripe/v1 PhpBindings/' . Stripe::VERSION . ' MyTestApp/1.2.34 (https://mytestapp.example)' - ); - - $this->assertSame($headers['Authorization'], 'Bearer ' . $apiKey); - } - - /** - * @expectedException \Stripe\Error\Authentication - * @expectedExceptionMessageRegExp #No API key provided# - */ - public function testRaisesAuthenticationErrorWhenNoApiKey() - { - Stripe::setApiKey(null); - Charge::create(); - } - - public function testRaisesInvalidRequestErrorOn400() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - null, - false, - [ - 'error' => [ - 'type' => 'invalid_request_error', - 'message' => 'Missing id', - 'param' => 'id', - ], - ], - 400 - ); - - try { - Charge::create(); - $this->fail("Did not raise error"); - } catch (Error\InvalidRequest $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame('Missing id', $e->getMessage()); - $this->assertSame('id', $e->getStripeParam()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesIdempotencyErrorOn400AndTypeIdempotencyError() - { - $this->stubRequest( - 'POST', - '/v1/charges', - array(), - null, - false, - array( - 'error' => array( - 'type' => 'idempotency_error', - 'message' => "Keys for idempotent requests can only be used with the same parameters they were first used with. Try using a key other than 'abc' if you meant to execute a different request.", - ), - ), - 400 - ); - - try { - Charge::create(); - $this->fail("Did not raise error"); - } catch (Error\Idempotency $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame("Keys for idempotent requests can only be used with the same parameters they were first used with. Try using a key other than 'abc' if you meant to execute a different request.", $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesAuthenticationErrorOn401() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - null, - false, - [ - 'error' => [ - 'type' => 'invalid_request_error', - 'message' => 'You did not provide an API key.', - ], - ], - 401 - ); - - try { - Charge::create(); - $this->fail("Did not raise error"); - } catch (Error\Authentication $e) { - $this->assertSame(401, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame('You did not provide an API key.', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesCardErrorOn402() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - null, - false, - [ - 'error' => [ - 'type' => 'card_error', - 'message' => 'Your card was declined.', - 'code' => 'card_declined', - 'decline_code' => 'generic_decline', - 'charge' => 'ch_declined_charge', - 'param' => 'exp_month', - ], - ], - 402 - ); - - try { - Charge::create(); - $this->fail("Did not raise error"); - } catch (Error\Card $e) { - $this->assertSame(402, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame('Your card was declined.', $e->getMessage()); - $this->assertSame('card_declined', $e->getStripeCode()); - $this->assertSame('generic_decline', $e->getDeclineCode()); - $this->assertSame('exp_month', $e->getStripeParam()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesPermissionErrorOn403() - { - $this->stubRequest( - 'GET', - '/v1/accounts/foo', - [], - null, - false, - [ - 'error' => [ - 'type' => 'invalid_request_error', - 'message' => "The provided key 'sk_test_********************1234' does not have access to account 'foo' (or that account does not exist). Application access may have been revoked.", - ], - ], - 403 - ); - - try { - Account::retrieve('foo'); - $this->fail("Did not raise error"); - } catch (Error\Permission $e) { - $this->assertSame(403, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame("The provided key 'sk_test_********************1234' does not have access to account 'foo' (or that account does not exist). Application access may have been revoked.", $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesInvalidRequestErrorOn404() - { - $this->stubRequest( - 'GET', - '/v1/charges/foo', - [], - null, - false, - [ - 'error' => [ - 'type' => 'invalid_request_error', - 'message' => 'No such charge: foo', - 'param' => 'id', - ], - ], - 404 - ); - - try { - Charge::retrieve('foo'); - $this->fail("Did not raise error"); - } catch (Error\InvalidRequest $e) { - $this->assertSame(404, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame('No such charge: foo', $e->getMessage()); - $this->assertSame('id', $e->getStripeParam()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesRateLimitErrorOn429() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - null, - false, - [ - 'error' => [ - 'message' => 'Too many requests', - ], - ], - 429 - ); - - try { - Charge::create(); - $this->fail("Did not raise error"); - } catch (Error\RateLimit $e) { - $this->assertSame(429, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame('Too many requests', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesRateLimitErrorOn400AndCodeRateLimit() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - null, - false, - [ - 'error' => [ - 'code' => 'rate_limit', - 'message' => 'Too many requests', - ], - ], - 400 - ); - - try { - Charge::create(); - $this->fail("Did not raise error"); - } catch (Error\RateLimit $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertTrue(is_array($e->getJsonBody())); - $this->assertSame('Too many requests', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesOAuthInvalidRequestError() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [], - null, - false, - [ - 'error' => 'invalid_request', - 'error_description' => 'No grant type specified', - ], - 400, - Stripe::$connectBase - ); - - try { - OAuth::token(); - $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidRequest $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('invalid_request', $e->getErrorCode()); - $this->assertSame('No grant type specified', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesOAuthInvalidClientError() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [], - null, - false, - [ - 'error' => 'invalid_client', - 'error_description' => 'No authentication was provided. Send your secret API key using the Authorization header, or as a client_secret POST parameter.', - ], - 401, - Stripe::$connectBase - ); - - try { - OAuth::token(); - $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidClient $e) { - $this->assertSame(401, $e->getHttpStatus()); - $this->assertSame('invalid_client', $e->getErrorCode()); - $this->assertSame('No authentication was provided. Send your secret API key using the Authorization header, or as a client_secret POST parameter.', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesOAuthInvalidGrantError() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [], - null, - false, - [ - 'error' => 'invalid_grant', - 'error_description' => 'This authorization code has already been used. All tokens issued with this code have been revoked.', - ], - 400, - Stripe::$connectBase - ); - - try { - OAuth::token(); - $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidGrant $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('invalid_grant', $e->getErrorCode()); - $this->assertSame('This authorization code has already been used. All tokens issued with this code have been revoked.', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesOAuthInvalidScopeError() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [], - null, - false, - [ - 'error' => 'invalid_scope', - 'error_description' => 'Invalid scope provided: invalid_scope.', - ], - 400, - Stripe::$connectBase - ); - - try { - OAuth::token(); - $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidScope $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('invalid_scope', $e->getErrorCode()); - $this->assertSame('Invalid scope provided: invalid_scope.', $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesOAuthUnsupportedGrantTypeError() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [], - null, - false, - [ - 'error' => 'unsupported_grant_type', - ], - 400, - Stripe::$connectBase - ); - - try { - OAuth::token(); - $this->fail("Did not raise error"); - } catch (Error\OAuth\UnsupportedGrantType $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('unsupported_grant_type', $e->getErrorCode()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testRaisesOAuthUnsupportedResponseTypeError() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [], - null, - false, - [ - 'error' => 'unsupported_response_type', - 'error_description' => "Only 'code' response_type is supported, but 'unsupported_response_type' was provided", - ], - 400, - Stripe::$connectBase - ); - - try { - OAuth::token(); - $this->fail("Did not raise error"); - } catch (Error\OAuth\UnsupportedResponseType $e) { - $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('unsupported_response_type', $e->getErrorCode()); - $this->assertSame("Only 'code' response_type is supported, but 'unsupported_response_type' was provided", $e->getMessage()); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testHeaderStripeVersionGlobal() - { - Stripe::setApiVersion('2222-22-22'); - $this->stubRequest( - 'POST', - '/v1/charges', - [], - [ - 'Stripe-Version: 2222-22-22', - ], - false, - [ - 'id' => 'ch_123', - 'object' => 'charge', - ] - ); - Charge::create(); - } - - public function testHeaderStripeVersionRequestOptions() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - [ - 'Stripe-Version: 2222-22-22', - ], - false, - [ - 'id' => 'ch_123', - 'object' => 'charge', - ] - ); - Charge::create([], ['stripe_version' => '2222-22-22']); - } - - public function testHeaderStripeAccountGlobal() - { - Stripe::setAccountId('acct_123'); - $this->stubRequest( - 'POST', - '/v1/charges', - [], - [ - 'Stripe-Account: acct_123', - ], - false, - [ - 'id' => 'ch_123', - 'object' => 'charge', - ] - ); - Charge::create(); - } - - public function testHeaderStripeAccountRequestOptions() - { - $this->stubRequest( - 'POST', - '/v1/charges', - [], - [ - 'Stripe-Account: acct_123', - ], - false, - [ - 'id' => 'ch_123', - 'object' => 'charge', - ] - ); - Charge::create([], ['stripe_account' => 'acct_123']); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ApplePayDomainTest.php b/htdocs/includes/stripe/tests/Stripe/ApplePayDomainTest.php deleted file mode 100644 index d033f55cbb0..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ApplePayDomainTest.php +++ /dev/null @@ -1,52 +0,0 @@ -expectsRequest( - 'get', - '/v1/apple_pay/domains' - ); - $resources = ApplePayDomain::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\ApplePayDomain", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/apple_pay/domains/' . self::TEST_RESOURCE_ID - ); - $resource = ApplePayDomain::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\ApplePayDomain", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/apple_pay/domains' - ); - $resource = ApplePayDomain::create([ - "domain_name" => "domain", - ]); - $this->assertInstanceOf("Stripe\\ApplePayDomain", $resource); - } - - public function testIsDeletable() - { - $resource = ApplePayDomain::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/apple_pay/domains/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\ApplePayDomain", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ApplicationFeeRefundTest.php b/htdocs/includes/stripe/tests/Stripe/ApplicationFeeRefundTest.php deleted file mode 100644 index 9af059ff7f3..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ApplicationFeeRefundTest.php +++ /dev/null @@ -1,21 +0,0 @@ -metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/application_fees/' . $resource->fee . '/refunds/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\ApplicationFeeRefund", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ApplicationFeeTest.php b/htdocs/includes/stripe/tests/Stripe/ApplicationFeeTest.php deleted file mode 100644 index 66e007ff3d2..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ApplicationFeeTest.php +++ /dev/null @@ -1,83 +0,0 @@ -expectsRequest( - 'get', - '/v1/application_fees' - ); - $resources = ApplicationFee::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\ApplicationFee", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/application_fees/' . self::TEST_RESOURCE_ID - ); - $resource = ApplicationFee::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\ApplicationFee", $resource); - } - - public function testIsRefundable() - { - $fee = ApplicationFee::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/application_fees/' . $fee->id . '/refunds' - ); - $resource = $fee->refund(); - $this->assertInstanceOf("Stripe\\ApplicationFee", $resource); - $this->assertSame($resource, $fee); - } - - public function testCanCreateRefund() - { - $this->expectsRequest( - 'post', - '/v1/application_fees/' . self::TEST_RESOURCE_ID . '/refunds' - ); - $resource = ApplicationFee::createRefund(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\ApplicationFeeRefund", $resource); - } - - public function testCanRetrieveRefund() - { - $this->expectsRequest( - 'get', - '/v1/application_fees/' . self::TEST_RESOURCE_ID . '/refunds/' . self::TEST_FEEREFUND_ID - ); - $resource = ApplicationFee::retrieveRefund(self::TEST_RESOURCE_ID, self::TEST_FEEREFUND_ID); - $this->assertInstanceOf("Stripe\\ApplicationFeeRefund", $resource); - } - - public function testCanUpdateRefund() - { - $this->expectsRequest( - 'post', - '/v1/application_fees/' . self::TEST_RESOURCE_ID . '/refunds/' . self::TEST_FEEREFUND_ID - ); - $resource = ApplicationFee::updateRefund(self::TEST_RESOURCE_ID, self::TEST_FEEREFUND_ID); - $this->assertInstanceOf("Stripe\\ApplicationFeeRefund", $resource); - } - - public function testCanListRefunds() - { - $this->expectsRequest( - 'get', - '/v1/application_fees/' . self::TEST_RESOURCE_ID . '/refunds' - ); - $resources = ApplicationFee::allRefunds(self::TEST_RESOURCE_ID); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\ApplicationFeeRefund", $resources->data[0]); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/BalanceTest.php b/htdocs/includes/stripe/tests/Stripe/BalanceTest.php deleted file mode 100644 index ccbdbdfb747..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/BalanceTest.php +++ /dev/null @@ -1,16 +0,0 @@ -expectsRequest( - 'get', - '/v1/balance' - ); - $resource = Balance::retrieve(); - $this->assertInstanceOf("Stripe\\Balance", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/BalanceTransactionTest.php b/htdocs/includes/stripe/tests/Stripe/BalanceTransactionTest.php deleted file mode 100644 index 8785e859113..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/BalanceTransactionTest.php +++ /dev/null @@ -1,29 +0,0 @@ -expectsRequest( - 'get', - '/v1/balance/history' - ); - $resources = BalanceTransaction::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\BalanceTransaction", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/balance/history/' . self::TEST_RESOURCE_ID - ); - $resource = BalanceTransaction::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\BalanceTransaction", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/BankAccountTest.php b/htdocs/includes/stripe/tests/Stripe/BankAccountTest.php deleted file mode 100644 index ab1dff9d5a8..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/BankAccountTest.php +++ /dev/null @@ -1,99 +0,0 @@ - self::TEST_RESOURCE_ID, - 'object' => 'bank_account', - 'metadata' => [], - ]; - return BankAccount::constructFrom( - array_merge($params, $base), - new Util\RequestOptions() - ); - } - - public function testHasCorrectUrlForCustomer() - { - $resource = $this->createFixture(['customer' => 'cus_123']); - $this->assertSame( - "/v1/customers/cus_123/sources/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - public function testHasCorrectUrlForAccount() - { - $resource = $this->createFixture(['account' => 'acct_123']); - $this->assertSame( - "/v1/accounts/acct_123/external_accounts/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - /** - * @expectedException \Stripe\Error\InvalidRequest - */ - public function testIsNotDirectlyRetrievable() - { - BankAccount::retrieve(self::TEST_RESOURCE_ID); - } - - public function testIsSaveable() - { - $resource = $this->createFixture(); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID - ); - $resource->save(); - $this->assertSame("Stripe\\BankAccount", get_class($resource)); - } - - /** - * @expectedException \Stripe\Error\InvalidRequest - */ - public function testIsNotDirectlyUpdatable() - { - BankAccount::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - } - - public function testIsDeletable() - { - $resource = $this->createFixture(); - $this->expectsRequest( - 'delete', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID - ); - $resource->delete(); - $this->assertSame("Stripe\\BankAccount", get_class($resource)); - } - - public function testIsVerifiable() - { - $resource = $this->createFixture(); - $this->expectsRequest( - 'post', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID . "/verify", - [ - "amounts" => [1, 2] - ] - ); - $resource->verify(["amounts" => [1, 2]]); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/BitcoinReceiverTest.php b/htdocs/includes/stripe/tests/Stripe/BitcoinReceiverTest.php deleted file mode 100644 index cea999fc4f2..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/BitcoinReceiverTest.php +++ /dev/null @@ -1,62 +0,0 @@ - self::TEST_RESOURCE_ID, - 'object' => 'bitcoin_receiver', - 'metadata' => [], - ]; - return BitcoinReceiver::constructFrom( - array_merge($params, $base), - new Util\RequestOptions() - ); - } - - public function testHasCorrectStandaloneUrl() - { - $resource = $this->createFixture(); - $this->assertSame( - "/v1/bitcoin/receivers/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - public function testHasCorrectUrlForCustomer() - { - $resource = $this->createFixture(['customer' => 'cus_123']); - $this->assertSame( - "/v1/customers/cus_123/sources/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - public function testIsListable() - { - $this->expectsRequest( - 'get', - '/v1/bitcoin/receivers' - ); - $resources = BitcoinReceiver::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertSame("Stripe\\BitcoinReceiver", get_class($resources->data[0])); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/bitcoin/receivers/' . self::TEST_RESOURCE_ID - ); - $resource = BitcoinReceiver::retrieve(self::TEST_RESOURCE_ID); - $this->assertSame("Stripe\\BitcoinReceiver", get_class($resource)); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/CardTest.php b/htdocs/includes/stripe/tests/Stripe/CardTest.php deleted file mode 100644 index 8976eff6679..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/CardTest.php +++ /dev/null @@ -1,94 +0,0 @@ - self::TEST_RESOURCE_ID, - 'object' => 'card', - 'metadata' => [], - ]; - return Card::constructFrom( - array_merge($params, $base), - new Util\RequestOptions() - ); - } - - public function testHasCorrectUrlForCustomer() - { - $resource = $this->createFixture(['customer' => 'cus_123']); - $this->assertSame( - "/v1/customers/cus_123/sources/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - public function testHasCorrectUrlForAccount() - { - $resource = $this->createFixture(['account' => 'acct_123']); - $this->assertSame( - "/v1/accounts/acct_123/external_accounts/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - public function testHasCorrectUrlForRecipient() - { - $resource = $this->createFixture(['recipient' => 'rp_123']); - $this->assertSame( - "/v1/recipients/rp_123/cards/" . self::TEST_RESOURCE_ID, - $resource->instanceUrl() - ); - } - - /** - * @expectedException \Stripe\Error\InvalidRequest - */ - public function testIsNotDirectlyRetrievable() - { - Card::retrieve(self::TEST_RESOURCE_ID); - } - - public function testIsSaveable() - { - $resource = $this->createFixture(); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID - ); - $resource->save(); - $this->assertSame("Stripe\\Card", get_class($resource)); - } - - /** - * @expectedException \Stripe\Error\InvalidRequest - */ - public function testIsNotDirectlyUpdatable() - { - Card::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - } - - public function testIsDeletable() - { - $resource = $this->createFixture(); - $this->expectsRequest( - 'delete', - '/v1/customers/cus_123/sources/' . self::TEST_RESOURCE_ID - ); - $resource->delete(); - $this->assertSame("Stripe\\Card", get_class($resource)); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ChargeTest.php b/htdocs/includes/stripe/tests/Stripe/ChargeTest.php deleted file mode 100644 index b8c6cbabf3b..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ChargeTest.php +++ /dev/null @@ -1,140 +0,0 @@ -expectsRequest( - 'get', - '/v1/charges' - ); - $resources = Charge::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Charge", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/charges/' . self::TEST_RESOURCE_ID - ); - $resource = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Charge", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/charges' - ); - $resource = Charge::create([ - "amount" => 100, - "currency" => "usd", - "source" => "tok_123" - ]); - $this->assertInstanceOf("Stripe\\Charge", $resource); - } - - public function testIsSaveable() - { - $resource = Charge::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/charges/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Charge", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/charges/' . self::TEST_RESOURCE_ID - ); - $resource = Charge::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Charge", $resource); - } - - public function testCanRefund() - { - $charge = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/charges/' . $charge->id . '/refund' - ); - $resource = $charge->refund(); - $this->assertInstanceOf("Stripe\\Charge", $resource); - $this->assertSame($resource, $charge); - } - - public function testCanCapture() - { - $charge = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/charges/' . $charge->id . '/capture' - ); - $resource = $charge->capture(); - $this->assertInstanceOf("Stripe\\Charge", $resource); - $this->assertSame($resource, $charge); - } - - public function testCanUpdateDispute() - { - $charge = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/charges/' . $charge->id . '/dispute' - ); - $resource = $charge->updateDispute(); - $this->assertInstanceOf("Stripe\\Dispute", $resource); - } - - public function testCanCloseDispute() - { - $charge = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/charges/' . $charge->id . '/dispute/close' - ); - $resource = $charge->closeDispute(); - $this->assertInstanceOf("Stripe\\Charge", $resource); - $this->assertSame($resource, $charge); - } - - public function testCanMarkAsFraudulent() - { - $charge = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/charges/' . $charge->id, - ['fraud_details' => ['user_report' => 'fraudulent']] - ); - $resource = $charge->markAsFraudulent(); - $this->assertInstanceOf("Stripe\\Charge", $resource); - $this->assertSame($resource, $charge); - } - - public function testCanMarkAsSafe() - { - $charge = Charge::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/charges/' . $charge->id, - ['fraud_details' => ['user_report' => 'safe']] - ); - $resource = $charge->markAsSafe(); - $this->assertInstanceOf("Stripe\\Charge", $resource); - $this->assertSame($resource, $charge); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/CollectionTest.php b/htdocs/includes/stripe/tests/Stripe/CollectionTest.php deleted file mode 100644 index 560085aede2..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/CollectionTest.php +++ /dev/null @@ -1,147 +0,0 @@ -fixture = Collection::constructFrom([ - 'data' => [['id' => 1]], - 'has_more' => true, - 'url' => '/things', - ]); - } - - public function testCanList() - { - $this->stubRequest( - 'GET', - '/things', - [], - null, - false, - [ - 'data' => [['id' => 1]], - 'has_more' => true, - 'url' => '/things', - ] - ); - - $resources = $this->fixture->all(); - $this->assertTrue(is_array($resources->data)); - } - - public function testCanRetrieve() - { - $this->stubRequest( - 'GET', - '/things/1', - [], - null, - false, - [ - 'id' => 1, - ] - ); - - $this->fixture->retrieve(1); - } - - public function testCanCreate() - { - $this->stubRequest( - 'POST', - '/things', - [ - 'foo' => 'bar', - ], - null, - false, - [ - 'id' => 2, - ] - ); - - $this->fixture->create([ - 'foo' => 'bar', - ]); - } - - public function testProvidesAutoPagingIterator() - { - $this->stubRequest( - 'GET', - '/things', - [ - 'starting_after' => 1, - ], - null, - false, - [ - 'data' => [['id' => 2], ['id' => 3]], - 'has_more' => false, - ] - ); - - $seen = []; - foreach ($this->fixture->autoPagingIterator() as $item) { - array_push($seen, $item['id']); - } - - $this->assertSame([1, 2, 3], $seen); - } - - public function testSupportsIteratorToArray() - { - $this->stubRequest( - 'GET', - '/things', - [ - 'starting_after' => 1, - ], - null, - false, - [ - 'data' => [['id' => 2], ['id' => 3]], - 'has_more' => false, - ] - ); - - $seen = []; - foreach (iterator_to_array($this->fixture->autoPagingIterator()) as $item) { - array_push($seen, $item['id']); - } - - $this->assertSame([1, 2, 3], $seen); - } - - public function testHeaders() - { - $this->stubRequest( - 'POST', - '/things', - [ - 'foo' => 'bar', - ], - [ - 'Stripe-Account: acct_foo', - 'Idempotency-Key: qwertyuiop', - ], - false, - [ - 'id' => 2, - ] - ); - - $this->fixture->create([ - 'foo' => 'bar', - ], [ - 'stripe_account' => 'acct_foo', - 'idempotency_key' => 'qwertyuiop', - ]); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/CountrySpecTest.php b/htdocs/includes/stripe/tests/Stripe/CountrySpecTest.php deleted file mode 100644 index cccd4116845..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/CountrySpecTest.php +++ /dev/null @@ -1,29 +0,0 @@ -expectsRequest( - 'get', - '/v1/country_specs' - ); - $resources = CountrySpec::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\CountrySpec", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/country_specs/' . self::TEST_RESOURCE_ID - ); - $resource = CountrySpec::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\CountrySpec", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/CouponTest.php b/htdocs/includes/stripe/tests/Stripe/CouponTest.php deleted file mode 100644 index 8a6fbf630cd..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/CouponTest.php +++ /dev/null @@ -1,79 +0,0 @@ -expectsRequest( - 'get', - '/v1/coupons' - ); - $resources = Coupon::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Coupon", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/coupons/' . self::TEST_RESOURCE_ID - ); - $resource = Coupon::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Coupon", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/coupons' - ); - $resource = Coupon::create([ - "percent_off" => 25, - "duration" => "repeating", - "duration_in_months" => 3, - "id" => self::TEST_RESOURCE_ID, - ]); - $this->assertInstanceOf("Stripe\\Coupon", $resource); - } - - public function testIsSaveable() - { - $resource = Coupon::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/coupons/' . self::TEST_RESOURCE_ID - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Coupon", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/coupons/' . self::TEST_RESOURCE_ID - ); - $resource = Coupon::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Coupon", $resource); - } - - public function testIsDeletable() - { - $resource = Coupon::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/coupons/' . self::TEST_RESOURCE_ID - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Coupon", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/CustomerTest.php b/htdocs/includes/stripe/tests/Stripe/CustomerTest.php deleted file mode 100644 index e279e5489e8..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/CustomerTest.php +++ /dev/null @@ -1,269 +0,0 @@ -expectsRequest( - 'get', - '/v1/customers' - ); - $resources = Customer::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Customer", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/customers/' . self::TEST_RESOURCE_ID - ); - $resource = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Customer", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/customers' - ); - $resource = Customer::create(); - $this->assertInstanceOf("Stripe\\Customer", $resource); - } - - public function testIsSaveable() - { - $resource = Customer::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/customers/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Customer", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/customers/' . self::TEST_RESOURCE_ID - ); - $resource = Customer::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Customer", $resource); - } - - public function testIsDeletable() - { - $resource = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/customers/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Customer", $resource); - } - - public function testCanAddInvoiceItem() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/invoiceitems', - [ - "amount" => 100, - "currency" => "usd", - "customer" => $customer->id - ] - ); - $resource = $customer->addInvoiceItem([ - "amount" => 100, - "currency" => "usd" - ]); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resource); - } - - public function testCanListInvoices() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'get', - '/v1/invoices', - ["customer" => $customer->id] - ); - $resources = $customer->invoices(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Invoice", $resources->data[0]); - } - - public function testCanListInvoiceItems() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'get', - '/v1/invoiceitems', - ["customer" => $customer->id] - ); - $resources = $customer->invoiceItems(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resources->data[0]); - } - - public function testCanListCharges() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'get', - '/v1/charges', - ["customer" => $customer->id] - ); - $resources = $customer->charges(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Charge", $resources->data[0]); - } - - public function testCanUpdateSubscription() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->stubRequest( - 'post', - '/v1/customers/' . $customer->id . '/subscription', - ["plan" => "plan"], - null, - false, - [ - "object" => "subscription", - "id" => "sub_foo" - ] - ); - $resource = $customer->updateSubscription(["plan" => "plan"]); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - $this->assertSame("sub_foo", $customer->subscription->id); - } - - public function testCanCancelSubscription() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->stubRequest( - 'delete', - '/v1/customers/' . $customer->id . '/subscription', - [], - null, - false, - [ - "object" => "subscription", - "id" => "sub_foo" - ] - ); - $resource = $customer->cancelSubscription(); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - $this->assertSame("sub_foo", $customer->subscription->id); - } - - public function testCanDeleteDiscount() - { - $customer = Customer::retrieve(self::TEST_RESOURCE_ID); - $this->stubRequest( - 'delete', - '/v1/customers/' . $customer->id . '/discount' - ); - $customer->deleteDiscount(); - $this->assertSame($customer->discount, null); - } - - public function testCanCreateSource() - { - $this->expectsRequest( - 'post', - '/v1/customers/' . self::TEST_RESOURCE_ID . '/sources' - ); - $resource = Customer::createSource(self::TEST_RESOURCE_ID, ["source" => "btok_123"]); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanRetrieveSource() - { - $this->expectsRequest( - 'get', - '/v1/customers/' . self::TEST_RESOURCE_ID . '/sources/' . self::TEST_SOURCE_ID - ); - $resource = Customer::retrieveSource(self::TEST_RESOURCE_ID, self::TEST_SOURCE_ID); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanUpdateSource() - { - $this->expectsRequest( - 'post', - '/v1/customers/' . self::TEST_RESOURCE_ID . '/sources/' . self::TEST_SOURCE_ID - ); - $resource = Customer::updateSource(self::TEST_RESOURCE_ID, self::TEST_SOURCE_ID, ["name" => "name"]); - // stripe-mock returns a Card on this method and not a bank account - $this->assertInstanceOf("Stripe\\Card", $resource); - } - - public function testCanDeleteSource() - { - $this->expectsRequest( - 'delete', - '/v1/customers/' . self::TEST_RESOURCE_ID . '/sources/' . self::TEST_SOURCE_ID - ); - $resource = Customer::deleteSource(self::TEST_RESOURCE_ID, self::TEST_SOURCE_ID); - $this->assertInstanceOf("Stripe\\BankAccount", $resource); - } - - public function testCanListSources() - { - $this->expectsRequest( - 'get', - '/v1/customers/' . self::TEST_RESOURCE_ID . '/sources' - ); - $resources = Customer::allSources(self::TEST_RESOURCE_ID); - $this->assertTrue(is_array($resources->data)); - } - - public function testSerializeSourceString() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'customer', - ], null); - $obj->source = 'tok_visa'; - - $expected = [ - 'source' => 'tok_visa', - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } - - public function testSerializeSourceMap() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'customer', - ], null); - $obj->source = [ - 'object' => 'card', - 'number' => '4242424242424242', - 'exp_month' => 12, - 'exp_year' => 2032, - ]; - - $expected = [ - 'source' => [ - 'object' => 'card', - 'number' => '4242424242424242', - 'exp_month' => 12, - 'exp_year' => 2032, - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/DisputeTest.php b/htdocs/includes/stripe/tests/Stripe/DisputeTest.php deleted file mode 100644 index 81d93da0213..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/DisputeTest.php +++ /dev/null @@ -1,65 +0,0 @@ -expectsRequest( - 'get', - '/v1/disputes' - ); - $resources = Dispute::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Dispute", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/disputes/' . self::TEST_RESOURCE_ID - ); - $resource = Dispute::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Dispute", $resource); - } - - public function testIsSaveable() - { - $resource = Dispute::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/disputes/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Dispute", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/disputes/' . self::TEST_RESOURCE_ID - ); - $resource = Dispute::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Dispute", $resource); - } - - public function testIsClosable() - { - $dispute = Dispute::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/disputes/' . $dispute->id . '/close' - ); - $resource = $dispute->close(); - $this->assertInstanceOf("Stripe\\Dispute", $resource); - $this->assertSame($resource, $dispute); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/EphemeralKeyTest.php b/htdocs/includes/stripe/tests/Stripe/EphemeralKeyTest.php deleted file mode 100644 index e8a1fc0e9ef..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/EphemeralKeyTest.php +++ /dev/null @@ -1,43 +0,0 @@ -expectsRequest( - 'post', - '/v1/ephemeral_keys', - null, - ["Stripe-Version: 2017-05-25"] - ); - $resource = EphemeralKey::create([ - "customer" => "cus_123", - ], ["stripe_version" => "2017-05-25"]); - $this->assertInstanceOf("Stripe\\EphemeralKey", $resource); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testIsNotCreatableWithoutAnExplicitApiVersion() - { - $resource = EphemeralKey::create([ - "customer" => "cus_123", - ]); - } - - public function testIsDeletable() - { - $key = EphemeralKey::create([ - "customer" => "cus_123", - ], ["stripe_version" => "2017-05-25"]); - $this->expectsRequest( - 'delete', - '/v1/ephemeral_keys/' . $key->id - ); - $resource = $key->delete(); - $this->assertInstanceOf("Stripe\\EphemeralKey", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/Error/BaseTest.php b/htdocs/includes/stripe/tests/Stripe/Error/BaseTest.php deleted file mode 100644 index 4c2732ed1d1..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/Error/BaseTest.php +++ /dev/null @@ -1,36 +0,0 @@ -getMockForAbstractClass('Stripe\\Error\\Base', [ - 'message', - 200, - '{"key": "value"}', - ['key' => 'value'], - [ - 'Some-Header' => 'Some Value', - 'Request-Id' => 'req_test', - ], - ]); - } - - public function testGetters() - { - $e = $this->createFixture(); - $this->assertSame(200, $e->getHttpStatus()); - $this->assertSame('{"key": "value"}', $e->getHttpBody()); - $this->assertSame(['key' => 'value'], $e->getJsonBody()); - $this->assertSame('Some Value', $e->getHttpHeaders()['Some-Header']); - $this->assertSame('req_test', $e->getRequestId()); - } - - public function testToString() - { - $e = $this->createFixture(); - $this->assertContains("from API request 'req_test'", (string)$e); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/Error/SignatureVerificationTest.php b/htdocs/includes/stripe/tests/Stripe/Error/SignatureVerificationTest.php deleted file mode 100644 index 020a41f8f76..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/Error/SignatureVerificationTest.php +++ /dev/null @@ -1,12 +0,0 @@ -assertSame('sig_header', $e->getSigHeader()); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/EventTest.php b/htdocs/includes/stripe/tests/Stripe/EventTest.php deleted file mode 100644 index 2e3c92f0e49..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/EventTest.php +++ /dev/null @@ -1,29 +0,0 @@ -expectsRequest( - 'get', - '/v1/events' - ); - $resources = Event::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Event", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/events/' . self::TEST_RESOURCE_ID - ); - $resource = Event::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Event", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ExchangeRateTest.php b/htdocs/includes/stripe/tests/Stripe/ExchangeRateTest.php deleted file mode 100644 index 8b07b5a1358..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ExchangeRateTest.php +++ /dev/null @@ -1,54 +0,0 @@ -stubRequest( - 'get', - '/v1/exchange_rates', - [], - null, - false, - [ - 'object' => 'list', - 'data' => [ - [ - 'id' => 'eur', - 'object' => 'exchange_rate', - 'rates' => ['usd' => 1.18221], - ], - [ - 'id' => 'usd', - 'object' => 'exchange_rate', - 'rates' => ['eur' => 0.845876], - ], - ], - ] - ); - - $listRates = ExchangeRate::all(); - $this->assertTrue(is_array($listRates->data)); - $this->assertEquals('exchange_rate', $listRates->data[0]->object); - } - - public function testIsRetrievable() - { - $this->stubRequest( - 'get', - '/v1/exchange_rates/usd', - [], - null, - false, - [ - 'id' => 'usd', - 'object' => 'exchange_rate', - 'rates' => ['eur' => 0.845876], - ] - ); - $rates = ExchangeRate::retrieve("usd"); - $this->assertEquals('exchange_rate', $rates->object); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/FileUploadTest.php b/htdocs/includes/stripe/tests/Stripe/FileUploadTest.php deleted file mode 100644 index 21bb0b568f6..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/FileUploadTest.php +++ /dev/null @@ -1,104 +0,0 @@ -fixture = [ - 'id' => self::TEST_RESOURCE_ID, - 'object' => 'file_upload', - ]; - } - - public function testIsListable() - { - $this->stubRequest( - 'get', - '/v1/files', - [], - null, - false, - [ - 'object' => 'list', - 'data' => [$this->fixture], - 'resource_url' => '/v1/files', - ], - 200, - Stripe::$apiUploadBase - ); - - $resources = FileUpload::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\FileUpload", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->stubRequest( - 'get', - '/v1/files/' . self::TEST_RESOURCE_ID, - [], - null, - false, - $this->fixture, - 200, - Stripe::$apiUploadBase - ); - $resource = FileUpload::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\FileUpload", $resource); - } - - public function testIsCreatableWithFileHandle() - { - $this->stubRequest( - 'post', - '/v1/files', - null, - ['Content-Type: multipart/form-data'], - true, - $this->fixture, - 200, - Stripe::$apiUploadBase - ); - $fp = fopen(dirname(__FILE__) . '/../data/test.png', 'r'); - $resource = FileUpload::create([ - "purpose" => "dispute_evidence", - "file" => $fp, - ]); - $this->assertInstanceOf("Stripe\\FileUpload", $resource); - } - - public function testIsCreatableWithCurlFile() - { - if (!class_exists('\CurlFile', false)) { - // Older PHP versions don't support this - return; - } - - $this->stubRequest( - 'post', - '/v1/files', - null, - ['Content-Type: multipart/form-data'], - true, - $this->fixture, - 200, - Stripe::$apiUploadBase - ); - $curlFile = new \CurlFile(dirname(__FILE__) . '/../data/test.png'); - $resource = FileUpload::create([ - "purpose" => "dispute_evidence", - "file" => $curlFile, - ]); - $this->assertInstanceOf("Stripe\\FileUpload", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/HttpClient/CurlClientTest.php b/htdocs/includes/stripe/tests/Stripe/HttpClient/CurlClientTest.php deleted file mode 100644 index 086e6d3ee8d..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/HttpClient/CurlClientTest.php +++ /dev/null @@ -1,228 +0,0 @@ -origMaxNetworkRetries = Stripe::getMaxNetworkRetries(); - $this->origMaxNetworkRetryDelay = Stripe::getMaxNetworkRetryDelay(); - $this->origInitialNetworkRetryDelay = Stripe::getInitialNetworkRetryDelay(); - } - - /** - * @before - */ - public function setUpReflectors() - { - $stripeReflector = new \ReflectionClass('\Stripe\Stripe'); - - $this->maxNetworkRetryDelayProperty = $stripeReflector->getProperty('maxNetworkRetryDelay'); - $this->maxNetworkRetryDelayProperty->setAccessible(true); - - $this->initialNetworkRetryDelayProperty = $stripeReflector->getProperty('initialNetworkRetryDelay'); - $this->initialNetworkRetryDelayProperty->setAccessible(true); - - $curlClientReflector = new \ReflectionClass('Stripe\HttpClient\CurlClient'); - - $this->shouldRetryMethod = $curlClientReflector->getMethod('shouldRetry'); - $this->shouldRetryMethod->setAccessible(true); - - $this->sleepTimeMethod = $curlClientReflector->getMethod('sleepTime'); - $this->sleepTimeMethod->setAccessible(true); - } - - /** - * @after - */ - public function restoreOriginalNetworkValues() - { - Stripe::setMaxNetworkRetries($this->origMaxNetworkRetries); - $this->setMaxNetworkRetryDelay($this->origMaxNetworkRetryDelay); - $this->setInitialNetworkRetryDelay($this->origInitialNetworkRetryDelay); - } - - private function setMaxNetworkRetryDelay($maxNetworkRetryDelay) - { - $this->maxNetworkRetryDelayProperty->setValue(null, $maxNetworkRetryDelay); - } - - private function setInitialNetworkRetryDelay($initialNetworkRetryDelay) - { - $this->initialNetworkRetryDelayProperty->setValue(null, $initialNetworkRetryDelay); - } - - private function createFakeRandomGenerator($returnValue = 1.0) - { - $fakeRandomGenerator = $this->getMock('Stripe\Util\RandomGenetator', ['randFloat']); - $fakeRandomGenerator->method('randFloat')->willReturn($returnValue); - return $fakeRandomGenerator; - } - - public function testTimeout() - { - $curl = new CurlClient(); - $this->assertSame(CurlClient::DEFAULT_TIMEOUT, $curl->getTimeout()); - $this->assertSame(CurlClient::DEFAULT_CONNECT_TIMEOUT, $curl->getConnectTimeout()); - - // implicitly tests whether we're returning the CurlClient instance - $curl = $curl->setConnectTimeout(1)->setTimeout(10); - $this->assertSame(1, $curl->getConnectTimeout()); - $this->assertSame(10, $curl->getTimeout()); - - $curl->setTimeout(-1); - $curl->setConnectTimeout(-999); - $this->assertSame(0, $curl->getTimeout()); - $this->assertSame(0, $curl->getConnectTimeout()); - } - - public function testUserAgentInfo() - { - $curl = new CurlClient(); - $uaInfo = $curl->getUserAgentInfo(); - $this->assertNotNull($uaInfo); - $this->assertNotNull($uaInfo['httplib']); - $this->assertNotNull($uaInfo['ssllib']); - } - - public function testDefaultOptions() - { - // make sure options array loads/saves properly - $optionsArray = [CURLOPT_PROXY => 'localhost:80']; - $withOptionsArray = new CurlClient($optionsArray); - $this->assertSame($withOptionsArray->getDefaultOptions(), $optionsArray); - - // make sure closure-based options work properly, including argument passing - $ref = null; - $withClosure = new CurlClient(function ($method, $absUrl, $headers, $params, $hasFile) use (&$ref) { - $ref = func_get_args(); - return []; - }); - - $withClosure->request('get', 'https://httpbin.org/status/200', [], [], false); - $this->assertSame($ref, ['get', 'https://httpbin.org/status/200', [], [], false]); - - // this is the last test case that will run, since it'll throw an exception at the end - $withBadClosure = new CurlClient(function () { - return 'thisShouldNotWork'; - }); - $this->setExpectedException('Stripe\Error\Api', "Non-array value returned by defaultOptions CurlClient callback"); - $withBadClosure->request('get', 'https://httpbin.org/status/200', [], [], false); - } - - public function testSslOption() - { - // make sure options array loads/saves properly - $optionsArray = [CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1]; - $withOptionsArray = new CurlClient($optionsArray); - $this->assertSame($withOptionsArray->getDefaultOptions(), $optionsArray); - } - - public function testShouldRetryOnTimeout() - { - Stripe::setMaxNetworkRetries(2); - - $curlClient = new CurlClient(); - - $this->assertTrue($this->shouldRetryMethod->invoke($curlClient, CURLE_OPERATION_TIMEOUTED, 0, 0)); - } - - public function testShouldRetryOnConnectionFailure() - { - Stripe::setMaxNetworkRetries(2); - - $curlClient = new CurlClient(); - - $this->assertTrue($this->shouldRetryMethod->invoke($curlClient, CURLE_COULDNT_CONNECT, 0, 0)); - } - - public function testShouldRetryOnConflict() - { - Stripe::setMaxNetworkRetries(2); - - $curlClient = new CurlClient(); - - $this->assertTrue($this->shouldRetryMethod->invoke($curlClient, 0, 409, 0)); - } - - public function testShouldNotRetryAtMaximumCount() - { - Stripe::setMaxNetworkRetries(2); - - $curlClient = new CurlClient(); - - $this->assertFalse($this->shouldRetryMethod->invoke($curlClient, 0, 0, Stripe::getMaxNetworkRetries())); - } - - public function testShouldNotRetryOnCertValidationError() - { - Stripe::setMaxNetworkRetries(2); - - $curlClient = new CurlClient(); - - $this->assertFalse($this->shouldRetryMethod->invoke($curlClient, CURLE_SSL_PEER_CERTIFICATE, -1, 0)); - } - - public function testSleepTimeShouldGrowExponentially() - { - $this->setMaxNetworkRetryDelay(999); - - $curlClient = new CurlClient(null, $this->createFakeRandomGenerator()); - - $this->assertEquals( - Stripe::getInitialNetworkRetryDelay() * 1, - $this->sleepTimeMethod->invoke($curlClient, 1) - ); - $this->assertEquals( - Stripe::getInitialNetworkRetryDelay() * 2, - $this->sleepTimeMethod->invoke($curlClient, 2) - ); - $this->assertEquals( - Stripe::getInitialNetworkRetryDelay() * 4, - $this->sleepTimeMethod->invoke($curlClient, 3) - ); - $this->assertEquals( - Stripe::getInitialNetworkRetryDelay() * 8, - $this->sleepTimeMethod->invoke($curlClient, 4) - ); - } - - public function testSleepTimeShouldEnforceMaxNetworkRetryDelay() - { - $this->setInitialNetworkRetryDelay(1); - $this->setMaxNetworkRetryDelay(2); - - $curlClient = new CurlClient(null, $this->createFakeRandomGenerator()); - - $this->assertEquals(1, $this->sleepTimeMethod->invoke($curlClient, 1)); - $this->assertEquals(2, $this->sleepTimeMethod->invoke($curlClient, 2)); - $this->assertEquals(2, $this->sleepTimeMethod->invoke($curlClient, 3)); - $this->assertEquals(2, $this->sleepTimeMethod->invoke($curlClient, 4)); - } - - public function testSleepTimeShouldAddSomeRandomness() - { - $randomValue = 0.8; - $this->setInitialNetworkRetryDelay(1); - $this->setMaxNetworkRetryDelay(8); - - $curlClient = new CurlClient(null, $this->createFakeRandomGenerator($randomValue)); - - $baseValue = Stripe::getInitialNetworkRetryDelay() * (0.5 * (1 + $randomValue)); - - // the initial value cannot be smaller than the base, - // so the randomness is ignored - $this->assertEquals(Stripe::getInitialNetworkRetryDelay(), $this->sleepTimeMethod->invoke($curlClient, 1)); - - // after the first one, the randomness is applied - $this->assertEquals($baseValue * 2, $this->sleepTimeMethod->invoke($curlClient, 2)); - $this->assertEquals($baseValue * 4, $this->sleepTimeMethod->invoke($curlClient, 3)); - $this->assertEquals($baseValue * 8, $this->sleepTimeMethod->invoke($curlClient, 4)); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/InvoiceItemTest.php b/htdocs/includes/stripe/tests/Stripe/InvoiceItemTest.php deleted file mode 100644 index ffe140aa7ca..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/InvoiceItemTest.php +++ /dev/null @@ -1,78 +0,0 @@ -expectsRequest( - 'get', - '/v1/invoiceitems' - ); - $resources = InvoiceItem::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/invoiceitems/' . self::TEST_RESOURCE_ID - ); - $resource = InvoiceItem::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/invoiceitems' - ); - $resource = InvoiceItem::create([ - "amount" => 100, - "currency" => "usd", - "customer" => "cus_123" - ]); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resource); - } - - public function testIsSaveable() - { - $resource = InvoiceItem::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/invoiceitems/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/invoiceitems/' . self::TEST_RESOURCE_ID - ); - $resource = InvoiceItem::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resource); - } - - public function testIsDeletable() - { - $invoiceItem = InvoiceItem::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/invoiceitems/' . $invoiceItem->id - ); - $resource = $invoiceItem->delete(); - $this->assertInstanceOf("Stripe\\InvoiceItem", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/InvoiceTest.php b/htdocs/includes/stripe/tests/Stripe/InvoiceTest.php deleted file mode 100644 index f1ae9378628..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/InvoiceTest.php +++ /dev/null @@ -1,87 +0,0 @@ -expectsRequest( - 'get', - '/v1/invoices' - ); - $resources = Invoice::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Invoice", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/invoices/' . self::TEST_RESOURCE_ID - ); - $resource = Invoice::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Invoice", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/invoices' - ); - $resource = Invoice::create([ - "customer" => "cus_123" - ]); - $this->assertInstanceOf("Stripe\\Invoice", $resource); - } - - public function testIsSaveable() - { - $resource = Invoice::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/invoices/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Invoice", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/invoices/' . self::TEST_RESOURCE_ID - ); - $resource = Invoice::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Invoice", $resource); - } - - public function testCanRetrieveUpcoming() - { - $this->expectsRequest( - 'get', - '/v1/invoices/upcoming' - ); - $resource = Invoice::upcoming(["customer" => "cus_123"]); - $this->assertInstanceOf("Stripe\\Invoice", $resource); - } - - public function testIsPayable() - { - $invoice = Invoice::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/invoices/' . $invoice->id . '/pay' - ); - $resource = $invoice->pay(); - $this->assertInstanceOf("Stripe\\Invoice", $resource); - $this->assertSame($resource, $invoice); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/OAuthTest.php b/htdocs/includes/stripe/tests/Stripe/OAuthTest.php deleted file mode 100644 index b4e43a88103..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/OAuthTest.php +++ /dev/null @@ -1,97 +0,0 @@ - 'read_write', - 'state' => 'csrf_token', - 'stripe_user' => [ - 'email' => 'test@example.com', - 'url' => 'https://example.com/profile/test', - 'country' => 'US', - ], - ]); - - $uri = parse_url($uriStr); - parse_str($uri['query'], $params); - - $this->assertSame('https', $uri['scheme']); - $this->assertSame('connect.stripe.com', $uri['host']); - $this->assertSame('/oauth/authorize', $uri['path']); - - $this->assertSame('ca_123', $params['client_id']); - $this->assertSame('read_write', $params['scope']); - $this->assertSame('test@example.com', $params['stripe_user']['email']); - $this->assertSame('https://example.com/profile/test', $params['stripe_user']['url']); - $this->assertSame('US', $params['stripe_user']['country']); - } - - /** - * @expectedException \Stripe\Error\Authentication - * @expectedExceptionMessageRegExp #No client_id provided# - */ - public function testRaisesAuthenticationErrorWhenNoClientId() - { - Stripe::setClientId(null); - OAuth::authorizeUrl(); - } - - public function testToken() - { - $this->stubRequest( - 'POST', - '/oauth/token', - [ - 'grant_type' => 'authorization_code', - 'code' => 'this_is_an_authorization_code', - ], - null, - false, - [ - 'access_token' => 'sk_access_token', - 'scope' => 'read_only', - 'livemode' => false, - 'token_type' => 'bearer', - 'refresh_token' => 'sk_refresh_token', - 'stripe_user_id' => 'acct_test', - 'stripe_publishable_key' => 'pk_test', - ], - 200, - Stripe::$connectBase - ); - - $resp = OAuth::token([ - 'grant_type' => 'authorization_code', - 'code' => 'this_is_an_authorization_code', - ]); - $this->assertSame('sk_access_token', $resp->access_token); - } - - public function testDeauthorize() - { - $this->stubRequest( - 'POST', - '/oauth/deauthorize', - [ - 'stripe_user_id' => 'acct_test_deauth', - 'client_id' => 'ca_123', - ], - null, - false, - [ - 'stripe_user_id' => 'acct_test_deauth', - ], - 200, - Stripe::$connectBase - ); - - $resp = OAuth::deauthorize([ - 'stripe_user_id' => 'acct_test_deauth', - ]); - $this->assertSame('acct_test_deauth', $resp->stripe_user_id); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/OrderReturnTest.php b/htdocs/includes/stripe/tests/Stripe/OrderReturnTest.php deleted file mode 100644 index bb2d65c437a..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/OrderReturnTest.php +++ /dev/null @@ -1,29 +0,0 @@ -expectsRequest( - 'get', - '/v1/order_returns' - ); - $resources = OrderReturn::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\OrderReturn", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/order_returns/' . self::TEST_RESOURCE_ID - ); - $resource = OrderReturn::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\OrderReturn", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/OrderTest.php b/htdocs/includes/stripe/tests/Stripe/OrderTest.php deleted file mode 100644 index 51d17e94fc7..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/OrderTest.php +++ /dev/null @@ -1,87 +0,0 @@ -expectsRequest( - 'get', - '/v1/orders' - ); - $resources = Order::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Order", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/orders/' . self::TEST_RESOURCE_ID - ); - $resource = Order::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Order", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/orders' - ); - $resource = Order::create([ - 'currency' => 'usd' - ]); - $this->assertInstanceOf("Stripe\\Order", $resource); - } - - public function testIsSaveable() - { - $resource = Order::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/orders/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Order", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/orders/' . self::TEST_RESOURCE_ID - ); - $resource = Order::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Order", $resource); - } - - public function testIsPayable() - { - $resource = Order::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/orders/' . $resource->id . '/pay' - ); - $resource->pay(); - $this->assertInstanceOf("Stripe\\Order", $resource); - } - - public function testIsReturnable() - { - $order = Order::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/orders/' . $order->id . '/returns' - ); - $resource = $order->returnOrder(); - $this->assertInstanceOf("Stripe\\OrderReturn", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/PayoutTest.php b/htdocs/includes/stripe/tests/Stripe/PayoutTest.php deleted file mode 100644 index 79c7b5fd015..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/PayoutTest.php +++ /dev/null @@ -1,77 +0,0 @@ -expectsRequest( - 'get', - '/v1/payouts' - ); - $resources = Payout::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Payout", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/payouts/' . self::TEST_RESOURCE_ID - ); - $resource = Payout::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Payout", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/payouts' - ); - $resource = Payout::create([ - "amount" => 100, - "currency" => "usd" - ]); - $this->assertInstanceOf("Stripe\\Payout", $resource); - } - - public function testIsSaveable() - { - $resource = Payout::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/payouts/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Payout", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/payouts/' . self::TEST_RESOURCE_ID - ); - $resource = Payout::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Payout", $resource); - } - - public function testIsCancelable() - { - $resource = Payout::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/payouts/' . $resource->id . '/cancel' - ); - $resource->cancel(); - $this->assertInstanceOf("Stripe\\Payout", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/PlanTest.php b/htdocs/includes/stripe/tests/Stripe/PlanTest.php deleted file mode 100644 index 8d71745ed56..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/PlanTest.php +++ /dev/null @@ -1,80 +0,0 @@ -expectsRequest( - 'get', - '/v1/plans' - ); - $resources = Plan::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Plan", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/plans/' . self::TEST_RESOURCE_ID - ); - $resource = Plan::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Plan", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/plans' - ); - $resource = Plan::create([ - 'amount' => 100, - 'interval' => 'month', - 'currency' => 'usd', - 'name' => self::TEST_RESOURCE_ID, - 'id' => self::TEST_RESOURCE_ID - ]); - $this->assertInstanceOf("Stripe\\Plan", $resource); - } - - public function testIsSaveable() - { - $resource = Plan::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/plans/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Plan", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/plans/' . self::TEST_RESOURCE_ID - ); - $resource = Plan::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Plan", $resource); - } - - public function testIsDeletable() - { - $resource = Plan::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/plans/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Plan", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ProductTest.php b/htdocs/includes/stripe/tests/Stripe/ProductTest.php deleted file mode 100644 index c2a3813c870..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ProductTest.php +++ /dev/null @@ -1,77 +0,0 @@ -expectsRequest( - 'get', - '/v1/products' - ); - $resources = Product::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Product", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/products/' . self::TEST_RESOURCE_ID - ); - $resource = Product::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Product", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/products' - ); - $resource = Product::create([ - 'name' => 'name', - 'type' => 'good' - ]); - $this->assertInstanceOf("Stripe\\Product", $resource); - } - - public function testIsSaveable() - { - $resource = Product::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/products/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Product", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/products/' . self::TEST_RESOURCE_ID - ); - $resource = Product::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Product", $resource); - } - - public function testIsDeletable() - { - $resource = Product::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/products/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Product", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/RecipientTest.php b/htdocs/includes/stripe/tests/Stripe/RecipientTest.php deleted file mode 100644 index 43dd6e82a79..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/RecipientTest.php +++ /dev/null @@ -1,90 +0,0 @@ -expectsRequest( - 'get', - '/v1/recipients' - ); - $resources = Recipient::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Recipient", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/recipients/' . self::TEST_RESOURCE_ID - ); - $resource = Recipient::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Recipient", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/recipients' - ); - $resource = Recipient::create([ - "name" => "name", - "type" => "individual" - ]); - $this->assertInstanceOf("Stripe\\Recipient", $resource); - } - - public function testIsSaveable() - { - $resource = Recipient::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/recipients/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Recipient", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/recipients/' . self::TEST_RESOURCE_ID - ); - $resource = Recipient::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Recipient", $resource); - } - - public function testIsDeletable() - { - $resource = Recipient::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/recipients/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Recipient", $resource); - } - - public function testCanListTransfers() - { - $recipient = Recipient::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'get', - '/v1/transfers', - ["recipient" => $recipient->id] - ); - $resources = $recipient->transfers(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Transfer", $resources->data[0]); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/RefundTest.php b/htdocs/includes/stripe/tests/Stripe/RefundTest.php deleted file mode 100644 index 788361d4d9d..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/RefundTest.php +++ /dev/null @@ -1,65 +0,0 @@ -expectsRequest( - 'get', - '/v1/refunds' - ); - $resources = Refund::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Refund", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/refunds/' . self::TEST_RESOURCE_ID - ); - $resource = Refund::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Refund", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/refunds' - ); - $resource = Refund::create([ - "charge" => "ch_123" - ]); - $this->assertInstanceOf("Stripe\\Refund", $resource); - } - - public function testIsSaveable() - { - $resource = Refund::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/refunds/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Refund", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/refunds/' . self::TEST_RESOURCE_ID - ); - $resource = Refund::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Refund", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/SKUTest.php b/htdocs/includes/stripe/tests/Stripe/SKUTest.php deleted file mode 100644 index d4fc2ad408b..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/SKUTest.php +++ /dev/null @@ -1,82 +0,0 @@ -expectsRequest( - 'get', - '/v1/skus' - ); - $resources = SKU::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\SKU", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/skus/' . self::TEST_RESOURCE_ID - ); - $resource = SKU::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\SKU", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/skus' - ); - $resource = SKU::create([ - 'currency' => 'usd', - 'inventory' => [ - 'type' => 'finite', - 'quantity' => 1 - ], - 'price' => 100, - 'product' => "prod_123" - ]); - $this->assertInstanceOf("Stripe\\SKU", $resource); - } - - public function testIsSaveable() - { - $resource = SKU::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/skus/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\SKU", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/skus/' . self::TEST_RESOURCE_ID - ); - $resource = SKU::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\SKU", $resource); - } - - public function testIsDeletable() - { - $resource = SKU::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/skus/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\SKU", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/SourceTest.php b/htdocs/includes/stripe/tests/Stripe/SourceTest.php deleted file mode 100644 index ad11b0d3455..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/SourceTest.php +++ /dev/null @@ -1,134 +0,0 @@ -expectsRequest( - 'get', - '/v1/sources/' . self::TEST_RESOURCE_ID - ); - $resource = Source::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Source", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/sources' - ); - $resource = Source::create([ - "type" => "card" - ]); - $this->assertInstanceOf("Stripe\\Source", $resource); - } - - public function testIsSaveable() - { - $resource = Source::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/sources/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Source", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/sources/' . self::TEST_RESOURCE_ID - ); - $resource = Source::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Source", $resource); - } - - public function testCanSaveCardExpiryDate() - { - $response = [ - 'id' => 'src_foo', - 'object' => 'source', - 'card' => [ - 'exp_month' => 8, - 'exp_year' => 2019, - ], - ]; - $source = Source::constructFrom($response); - - $response['card']['exp_month'] = 12; - $response['card']['exp_year'] = 2022; - $this->stubRequest( - 'POST', - '/v1/sources/src_foo', - [ - 'card' => [ - 'exp_month' => 12, - 'exp_year' => 2022, - ] - ], - null, - false, - $response - ); - - $source->card->exp_month = 12; - $source->card->exp_year = 2022; - $source->save(); - - $this->assertSame(12, $source->card->exp_month); - $this->assertSame(2022, $source->card->exp_year); - } - - public function testIsDetachableWhenAttached() - { - $resource = Source::retrieve(self::TEST_RESOURCE_ID); - $resource->customer = "cus_123"; - $this->expectsRequest( - 'delete', - '/v1/customers/cus_123/sources/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\Source", $resource); - } - - /** - * @expectedException \Stripe\Error\Api - */ - public function testIsNotDetachableWhenUnattached() - { - $resource = Source::retrieve(self::TEST_RESOURCE_ID); - $resource->detach(); - } - - public function testCanListSourceTransactions() - { - $source = Source::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'get', - '/v1/sources/' . $source->id . "/source_transactions" - ); - $resources = $source->sourceTransactions(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\SourceTransaction", $resources->data[0]); - } - - public function testCanVerify() - { - $resource = Source::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/sources/' . $resource->id . "/verify" - ); - $resource->verify(["values" => [32, 45]]); - $this->assertInstanceOf("Stripe\\Source", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/StripeObjectTest.php b/htdocs/includes/stripe/tests/Stripe/StripeObjectTest.php deleted file mode 100644 index af1cd936e1c..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/StripeObjectTest.php +++ /dev/null @@ -1,453 +0,0 @@ -deepCopyReflector = new \ReflectionMethod('Stripe\\StripeObject', 'deepCopy'); - $this->deepCopyReflector->setAccessible(true); - - // This is used to access the `_opts` protected variable - $this->optsReflector = new \ReflectionProperty('Stripe\\StripeObject', '_opts'); - $this->optsReflector->setAccessible(true); - } - - public function testArrayAccessorsSemantics() - { - $s = new StripeObject(); - $s['foo'] = 'a'; - $this->assertSame($s['foo'], 'a'); - $this->assertTrue(isset($s['foo'])); - unset($s['foo']); - $this->assertFalse(isset($s['foo'])); - } - - public function testNormalAccessorsSemantics() - { - $s = new StripeObject(); - $s->foo = 'a'; - $this->assertSame($s->foo, 'a'); - $this->assertTrue(isset($s->foo)); - unset($s->foo); - $this->assertFalse(isset($s->foo)); - } - - public function testArrayAccessorsMatchNormalAccessors() - { - $s = new StripeObject(); - $s->foo = 'a'; - $this->assertSame($s['foo'], 'a'); - - $s['bar'] = 'b'; - $this->assertSame($s->bar, 'b'); - } - - public function testCount() - { - $s = new StripeObject(); - $this->assertSame(0, count($s)); - - $s['key1'] = 'value1'; - $this->assertSame(1, count($s)); - - $s['key2'] = 'value2'; - $this->assertSame(2, count($s)); - - unset($s['key1']); - $this->assertSame(1, count($s)); - } - - public function testKeys() - { - $s = new StripeObject(); - $s->foo = 'bar'; - $this->assertSame($s->keys(), ['foo']); - } - - public function testValues() - { - $s = new StripeObject(); - $s->foo = 'bar'; - $this->assertSame($s->values(), ['bar']); - } - - public function testToArray() - { - $s = new StripeObject(); - $s->foo = 'a'; - - $converted = $s->__toArray(); - - $this->assertInternalType('array', $converted); - $this->assertArrayHasKey('foo', $converted); - $this->assertEquals('a', $converted['foo']); - } - - public function testRecursiveToArray() - { - $s = new StripeObject(); - $z = new StripeObject(); - - $s->child = $z; - $z->foo = 'a'; - - $converted = $s->__toArray(true); - - $this->assertInternalType('array', $converted); - $this->assertArrayHasKey('child', $converted); - $this->assertInternalType('array', $converted['child']); - $this->assertArrayHasKey('foo', $converted['child']); - $this->assertEquals('a', $converted['child']['foo']); - } - - public function testNonexistentProperty() - { - $s = new StripeObject(); - $this->assertNull($s->nonexistent); - } - - public function testPropertyDoesNotExists() - { - $s = new StripeObject(); - $this->assertNull($s['nonexistent']); - } - - public function testJsonEncode() - { - $s = new StripeObject(); - $s->foo = 'a'; - - $this->assertEquals('{"foo":"a"}', json_encode($s)); - } - - public function testToString() - { - $s = new StripeObject(); - $s->foo = 'a'; - - $string = $s->__toString(); - $expected = <<assertEquals($expected, $string); - } - - public function testReplaceNewNestedUpdatable() - { - $s = new StripeObject(); - - $s->metadata = ['bar']; - $this->assertSame($s->metadata, ['bar']); - $s->metadata = ['baz', 'qux']; - $this->assertSame($s->metadata, ['baz', 'qux']); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testSetPermanentAttribute() - { - $s = new StripeObject(); - $s->id = 'abc_123'; - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testSetEmptyStringValue() - { - $s = new StripeObject(); - $s->foo = ''; - } - - public function testSerializeParametersOnEmptyObject() - { - $obj = StripeObject::constructFrom([]); - $this->assertSame([], $obj->serializeParameters()); - } - - public function testSerializeParametersOnNewObjectWithSubObject() - { - $obj = new StripeObject(); - $obj->metadata = ['foo' => 'bar']; - $this->assertSame(['metadata' => ['foo' => 'bar']], $obj->serializeParameters()); - } - - public function testSerializeParametersOnBasicObject() - { - $obj = StripeObject::constructFrom(['foo' => null]); - $obj->updateAttributes(['foo' => 'bar']); - $this->assertSame(['foo' => 'bar'], $obj->serializeParameters()); - } - - public function testSerializeParametersOnMoreComplexObject() - { - $obj = StripeObject::constructFrom([ - 'foo' => StripeObject::constructFrom([ - 'bar' => null, - 'baz' => null, - ]), - ]); - $obj->foo->bar = 'newbar'; - $this->assertSame(['foo' => ['bar' => 'newbar']], $obj->serializeParameters()); - } - - public function testSerializeParametersOnArray() - { - $obj = StripeObject::constructFrom([ - 'foo' => null, - ]); - $obj->foo = ['new-value']; - $this->assertSame(['foo' => ['new-value']], $obj->serializeParameters()); - } - - public function testSerializeParametersOnArrayThatShortens() - { - $obj = StripeObject::constructFrom([ - 'foo' => ['0-index', '1-index', '2-index'], - ]); - $obj->foo = ['new-value']; - $this->assertSame(['foo' => ['new-value']], $obj->serializeParameters()); - } - - public function testSerializeParametersOnArrayThatLengthens() - { - $obj = StripeObject::constructFrom([ - 'foo' => ['0-index', '1-index', '2-index'], - ]); - $obj->foo = array_fill(0, 4, 'new-value'); - $this->assertSame(['foo' => array_fill(0, 4, 'new-value')], $obj->serializeParameters()); - } - - public function testSerializeParametersOnArrayOfHashes() - { - $obj = StripeObject::constructFrom(['foo' => null]); - $obj->foo = [ - StripeObject::constructFrom(['bar' => null]), - ]; - - $obj->foo[0]->bar = 'baz'; - $this->assertSame(['foo' => [['bar' => 'baz']]], $obj->serializeParameters()); - } - - public function testSerializeParametersDoesNotIncludeUnchangedValues() - { - $obj = StripeObject::constructFrom([ - 'foo' => null, - ]); - $this->assertSame([], $obj->serializeParameters()); - } - - public function testSerializeParametersOnUnchangedArray() - { - $obj = StripeObject::constructFrom([ - 'foo' => ['0-index', '1-index', '2-index'], - ]); - $obj->foo = ['0-index', '1-index', '2-index']; - $this->assertSame([], $obj->serializeParameters()); - } - - public function testSerializeParametersWithStripeObject() - { - $obj = StripeObject::constructFrom([]); - $obj->metadata = StripeObject::constructFrom(['foo' => 'bar']); - - $serialized = $obj->serializeParameters(); - $this->assertSame(['foo' => 'bar'], $serialized['metadata']); - } - - public function testSerializeParametersOnReplacedStripeObject() - { - $obj = StripeObject::constructFrom([ - 'metadata' => StripeObject::constructFrom(['bar' => 'foo']), - ]); - $obj->metadata = StripeObject::constructFrom(['baz' => 'foo']); - - $serialized = $obj->serializeParameters(); - $this->assertSame(['bar' => '', 'baz' => 'foo'], $serialized['metadata']); - } - - public function testSerializeParametersOnArrayOfStripeObjects() - { - $obj = StripeObject::constructFrom([]); - $obj->metadata = [ - StripeObject::constructFrom(['foo' => 'bar']), - ]; - - $serialized = $obj->serializeParameters(); - $this->assertSame([['foo' => 'bar']], $serialized['metadata']); - } - - public function testSerializeParametersOnSetApiResource() - { - $customer = Customer::constructFrom(['id' => 'cus_123']); - $obj = StripeObject::constructFrom([]); - - // the key here is that the property is set explicitly (and therefore - // marked as unsaved), which is why it gets included below - $obj->customer = $customer; - - $serialized = $obj->serializeParameters(); - $this->assertSame(['customer' => $customer], $serialized); - } - - public function testSerializeParametersOnNotSetApiResource() - { - $customer = Customer::constructFrom(['id' => 'cus_123']); - $obj = StripeObject::constructFrom(['customer' => $customer]); - - $serialized = $obj->serializeParameters(); - $this->assertSame([], $serialized); - } - - public function testSerializeParametersOnApiResourceFlaggedWithSaveWithParent() - { - $customer = Customer::constructFrom(['id' => 'cus_123']); - $customer->saveWithParent = true; - - $obj = StripeObject::constructFrom(['customer' => $customer]); - - $serialized = $obj->serializeParameters(); - $this->assertSame(['customer' => []], $serialized); - } - - public function testSerializeParametersRaisesExceotionOnOtherEmbeddedApiResources() - { - // This customer doesn't have an ID and therefore the library doesn't know - // what to do with it and throws an InvalidArgumentException because it's - // probably not what the user expected to happen. - $customer = Customer::constructFrom([]); - - $obj = StripeObject::constructFrom([]); - $obj->customer = $customer; - - try { - $serialized = $obj->serializeParameters(); - $this->fail("Did not raise error"); - } catch (\InvalidArgumentException $e) { - $this->assertSame( - "Cannot save property `customer` containing an API resource of type Stripe\Customer. " . - "It doesn't appear to be persisted and is not marked as `saveWithParent`.", - $e->getMessage() - ); - } catch (\Exception $e) { - $this->fail("Unexpected exception: " . get_class($e)); - } - } - - public function testSerializeParametersForce() - { - $obj = StripeObject::constructFrom([ - 'id' => 'id', - 'metadata' => StripeObject::constructFrom([ - 'bar' => 'foo', - ]), - ]); - - $serialized = $obj->serializeParameters(true); - $this->assertSame(['id' => 'id', 'metadata' => ['bar' => 'foo']], $serialized); - } - - public function testDirty() - { - $obj = StripeObject::constructFrom([ - 'id' => 'id', - 'metadata' => StripeObject::constructFrom([ - 'bar' => 'foo', - ]), - ]); - - // note that `$force` and `dirty()` are for different things, but are - // functionally equivalent - $obj->dirty(); - - $serialized = $obj->serializeParameters(); - $this->assertSame(['id' => 'id', 'metadata' => ['bar' => 'foo']], $serialized); - } - - public function testDeepCopy() - { - $opts = [ - "api_base" => Stripe::$apiBase, - "api_key" => "apikey", - ]; - $values = [ - "id" => 1, - "name" => "Stripe", - "arr" => [ - StripeObject::constructFrom(["id" => "index0"], $opts), - "index1", - 2, - ], - "map" => [ - "0" => StripeObject::constructFrom(["id" => "index0"], $opts), - "1" => "index1", - "2" => 2 - ], - ]; - - $copyValues = $this->deepCopyReflector->invoke(null, $values); - - // we can't compare the hashes directly because they have embedded - // objects which are different from each other - $this->assertEquals($values["id"], $copyValues["id"]); - $this->assertEquals($values["name"], $copyValues["name"]); - $this->assertEquals(count($values["arr"]), count($copyValues["arr"])); - - // internal values of the copied StripeObject should be the same, - // but the object itself should be new (hence the assertNotSame) - $this->assertEquals($values["arr"][0]["id"], $copyValues["arr"][0]["id"]); - $this->assertNotSame($values["arr"][0], $copyValues["arr"][0]); - - // likewise, the Util\RequestOptions instance in _opts should have - // copied values but be a new instance - $this->assertEquals( - $this->optsReflector->getValue($values["arr"][0]), - $this->optsReflector->getValue($copyValues["arr"][0]) - ); - $this->assertNotSame( - $this->optsReflector->getValue($values["arr"][0]), - $this->optsReflector->getValue($copyValues["arr"][0]) - ); - - // scalars however, can be compared - $this->assertEquals($values["arr"][1], $copyValues["arr"][1]); - $this->assertEquals($values["arr"][2], $copyValues["arr"][2]); - - // and a similar story with the hash - $this->assertEquals($values["map"]["0"]["id"], $copyValues["map"]["0"]["id"]); - $this->assertNotSame($values["map"]["0"], $copyValues["map"]["0"]); - $this->assertNotSame( - $this->optsReflector->getValue($values["arr"][0]), - $this->optsReflector->getValue($copyValues["arr"][0]) - ); - $this->assertEquals( - $this->optsReflector->getValue($values["map"]["0"]), - $this->optsReflector->getValue($copyValues["map"]["0"]) - ); - $this->assertNotSame( - $this->optsReflector->getValue($values["map"]["0"]), - $this->optsReflector->getValue($copyValues["map"]["0"]) - ); - $this->assertEquals($values["map"]["1"], $copyValues["map"]["1"]); - $this->assertEquals($values["map"]["2"], $copyValues["map"]["2"]); - } - - public function testDeepCopyMaintainClass() - { - $charge = Charge::constructFrom(["id" => 1], null); - $copyCharge = $this->deepCopyReflector->invoke(null, $charge); - $this->assertEquals(get_class($charge), get_class($copyCharge)); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/StripeTest.php b/htdocs/includes/stripe/tests/Stripe/StripeTest.php deleted file mode 100644 index f594518d13d..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/StripeTest.php +++ /dev/null @@ -1,30 +0,0 @@ -orig = [ - 'caBundlePath' => Stripe::$caBundlePath, - ]; - } - - /** - * @after - */ - public function restoreOriginalValues() - { - Stripe::$caBundlePath = $this->orig['caBundlePath']; - } - - public function testCABundlePathAccessors() - { - Stripe::setCABundlePath('path/to/ca/bundle'); - $this->assertEquals('path/to/ca/bundle', Stripe::getCABundlePath()); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/SubscriptionItemTest.php b/htdocs/includes/stripe/tests/Stripe/SubscriptionItemTest.php deleted file mode 100644 index 09e766c1bec..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/SubscriptionItemTest.php +++ /dev/null @@ -1,77 +0,0 @@ -expectsRequest( - 'get', - '/v1/subscription_items' - ); - $resources = SubscriptionItem::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\SubscriptionItem", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/subscription_items/' . self::TEST_RESOURCE_ID - ); - $resource = SubscriptionItem::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\SubscriptionItem", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/subscription_items' - ); - $resource = SubscriptionItem::create([ - "plan" => "plan", - "subscription" => "sub_123" - ]); - $this->assertInstanceOf("Stripe\\SubscriptionItem", $resource); - } - - public function testIsSaveable() - { - $resource = SubscriptionItem::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/subscription_items/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\SubscriptionItem", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/subscription_items/' . self::TEST_RESOURCE_ID - ); - $resource = SubscriptionItem::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\SubscriptionItem", $resource); - } - - public function testIsDeletable() - { - $resource = SubscriptionItem::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/subscription_items/' . $resource->id - ); - $resource->delete(); - $this->assertInstanceOf("Stripe\\SubscriptionItem", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/SubscriptionTest.php b/htdocs/includes/stripe/tests/Stripe/SubscriptionTest.php deleted file mode 100644 index 4a42e218224..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/SubscriptionTest.php +++ /dev/null @@ -1,115 +0,0 @@ -expectsRequest( - 'get', - '/v1/subscriptions' - ); - $resources = Subscription::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Subscription", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/subscriptions/' . self::TEST_RESOURCE_ID - ); - $resource = Subscription::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/subscriptions' - ); - $resource = Subscription::create([ - "customer" => "cus_123", - "plan" => "plan" - ]); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - } - - public function testIsSaveable() - { - $resource = Subscription::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/subscriptions/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/subscriptions/' . self::TEST_RESOURCE_ID - ); - $resource = Subscription::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - } - - public function testIsCancelable() - { - $resource = Subscription::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/subscriptions/' . $resource->id, - [ - 'at_period_end' => 'true', - ] - ); - $resource->cancel([ - 'at_period_end' => true, - ]); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - } - - public function testCanDeleteDiscount() - { - $resource = Subscription::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'delete', - '/v1/subscriptions/' . $resource->id . '/discount' - ); - $resource->deleteDiscount(); - $this->assertInstanceOf("Stripe\\Subscription", $resource); - } - - public function testSerializeParametersItems() - { - $obj = Util\Util::convertToStripeObject([ - 'object' => 'subscription', - 'items' => Util\Util::convertToStripeObject([ - 'object' => 'list', - 'data' => [], - ], null), - ], null); - $obj->items = [ - ['id' => 'si_foo', 'deleted' => true], - ['plan' => 'plan_bar'], - ]; - $expected = [ - 'items' => [ - 0 => ['id' => 'si_foo', 'deleted' => true], - 1 => ['plan' => 'plan_bar'], - ], - ]; - $this->assertSame($expected, $obj->serializeParameters()); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/ThreeDSecureTest.php b/htdocs/includes/stripe/tests/Stripe/ThreeDSecureTest.php deleted file mode 100644 index f56e649cbc1..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/ThreeDSecureTest.php +++ /dev/null @@ -1,32 +0,0 @@ -expectsRequest( - 'get', - '/v1/3d_secure/' . self::TEST_RESOURCE_ID - ); - $resource = ThreeDSecure::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\ThreeDSecure", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/3d_secure' - ); - $resource = ThreeDSecure::create([ - "amount" => 100, - "currency" => "usd", - "return_url" => "url" - ]); - $this->assertInstanceOf("Stripe\\ThreeDSecure", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/TokenTest.php b/htdocs/includes/stripe/tests/Stripe/TokenTest.php deleted file mode 100644 index 36bb4bc8283..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/TokenTest.php +++ /dev/null @@ -1,28 +0,0 @@ -expectsRequest( - 'get', - '/v1/tokens/' . self::TEST_RESOURCE_ID - ); - $resource = Token::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Token", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/tokens' - ); - $resource = Token::create(["card" => "tok_visa"]); - $this->assertInstanceOf("Stripe\\Token", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/TopupTest.php b/htdocs/includes/stripe/tests/Stripe/TopupTest.php deleted file mode 100644 index 994447636c6..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/TopupTest.php +++ /dev/null @@ -1,69 +0,0 @@ -expectsRequest( - 'get', - '/v1/topups' - ); - $resources = Topup::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Topup", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/topups/' . self::TEST_RESOURCE_ID - ); - $resource = Topup::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Topup", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/topups' - ); - $resource = Topup::create([ - "amount" => 100, - "currency" => "usd", - "source" => "tok_123", - "description" => "description", - "statement_descriptor" => "statement descriptor" - ]); - $this->assertInstanceOf("Stripe\\Topup", $resource); - } - - public function testIsSaveable() - { - $resource = Topup::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/topups/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Topup", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/topups/' . self::TEST_RESOURCE_ID - ); - $resource = Topup::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Topup", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/TransferReversalTest.php b/htdocs/includes/stripe/tests/Stripe/TransferReversalTest.php deleted file mode 100644 index 37101c73208..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/TransferReversalTest.php +++ /dev/null @@ -1,21 +0,0 @@ -metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/transfers/' . $resource->transfer . '/reversals/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\TransferReversal", $resource); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/TransferTest.php b/htdocs/includes/stripe/tests/Stripe/TransferTest.php deleted file mode 100644 index d60d560e7c5..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/TransferTest.php +++ /dev/null @@ -1,140 +0,0 @@ -expectsRequest( - 'get', - '/v1/transfers' - ); - $resources = Transfer::all(); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\Transfer", $resources->data[0]); - } - - public function testIsRetrievable() - { - $this->expectsRequest( - 'get', - '/v1/transfers/' . self::TEST_RESOURCE_ID - ); - $resource = Transfer::retrieve(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\Transfer", $resource); - } - - public function testIsCreatable() - { - $this->expectsRequest( - 'post', - '/v1/transfers' - ); - $resource = Transfer::create([ - "amount" => 100, - "currency" => "usd", - "destination" => "acct_123" - ]); - $this->assertInstanceOf("Stripe\\Transfer", $resource); - } - - public function testIsSaveable() - { - $resource = Transfer::retrieve(self::TEST_RESOURCE_ID); - $resource->metadata["key"] = "value"; - $this->expectsRequest( - 'post', - '/v1/transfers/' . $resource->id - ); - $resource->save(); - $this->assertInstanceOf("Stripe\\Transfer", $resource); - } - - public function testIsUpdatable() - { - $this->expectsRequest( - 'post', - '/v1/transfers/' . self::TEST_RESOURCE_ID - ); - $resource = Transfer::update(self::TEST_RESOURCE_ID, [ - "metadata" => ["key" => "value"], - ]); - $this->assertInstanceOf("Stripe\\Transfer", $resource); - } - - public function testIsReversable() - { - $resource = Transfer::retrieve(self::TEST_RESOURCE_ID); - $this->expectsRequest( - 'post', - '/v1/transfers/' . $resource->id . '/reversals' - ); - $resource->reverse(); - $this->assertInstanceOf("Stripe\\Transfer", $resource); - } - - public function testIsCancelable() - { - $transfer = Transfer::retrieve(self::TEST_RESOURCE_ID); - - // stripe-mock does not support this anymore so we stub it - $this->stubRequest( - 'post', - '/v1/transfers/' . $transfer->id . '/cancel' - ); - $resource = $transfer->cancel(); - $this->assertInstanceOf("Stripe\\Transfer", $resource); - $this->assertSame($resource, $transfer); - } - - public function testCanCreateReversal() - { - $this->expectsRequest( - 'post', - '/v1/transfers/' . self::TEST_RESOURCE_ID . '/reversals' - ); - $resource = Transfer::createReversal(self::TEST_RESOURCE_ID); - $this->assertInstanceOf("Stripe\\TransferReversal", $resource); - } - - public function testCanRetrieveReversal() - { - $this->expectsRequest( - 'get', - '/v1/transfers/' . self::TEST_RESOURCE_ID . '/reversals/' . self::TEST_REVERSAL_ID - ); - $resource = Transfer::retrieveReversal(self::TEST_RESOURCE_ID, self::TEST_REVERSAL_ID); - $this->assertInstanceOf("Stripe\\TransferReversal", $resource); - } - - public function testCanUpdateReversal() - { - $this->expectsRequest( - 'post', - '/v1/transfers/' . self::TEST_RESOURCE_ID . '/reversals/' . self::TEST_REVERSAL_ID - ); - $resource = Transfer::updateReversal( - self::TEST_RESOURCE_ID, - self::TEST_REVERSAL_ID, - [ - "metadata" => ["key" => "value"], - ] - ); - $this->assertInstanceOf("Stripe\\TransferReversal", $resource); - } - - public function testCanListReversal() - { - $this->expectsRequest( - 'get', - '/v1/transfers/' . self::TEST_RESOURCE_ID . '/reversals' - ); - $resources = Transfer::allReversals(self::TEST_RESOURCE_ID); - $this->assertTrue(is_array($resources->data)); - $this->assertInstanceOf("Stripe\\TransferReversal", $resources->data[0]); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/Util/DefaultLoggerTest.php b/htdocs/includes/stripe/tests/Stripe/Util/DefaultLoggerTest.php deleted file mode 100644 index 711af03c4a0..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/Util/DefaultLoggerTest.php +++ /dev/null @@ -1,28 +0,0 @@ -error("message"); - - global $lastMessage; - $this->assertSame($lastMessage, "message"); - } -} - -// This is a little terrible, but unfortunately there's no clean way to stub a -// call to `error_log`. Here we overwrite it so that we can get the last arguments -// that went to it. This is obviously bad, but luckily it's constrained to -// being just in \Stripe\Util (i.e. won't interfere with PHPUnit for example) -// and _just_ present when tests are running. -function error_log($message) -{ - global $lastMessage; - $lastMessage = $message; -} diff --git a/htdocs/includes/stripe/tests/Stripe/Util/RequestOptionsTest.php b/htdocs/includes/stripe/tests/Stripe/Util/RequestOptionsTest.php deleted file mode 100644 index 558f73982ea..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/Util/RequestOptionsTest.php +++ /dev/null @@ -1,81 +0,0 @@ -assertSame("foo", $opts->apiKey); - $this->assertSame([], $opts->headers); - } - - public function testNull() - { - $opts = Util\RequestOptions::parse(null); - $this->assertSame(null, $opts->apiKey); - $this->assertSame([], $opts->headers); - } - - public function testEmptyArray() - { - $opts = Util\RequestOptions::parse([]); - $this->assertSame(null, $opts->apiKey); - $this->assertSame([], $opts->headers); - } - - public function testAPIKeyArray() - { - $opts = Util\RequestOptions::parse( - [ - 'api_key' => 'foo', - ] - ); - $this->assertSame('foo', $opts->apiKey); - $this->assertSame([], $opts->headers); - } - - public function testIdempotentKeyArray() - { - $opts = Util\RequestOptions::parse( - [ - 'idempotency_key' => 'foo', - ] - ); - $this->assertSame(null, $opts->apiKey); - $this->assertSame(['Idempotency-Key' => 'foo'], $opts->headers); - } - - public function testKeyArray() - { - $opts = Util\RequestOptions::parse( - [ - 'idempotency_key' => 'foo', - 'api_key' => 'foo' - ] - ); - $this->assertSame('foo', $opts->apiKey); - $this->assertSame(['Idempotency-Key' => 'foo'], $opts->headers); - } - - /** - * @expectedException Stripe\Error\Api - */ - public function testWrongType() - { - $opts = Util\RequestOptions::parse(5); - } - - public function testDiscardNonPersistentHeaders() - { - $opts = Util\RequestOptions::parse( - [ - 'stripe_account' => 'foo', - 'idempotency_key' => 'foo', - ] - ); - $opts->discardNonPersistentHeaders(); - $this->assertSame(['Stripe-Account' => 'foo'], $opts->headers); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/Util/UtilTest.php b/htdocs/includes/stripe/tests/Stripe/Util/UtilTest.php deleted file mode 100644 index cf5130208db..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/Util/UtilTest.php +++ /dev/null @@ -1,90 +0,0 @@ -assertTrue(Util\Util::isList($list)); - - $notlist = [5, 'nstaoush', [], 'bar' => 'baz']; - $this->assertFalse(Util\Util::isList($notlist)); - } - - public function testThatPHPHasValueSemanticsForArrays() - { - $original = ['php-arrays' => 'value-semantics']; - $derived = $original; - $derived['php-arrays'] = 'reference-semantics'; - - $this->assertSame('value-semantics', $original['php-arrays']); - } - - public function testConvertStripeObjectToArrayIncludesId() - { - $customer = Util\Util::convertToStripeObject([ - 'id' => 'cus_123', - 'object' => 'customer', - ], null); - $this->assertTrue(array_key_exists("id", $customer->__toArray(true))); - } - - public function testUtf8() - { - // UTF-8 string - $x = "\xc3\xa9"; - $this->assertSame(Util\Util::utf8($x), $x); - - // Latin-1 string - $x = "\xe9"; - $this->assertSame(Util\Util::utf8($x), "\xc3\xa9"); - - // Not a string - $x = true; - $this->assertSame(Util\Util::utf8($x), $x); - } - - public function testUrlEncode() - { - $a = [ - 'my' => 'value', - 'that' => ['your' => 'example'], - 'bar' => 1, - 'baz' => null - ]; - - $enc = Util\Util::urlEncode($a); - $this->assertSame('my=value&that%5Byour%5D=example&bar=1', $enc); - - $a = ['that' => ['your' => 'example', 'foo' => null]]; - $enc = Util\Util::urlEncode($a); - $this->assertSame('that%5Byour%5D=example', $enc); - - $a = ['that' => 'example', 'foo' => ['bar', 'baz']]; - $enc = Util\Util::urlEncode($a); - $this->assertSame('that=example&foo%5B%5D=bar&foo%5B%5D=baz', $enc); - - $a = [ - 'my' => 'value', - 'that' => ['your' => ['cheese', 'whiz', null]], - 'bar' => 1, - 'baz' => null - ]; - - $enc = Util\Util::urlEncode($a); - $expected = 'my=value&that%5Byour%5D%5B%5D=cheese' - . '&that%5Byour%5D%5B%5D=whiz&bar=1'; - $this->assertSame($expected, $enc); - - // Ignores an empty array - $enc = Util\Util::urlEncode(['foo' => [], 'bar' => 'baz']); - $expected = 'bar=baz'; - $this->assertSame($expected, $enc); - - $a = ['foo' => [['bar' => 'baz'], ['bar' => 'bin']]]; - $enc = Util\Util::urlEncode($a); - $this->assertSame('foo%5B0%5D%5Bbar%5D=baz&foo%5B1%5D%5Bbar%5D=bin', $enc); - } -} diff --git a/htdocs/includes/stripe/tests/Stripe/WebhookTest.php b/htdocs/includes/stripe/tests/Stripe/WebhookTest.php deleted file mode 100644 index dcd82671afc..00000000000 --- a/htdocs/includes/stripe/tests/Stripe/WebhookTest.php +++ /dev/null @@ -1,110 +0,0 @@ -generateHeader(); - $event = Webhook::constructEvent(self::EVENT_PAYLOAD, $sigHeader, self::SECRET); - $this->assertEquals("evt_test_webhook", $event->id); - } - - /** - * @expectedException \UnexpectedValueException - */ - public function testInvalidJson() - { - $payload = "this is not valid JSON"; - $sigHeader = $this->generateHeader(["payload" => $payload]); - Webhook::constructEvent($payload, $sigHeader, self::SECRET); - } - - /** - * @expectedException \Stripe\Error\SignatureVerification - */ - public function testValidJsonAndInvalidHeader() - { - $sigHeader = "bad_header"; - Webhook::constructEvent(self::EVENT_PAYLOAD, $sigHeader, self::SECRET); - } - - /** - * @expectedException \Stripe\Error\SignatureVerification - * @expectedExceptionMessage Unable to extract timestamp and signatures from header - */ - public function testMalformedHeader() - { - $sigHeader = "i'm not even a real signature header"; - WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET); - } - - /** - * @expectedException \Stripe\Error\SignatureVerification - * @expectedExceptionMessage No signatures found with expected scheme - */ - public function testNoSignaturesWithExpectedScheme() - { - $sigHeader = $this->generateHeader(["scheme" => "v0"]); - WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET); - } - - /** - * @expectedException \Stripe\Error\SignatureVerification - * @expectedExceptionMessage No signatures found matching the expected signature for payload - */ - public function testNoValidSignatureForPayload() - { - $sigHeader = $this->generateHeader(["signature" => "bad_signature"]); - WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET); - } - - /** - * @expectedException \Stripe\Error\SignatureVerification - * @expectedExceptionMessage Timestamp outside the tolerance zone - */ - public function testTimestampOutsideTolerance() - { - $sigHeader = $this->generateHeader(["timestamp" => time() - 15]); - WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET, 10); - } - - public function testValidHeaderAndSignature() - { - $sigHeader = $this->generateHeader(); - $this->assertTrue(WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET, 10)); - } - - public function testHeaderContainsValidSignature() - { - $sigHeader = $this->generateHeader() . ",v1=bad_signature"; - $this->assertTrue(WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET, 10)); - } - - public function testTimestampOffButNoTolerance() - { - $sigHeader = $this->generateHeader(["timestamp" => 12345]); - $this->assertTrue(WebhookSignature::verifyHeader(self::EVENT_PAYLOAD, $sigHeader, self::SECRET)); - } -} diff --git a/htdocs/includes/stripe/tests/TestCase.php b/htdocs/includes/stripe/tests/TestCase.php deleted file mode 100644 index 840c0ec58c1..00000000000 --- a/htdocs/includes/stripe/tests/TestCase.php +++ /dev/null @@ -1,177 +0,0 @@ -origApiBase = Stripe::$apiBase; - $this->origApiKey = Stripe::getApiKey(); - $this->origClientId = Stripe::getClientId(); - $this->origApiVersion = Stripe::getApiVersion(); - $this->origAccountId = Stripe::getAccountId(); - - // Set up host and credentials for stripe-mock - Stripe::$apiBase = "http://localhost:" . MOCK_PORT; - Stripe::setApiKey("sk_test_123"); - Stripe::setClientId("ca_123"); - Stripe::setApiVersion(null); - Stripe::setAccountId(null); - - // Set up the HTTP client mocker - $this->clientMock = $this->getMock('\Stripe\HttpClient\ClientInterface'); - - // By default, use the real HTTP client - ApiRequestor::setHttpClient(HttpClient\CurlClient::instance()); - } - - protected function tearDown() - { - // Restore original values - Stripe::$apiBase = $this->origApiBase; - Stripe::setApiKey($this->origApiKey); - Stripe::setClientId($this->origClientId); - Stripe::setApiVersion($this->origApiVersion); - Stripe::setAccountId($this->origAccountId); - } - - /** - * Sets up a request expectation with the provided parameters. The request - * will actually go through and be emitted. - * - * @param string $method HTTP method (e.g. 'post', 'get', etc.) - * @param string $path relative path (e.g. '/v1/charges') - * @param array|null $params array of parameters. If null, parameters will - * not be checked. - * @param string[]|null $headers array of headers. Does not need to be - * exhaustive. If null, headers are not checked. - * @param bool $hasFile Whether the request parameters contains a file. - * Defaults to false. - */ - protected function expectsRequest( - $method, - $path, - $params = null, - $headers = null, - $hasFile = false - ) { - $this->prepareRequestMock($method, $path, $params, $headers, $hasFile) - ->will($this->returnCallback( - function ($method, $absUrl, $headers, $params, $hasFile) { - $curlClient = HttpClient\CurlClient::instance(); - ApiRequestor::setHttpClient($curlClient); - return $curlClient->request($method, $absUrl, $headers, $params, $hasFile); - } - )); - } - - /** - * Sets up a request expectation with the provided parameters. The request - * will not actually be emitted, instead the provided response parameters - * will be returned. - * - * @param string $method HTTP method (e.g. 'post', 'get', etc.) - * @param string $path relative path (e.g. '/v1/charges') - * @param array|null $params array of parameters. If null, parameters will - * not be checked. - * @param string[]|null $headers array of headers. Does not need to be - * exhaustive. If null, headers are not checked. - * @param bool $hasFile Whether the request parameters contains a file. - * Defaults to false. - * @param array $response - * @param integer $rcode - * @param string|null $base - * - * @return array - */ - protected function stubRequest( - $method, - $path, - $params = null, - $headers = null, - $hasFile = false, - $response = [], - $rcode = 200, - $base = null - ) { - $this->prepareRequestMock($method, $path, $params, $headers, $hasFile, $base) - ->willReturn([json_encode($response), $rcode, []]); - } - - /** - * Prepares the client mocker for an invocation of the `request` method. - * This helper method is used by both `expectsRequest` and `stubRequest` to - * prepare the client mocker to expect an invocation of the `request` method - * with the provided arguments. - * - * @param string $method HTTP method (e.g. 'post', 'get', etc.) - * @param string $path relative path (e.g. '/v1/charges') - * @param array|null $params array of parameters. If null, parameters will - * not be checked. - * @param string[]|null $headers array of headers. Does not need to be - * exhaustive. If null, headers are not checked. - * @param bool $hasFile Whether the request parameters contains a file. - * Defaults to false. - * @param string|null $base base URL (e.g. 'https://api.stripe.com') - * - * @return PHPUnit_Framework_MockObject_Builder_InvocationMocker - */ - private function prepareRequestMock( - $method, - $path, - $params = null, - $headers = null, - $hasFile = false, - $base = null - ) { - ApiRequestor::setHttpClient($this->clientMock); - - if ($base === null) { - $base = Stripe::$apiBase; - } - $absUrl = $base . $path; - - return $this->clientMock - ->expects($this->once()) - ->method('request') - ->with( - $this->identicalTo(strtolower($method)), - $this->identicalTo($absUrl), - // for headers, we only check that all of the headers provided in $headers are - // present in the list of headers of the actual request - $headers === null ? $this->anything() : $this->callback(function ($array) use ($headers) { - foreach ($headers as $header) { - if (!in_array($header, $array)) { - return false; - } - } - return true; - }), - $params === null ? $this->anything() : $this->identicalTo($params), - $this->identicalTo($hasFile) - ); - } -} diff --git a/htdocs/includes/stripe/tests/bootstrap.no_autoload.php b/htdocs/includes/stripe/tests/bootstrap.no_autoload.php deleted file mode 100644 index 7011a3f4782..00000000000 --- a/htdocs/includes/stripe/tests/bootstrap.no_autoload.php +++ /dev/null @@ -1,5 +0,0 @@ -payb { $langs->load("paybox"); - // TODO + // TODO Chek setup is complete $validpaymentmethod['paybox']='valid'; } @@ -425,187 +425,238 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $error = 0; $errormessage = ''; - try { - $metadata = array( - 'dol_version' => DOL_VERSION, - 'dol_entity' => $conf->entity, - 'dol_company' => $mysoc->name, // Usefull when using multicompany - 'ipaddress'=> getUserRemoteIP() - ); + if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + { + try { + $metadata = array( + 'dol_version' => DOL_VERSION, + 'dol_entity' => $conf->entity, + 'dol_company' => $mysoc->name, // Usefull when using multicompany + 'ipaddress'=> getUserRemoteIP() + ); - if (! empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; + if (! empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; - if ($thirdparty_id > 0) - { - dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe'); + if ($thirdparty_id > 0) + { + dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe'); - $service = 'StripeTest'; - $servicestatus = 0; - if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'int')) - { - $service = 'StripeLive'; - $servicestatus = 1; - } + $service = 'StripeTest'; + $servicestatus = 0; + if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'int')) + { + $service = 'StripeLive'; + $servicestatus = 1; + } - $thirdparty = new Societe($db); - $thirdparty->fetch($thirdparty_id); + $thirdparty = new Societe($db); + $thirdparty->fetch($thirdparty_id); - // Create Stripe customer - include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; - $stripe = new Stripe($db); - $stripeacc = $stripe->getStripeAccount($service); - $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1); + // Create Stripe customer + include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; + $stripe = new Stripe($db); + $stripeacc = $stripe->getStripeAccount($service); + $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1); - // Create Stripe card from Token - if ($savesource) { - $card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata)); - } else { - $card = $stripeToken; - } + // Create Stripe card from Token + if ($savesource) { + $card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata)); + } else { + $card = $stripeToken; + } - if (empty($card)) - { - $error++; - dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe'); - setEventMessages('Failed to create card record', null, 'errors'); - $action=''; - } - else - { - if (! empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; - if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; - if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (empty($card)) + { + $error++; + dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe'); + setEventMessages('Failed to create card record', null, 'errors'); + $action=''; + } + else + { + if (! empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; + if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; + if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; - dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe'); - $charge = \Stripe\Charge::create(array( - 'amount' => price2num($amountstripe, 'MU'), - 'currency' => $currency, - 'capture' => true, // Charge immediatly - 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, - 'metadata' => $metadata, - 'customer' => $customer->id, - 'source' => $card, - 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) - ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); - // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) - if (empty($charge)) - { - $error++; - dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); - setEventMessages('Failed to charge card', null, 'errors'); - $action=''; - } - } - } - else - { - $vatcleaned = $vatnumber ? $vatnumber : null; + dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe'); + $charge = \Stripe\Charge::create(array( + 'amount' => price2num($amountstripe, 'MU'), + 'currency' => $currency, + 'capture' => true, // Charge immediatly + 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, + 'metadata' => $metadata, + 'customer' => $customer->id, + 'source' => $card, + 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); + // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) + if (empty($charge)) + { + $error++; + dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); + setEventMessages('Failed to charge card', null, 'errors'); + $action=''; + } + } + } + else + { + $vatcleaned = $vatnumber ? $vatnumber : null; - $taxinfo = array('type'=>'vat'); - if ($vatcleaned) - { - $taxinfo["tax_id"] = $vatcleaned; - } - // We force data to "null" if not defined as expected by Stripe - if (empty($vatcleaned)) $taxinfo=null; + $taxinfo = array('type'=>'vat'); + if ($vatcleaned) + { + $taxinfo["tax_id"] = $vatcleaned; + } + // We force data to "null" if not defined as expected by Stripe + if (empty($vatcleaned)) $taxinfo=null; - dol_syslog("Create anonymous customer card profile", LOG_DEBUG, 0, '_stripe'); - $customer = \Stripe\Customer::create(array( - 'email' => $email, - 'description' => ($email?'Anonymous customer for '.$email:'Anonymous customer'), - 'metadata' => $metadata, - 'tax_info' => $taxinfo, - 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) - )); - // Return $customer = array('id'=>'cus_XXXX', ...) + dol_syslog("Create anonymous customer card profile", LOG_DEBUG, 0, '_stripe'); + $customer = \Stripe\Customer::create(array( + 'email' => $email, + 'description' => ($email?'Anonymous customer for '.$email:'Anonymous customer'), + 'metadata' => $metadata, + 'tax_info' => $taxinfo, + 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) + )); + // Return $customer = array('id'=>'cus_XXXX', ...) - if (! empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; - if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; - if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (! empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; + if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; + if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; - // The customer was just created with a source, so we can make a charge - // with no card defined, the source just used for customer creation will be used. - dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); - $charge = \Stripe\Charge::create(array( - 'customer' => $customer->id, - 'amount' => price2num($amountstripe, 'MU'), - 'currency' => $currency, - 'capture' => true, // Charge immediatly - 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, - 'metadata' => $metadata, - 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) - ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); - // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) - if (empty($charge)) - { - $error++; - dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); - setEventMessages('Failed to charge card', null, 'errors'); - $action=''; - } - } - } catch(\Stripe\Error\Card $e) { - // Since it's a decline, \Stripe\Error\Card will be caught - $body = $e->getJsonBody(); - $err = $body['error']; + // The customer was just created with a source, so we can make a charge + // with no card defined, the source just used for customer creation will be used. + dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); + $charge = \Stripe\Charge::create(array( + 'customer' => $customer->id, + 'amount' => price2num($amountstripe, 'MU'), + 'currency' => $currency, + 'capture' => true, // Charge immediatly + 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, + 'metadata' => $metadata, + 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); + // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) + if (empty($charge)) + { + $error++; + dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); + setEventMessages('Failed to charge card', null, 'errors'); + $action=''; + } + } + } catch(\Stripe\Error\Card $e) { + // Since it's a decline, \Stripe\Error\Card will be caught + $body = $e->getJsonBody(); + $err = $body['error']; - print('Status is:' . $e->getHttpStatus() . "\n"); - print('Type is:' . $err['type'] . "\n"); - print('Code is:' . $err['code'] . "\n"); - // param is '' in this case - print('Param is:' . $err['param'] . "\n"); - print('Message is:' . $err['message'] . "\n"); + print('Status is:' . $e->getHttpStatus() . "\n"); + print('Type is:' . $err['type'] . "\n"); + print('Code is:' . $err['code'] . "\n"); + // param is '' in this case + print('Param is:' . $err['param'] . "\n"); + print('Message is:' . $err['message'] . "\n"); + + $error++; + $errormessage="ErrorCard ".$e->getMessage()." err=".var_export($err, true); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\RateLimit $e) { + // Too many requests made to the API too quickly + $error++; + $errormessage="ErrorRateLimit ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\InvalidRequest $e) { + // Invalid parameters were supplied to Stripe's API + $error++; + $errormessage="ErrorInvalidRequest ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\Authentication $e) { + // Authentication with Stripe's API failed + // (maybe you changed API keys recently) + $error++; + $errormessage="ErrorAuthentication ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\ApiConnection $e) { + // Network communication with Stripe failed + $error++; + $errormessage="ErrorApiConnection ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\Base $e) { + // Display a very generic error to the user, and maybe send + // yourself an email + $error++; + $errormessage="ErrorBase ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (Exception $e) { + // Something else happened, completely unrelated to Stripe + $error++; + $errormessage="ErrorException ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } + } + + if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + { + $service = 'StripeTest'; + $servicestatus = 0; + if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'int')) + { + $service = 'StripeLive'; + $servicestatus = 1; + } + include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; + $stripe = new Stripe($db); + $stripeacc = $stripe->getStripeAccount($service); + + // We go here if $conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION is set. + // In such a case, payment is always ok when we call the "charge" action. + $paymentintent_id = GETPOST("paymentintent_id", "alpha"); + + // Force to use the correct API key + global $stripearrayofkeysbyenv; + \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']); + + try { + if (empty($key)) { // If the Stripe connect account not set, we use common API usage + $paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id); + } else { + $paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc)); + } + } + catch(Exception $e) + { + $error++; + $errormessage="CantRetreivePaymentIntent ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } + + if ($paymentintent->status != 'succeeded') + { + $error++; + $errormessage="StatusOfRetreivedIntent is not succeeded: ".$e->getMessage(); + dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } + } - $error++; - $errormessage="ErrorCard ".$e->getMessage()." err=".var_export($err, true); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } catch (\Stripe\Error\RateLimit $e) { - // Too many requests made to the API too quickly - $error++; - $errormessage="ErrorRateLimit ".$e->getMessage(); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } catch (\Stripe\Error\InvalidRequest $e) { - // Invalid parameters were supplied to Stripe's API - $error++; - $errormessage="ErrorInvalidRequest ".$e->getMessage(); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } catch (\Stripe\Error\Authentication $e) { - // Authentication with Stripe's API failed - // (maybe you changed API keys recently) - $error++; - $errormessage="ErrorAuthentication ".$e->getMessage(); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } catch (\Stripe\Error\ApiConnection $e) { - // Network communication with Stripe failed - $error++; - $errormessage="ErrorApiConnection ".$e->getMessage(); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } catch (\Stripe\Error\Base $e) { - // Display a very generic error to the user, and maybe send - // yourself an email - $error++; - $errormessage="ErrorBase ".$e->getMessage(); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } catch (Exception $e) { - // Something else happened, completely unrelated to Stripe - $error++; - $errormessage="ErrorException ".$e->getMessage(); - dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); - $action=''; - } $remoteip = getUserRemoteIP(); @@ -615,7 +666,7 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $_SESSION["paymentType"] = ''; $_SESSION['ipaddress'] = ($remoteip?$remoteip:'unknown'); // Payer ip $_SESSION['payerID'] = is_object($customer)?$customer->id:''; - $_SESSION['TRANSACTIONID'] = is_object($charge)?$charge->id:''; + $_SESSION['TRANSACTIONID'] = (is_object($charge) ? $charge->id : (is_object($paymentintent) ? $paymentintent->id : '')); $_SESSION['errormessage'] = $errormessage; dol_syslog("Action charge stripe ip=".$remoteip, LOG_DEBUG, 0, '_stripe'); @@ -768,8 +819,8 @@ $object = null; if (! $source) { $found=true; - $tag=GETPOST("tag"); - $fulltag=$tag; + $tag=GETPOST("tag", 'alpha'); + $fulltag="TAG=".$tag; // Creditor print ''.$langs->trans("Creditor"); @@ -818,12 +869,9 @@ if (! $source) $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = null; - // for dev only - print ''.$langs->trans("PaymentIntent"); - print ''; - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, $object, $stripecu, $stripeacc, $servicestatus); - print ''.$paymentintent->id.''; - print ''."\n"; + + $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag, $object, $stripecu, $stripeacc, $servicestatus); + if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); } // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum // as they don't exists (buyer is unknown, tag is free). @@ -848,9 +896,8 @@ if ($source == 'order') else { $result=$order->fetch_thirdparty($order->socid); - - $object = $order; } + $object = $order; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { @@ -860,7 +907,6 @@ if ($source == 'order') } $fulltag='ORD='.$order->id.'.CUS='.$order->thirdparty->id; - //$fulltag.='.NAM='.strtr($order->thirdparty->name,"-"," "); if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } $fulltag=dol_string_unaccent($fulltag); @@ -933,12 +979,9 @@ if ($source == 'order') $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = $stripe->customerStripe($order->thirdparty, $stripeacc, $servicestatus, 1); - // for dev only - print ''.$langs->trans("PaymentIntent"); - print ''; - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, $object, $stripecu, $stripeacc, $servicestatus); - print ''.$paymentintent->id.''; - print ''."\n"; + + $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag.' ref='.$object->ref, $object, $stripecu, $stripeacc, $servicestatus); + if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); } // Shipping address @@ -992,9 +1035,8 @@ if ($source == 'invoice') else { $result=$invoice->fetch_thirdparty($invoice->socid); - - $object = $invoice; } + $object = $invoice; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { @@ -1083,12 +1125,9 @@ if ($source == 'invoice') $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = $stripe->customerStripe($invoice->thirdparty, $stripeacc, $servicestatus, 1); - // for dev only - print ''.$langs->trans("PaymentIntent"); - print ''; - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, $object, $stripecu, $stripeacc, $servicestatus); - print ''.$paymentintent->id.''; - print ''."\n"; + + $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag.' ref='.$object->ref, $object, $stripecu, $stripeacc, $servicestatus); + if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); } // Shipping address @@ -1144,8 +1183,6 @@ if ($source == 'contractline') { if ($contractline->fk_contrat > 0) { - $object = $contractline; - $result=$contract->fetch($contractline->fk_contrat); if ($result > 0) { @@ -1163,6 +1200,7 @@ if ($source == 'contractline') $error++; } } + $object = $contractline; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { @@ -1317,12 +1355,9 @@ if ($source == 'contractline') $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = null; - // for dev only - print ''.$langs->trans("PaymentIntent"); - print ''; - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, $object, $stripecu, $stripeacc, $servicestatus); - print ''.$paymentintent->id.''; - print ''."\n"; + + $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag." ref=".$object->ref, $object, $stripecu, $stripeacc, $servicestatus); + if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); } // Shipping address @@ -1376,9 +1411,9 @@ if ($source == 'membersubscription') else { $member->fetch_thirdparty(); - $object = $member; $subscription=new Subscription($db); } + $object = $member; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { @@ -1506,12 +1541,9 @@ if ($source == 'membersubscription') $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = null; - // for dev only - print ''.$langs->trans("PaymentIntent"); - print ''; - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, $object, $stripecu, $stripeacc, $servicestatus); - print ''.$paymentintent->id.''; - print ''."\n"; + + $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag." ref=".$object->ref, $object, $stripecu, $stripeacc, $servicestatus); + if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); } // Shipping address @@ -1564,8 +1596,8 @@ if ($source == 'donation') else { $don->fetch_thirdparty(); - $object = $don; } + $object = $don; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { @@ -1670,12 +1702,9 @@ if ($source == 'donation') $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = $stripe->customerStripe($don->thirdparty, $stripeacc, $servicestatus, 1); - // for dev only - print ''.$langs->trans("PaymentIntent"); - print ''; - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, $object, $stripecu, $stripeacc, $servicestatus); - print ''.$paymentintent->id.''; - print ''."\n"; + + $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag." ref=".$object->ref, $object, $stripecu, $stripeacc, $servicestatus); + if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); } // Shipping address @@ -1718,6 +1747,7 @@ if ($mesg) print '
'. print ''."\n"; print "\n"; + if ($action != 'dopayment') { if ($found && ! $error) // We are in a management option and no error @@ -1748,13 +1778,13 @@ if ($action != 'dopayment') if ((empty($paymentmethod) || $paymentmethod == 'paybox') && ! empty($conf->paybox->enabled)) { // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of paybox - print '
'; + print '
'; } if ((empty($paymentmethod) || $paymentmethod == 'stripe') && ! empty($conf->stripe->enabled)) { // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of stripe - print '
'; + print '
'; } if ((empty($paymentmethod) || $paymentmethod == 'paypal') && ! empty($conf->paypal->enabled)) @@ -1763,11 +1793,11 @@ if ($action != 'dopayment') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') { - print '
'; + print '
'; } if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') { - print '
'; + print '
'; } } } @@ -1799,17 +1829,6 @@ if (preg_match('/^dopayment/', $action)) // Stripe if (GETPOST('dopayment_stripe', 'alpha')) { - // Simple checkout - /* - print ''; - */ - // Personalized checkout print ''; - print ' + print '
'; -
-
'; + print ''; print ''."\n"; print ''."\n"; @@ -1860,41 +1878,60 @@ if (preg_match('/^dopayment/', $action)) print ''; print ''; - print ' - - -
'; + if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || ! empty($paymentintent)) + { + print ' + + +
'; + + if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + { + print '
'; + } + + print ' +
+ + '; + + if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + { + print '
'; + } + + print '
+ +
+ + + + +
+ +
'; + + print ''; + print ''; + + print ' +
'; + } if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { - print '
'; + if (empty($paymentintent)) + { + print '
'.$langs->trans("Error").'
'; + } + else + { + print ''; + //$_SESSION["paymentintent_id"] = $paymentintent->id; + } } - print ' -
- - '; - - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { - print '
'; - } - - print '
- -
- - - - -
'; - - print '
- - -
- -
'."\n"; + print ''."\n"; print ''."\n"; @@ -1931,7 +1968,6 @@ if (preg_match('/^dopayment/', $action)) }; var cardElement = elements.create('card', {style: style}); - var cardholderName = document.getElementById('cardholder-name'); // Add an instance of the card Element into the `card-element`
cardElement.mount('#card-element'); @@ -1940,44 +1976,70 @@ if (preg_match('/^dopayment/', $action)) cardElement.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { - console.log("Show event error"); + console.log("Show event error (like 'Incorrect card number', ...)"); displayError.textContent = event.error.message; } else { - console.log("No error"); + console.log("Reset error message"); displayError.textContent = ''; } }); // Handle form submission + var cardholderName = document.getElementById('cardholder-name'); var cardButton = document.getElementById('buttontopay'); var clientSecret = cardButton.dataset.secret; cardButton.addEventListener('click', function(event) { - stripe.handleCardPayment( - clientSecret, cardElement, { - source_data: { - owner: { - name: cardholderName.value, + console.log("We click on buttontopay"); + event.preventDefault(); + + if (cardholderName.value == '') + { + console.log("Field Card holder is empty"); + var displayError = document.getElementById('card-errors'); + displayError.textContent = 'trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardOwner"))); ?>'; + } + else + { + stripe.handleCardPayment( + clientSecret, cardElement, { + payment_method_data: { + billing_details: { + name: cardholderName.value + , email: '', + thirdparty)) { ?>, phone: thirdparty->phone; ?>', + thirdparty)) { + print ', address: {'."\n"; + print ' city: '.$object->thirdparty->town.','; + print ' country: '.$object->thirdparty->country_code.','; + print ' line1: '.$object->thirdparty->address.','; + print ' postal_code: '.$object->thirdparty->zip; + print '}'."\n"; + } ?> + } /* TODO Add all other known data like emails, ... to be SCA compliant */ + }, + save_payment_method: false } - } + ).then(function(result) { + console.log(result); + if (result.error) { + console.log("Error on result of handleCardPayment"); + jQuery('#buttontopay').show(); + jQuery('#hourglasstopay').hide(); + // Inform the user if there was an error + var errorElement = document.getElementById('card-errors'); + errorElement.textContent = result.error.message; + } else { + // The payment has succeeded. Display a success message. + console.log("No error on result of handleCardPayment, so we submit the form"); + // Submit the form + jQuery('#buttontopay').hide(); + jQuery('#hourglasstopay').show(); + // Send form (action=charge that will do nothing) + jQuery('#payment-form').submit(); + } + }); } - ).then(function(result) { - jQuery('#buttontopay').hide(); - jQuery('#hourglasstopay').show(); - if (result.error) { - console.log("Error on result of handleCardPayment"); - jQuery('#buttontopay').show(); - jQuery('#hourglasstopay').hide(); - // Inform the user if there was an error - var errorElement = document.getElementById('card-errors'); - errorElement.textContent = result.error.message; - } else { - console.log("No error on result of handleCardPayment, so we submit the form"); - // Submit the form - jQuery('#buttontopay').hide(); - jQuery('#hourglasstopay').show(); - } - }); }); diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index 62d709fc674..52413921f90 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -280,7 +280,7 @@ $fulltag = $FULLTAG; $tmptag=dolExplodeIntoArray($fulltag, '.', '='); -dol_syslog("ispaymentok=".$ispaymentok, LOG_DEBUG, 0, '_payment'); +dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment'); // Make complementary actions @@ -296,7 +296,7 @@ if ($ispaymentok) $user->rights->facture->creer = 1; $user->rights->adherent->cotisation->creer = 1; - if (in_array('MEM', array_keys($tmptag))) + if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) { // Validate member // Create subscription @@ -583,7 +583,7 @@ if ($ispaymentok) $ispostactionok = -1; } } - elseif (in_array('INV', array_keys($tmptag))) + elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) { // Record payment include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -769,14 +769,14 @@ if ($ispaymentok) $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived"); $content=""; - if (in_array('MEM', array_keys($tmptag))) + if (array_key_exists('MEM', $tmptag)) { $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=''.$companylangs->trans("PaymentSubscription")."

\n"; $content.=$companylangs->trans("MemberId").': '.$tmptag['MEM']."
\n"; $content.=$companylangs->trans("Link").': '.$url.''."
\n"; } - elseif (in_array('INV', array_keys($tmptag))) + elseif (array_key_exists('INV', $tmptag)) { $url=$urlwithroot."/compta/facture/card.php?id=".$tmptag['INV']; $content.=''.$companylangs->trans("Payment")."

\n"; diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 1f2f39719a8..ee1c1a67f0a 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -243,6 +243,7 @@ class Stripe extends CommonObject * @param double $amount Amount * @param string $currency_code Currency code * @param string $tag Tag + * @param string $description Description * @param Societe $object Object to pay with Stripe * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe() * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect @@ -252,10 +253,14 @@ class Stripe extends CommonObject * @param boolean $confirmnow false=default, true=try to confirm immediatly after create (if conditions are ok) * @return \Stripe\PaymentIntent|null Stripe PaymentIntent or null if not found */ - public function getPaymentIntent($amount, $currency_code, $tag, $object = null, $customer = null, $key = null, $status = 0, $usethirdpartyemailforreceiptemail = 0, $mode = 'automatic', $confirmnow = false) + public function getPaymentIntent($amount, $currency_code, $tag, $description = '', $object = null, $customer = null, $key = null, $status = 0, $usethirdpartyemailforreceiptemail = 0, $mode = 'automatic', $confirmnow = false) { global $conf, $user, $mysoc; + dol_syslog("getPaymentIntent"); + + $error = 0; + if (empty($status)) $service = 'StripeTest'; else $service = 'StripeLive'; @@ -305,6 +310,7 @@ class Stripe extends CommonObject } catch(Exception $e) { + $error++; $this->error = $e->getMessage(); } } @@ -314,9 +320,6 @@ class Stripe extends CommonObject if (empty($paymentintent)) { $ipaddress=getUserRemoteIP(); - // Not enough space for a ref so we store id. Also with multicompany we can have same ref for 2 different - // object and we need a unique (this is used later as idempotency_key) - $description=$tag; $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); if (is_object($object)) { @@ -330,12 +333,14 @@ class Stripe extends CommonObject "amount" => $stripeamount, "currency" => $currency_code, "payment_method_types" => ["card"], - "statement_descriptor" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "description" => $description, + "statement_descriptor" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) "metadata" => $metadata ); if (! is_null($customer)) $dataforintent["customer"]=$customer; // save_payment_method = true, // payment_method = + //var_dump($dataforintent); if ($conf->entity!=$conf->global->STRIPECONNECT_PRINCIPAL && $fee>0) { @@ -353,9 +358,12 @@ class Stripe extends CommonObject if (empty($key)) { // If the Stripe connect account not set, we use common API usage $paymentintent = \Stripe\PaymentIntent::create($dataforintent, array("idempotency_key" => "$description")); + //$paymentintent = \Stripe\PaymentIntent::create($dataforintent, array()); } else { $paymentintent = \Stripe\PaymentIntent::create($dataforintent, array("idempotency_key" => "$description", "stripe_account" => $key)); + //$paymentintent = \Stripe\PaymentIntent::create($dataforintent, array("stripe_account" => $key)); } + //var_dump($paymentintent); // Store the payment intent if (is_object($object)) @@ -366,6 +374,7 @@ class Stripe extends CommonObject $resql = $this->db->query($sql); if (! $resql) { + $error++; $this->error = $this->db->lasterror(); dol_syslog(get_class($this) . "::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database."); } @@ -377,10 +386,18 @@ class Stripe extends CommonObject } catch(Exception $e) { + /*var_dump($dataforintent); + var_dump($description); + var_dump($key); + var_dump($paymentintent); + var_dump($e->getMessage());*/ + $error++; $this->error = $e->getMessage(); } } + dol_syslog("getPaymentIntent return error=".$error); + return $paymentintent; } diff --git a/htdocs/stripe/lib/stripe.lib.php b/htdocs/stripe/lib/stripe.lib.php index d806d6a39b3..100ce840e24 100644 --- a/htdocs/stripe/lib/stripe.lib.php +++ b/htdocs/stripe/lib/stripe.lib.php @@ -87,12 +87,12 @@ function showStripePaymentUrl($type, $ref) * @param string $freetag Free tag * @return string Url string */ -function getStripePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_free_tag') +function getStripePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_tag') { global $conf; $ref=str_replace(' ', '', $ref); - + if ($type == 'free') { $out=DOL_MAIN_URL_ROOT.'/public/stripe/newpayment.php?amount='.($mode?'':'').$amount.($mode?'':'').'&tag='.($mode?'':'').$freetag.($mode?'':''); diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php index b8ffa08fbaf..7302191fc84 100644 --- a/htdocs/theme/eldy/global.inc.php +++ b/htdocs/theme/eldy/global.inc.php @@ -132,19 +132,27 @@ input.smallpadd { /* Used for timesheet input */ input.buttongen { vertical-align: middle; } -input.buttonpayment { +input.buttonpayment, button.buttonpayment, div.buttonpayment { min-width: 320px; margin-bottom: 15px; background-image: none; line-height: 24px; padding: 8px; background: none; - padding-left: 38px; - text-align: ; - border: 1px solid #ddd; - background-color: #eee; + text-align: center; + border: 0; + background-color: #9999bb; white-space: normal; - box-shadow: 1px 1px 8px #bbb; + box-shadow: 1px 1px 4px #bbb; + color: #fff; + border-radius: 4px; +} +div.buttonpayment input { + background-color: unset; + color: #fff; + border-bottom: unset; + font-weight: bold; + text-transform: uppercase; } input.buttonpaymentcb { background-image: url(); @@ -3569,6 +3577,7 @@ div#card-errors { color: #fa755a; text-align: center; padding-top: 3px; + max-width: 320px; } diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index 755736eb79f..2906da3729c 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -352,18 +352,25 @@ input.smallpadd { /* Used for timesheet input */ input.buttongen { vertical-align: middle; } -input.buttonpayment { +input.buttonpayment, button.buttonpayment, div.buttonpayment { min-width: 320px; margin-bottom: 15px; background-image: none; line-height: 24px; padding: 8px; background: none; - padding-left: 30px; - text-align: ; + text-align: center; border: 2px solid #ccc; background-color: #eee; white-space: normal; + color: #888 !important; +} +div.buttonpayment input { + background-color: unset; + border-bottom: unset; + font-weight: bold; + text-transform: uppercase; + color: #333; } input.buttonpaymentcb { background-image: url(); @@ -3660,6 +3667,7 @@ div#card-errors { color: #fa755a; text-align: center; padding-top: 3px; + max-width: 320px; }