Giter Club home page Giter Club logo

stripe-php's Introduction

Stripe PHP bindings

Build Status Latest Stable Version Total Downloads License Code Coverage

The Stripe PHP library provides convenient access to the Stripe API from applications written in the PHP language. It includes a pre-defined set of classes for API resources that initialize themselves dynamically from API responses which makes it compatible with a wide range of versions of the Stripe API.

Requirements

PHP 5.6.0 and later.

Composer

You can install the bindings via Composer. Run the following command:

composer require stripe/stripe-php

To use the bindings, use Composer's autoload:

require_once 'vendor/autoload.php';

Manual Installation

If you do not wish to use Composer, you can download the latest release. Then, to use the bindings, include the init.php file.

require_once '/path/to/stripe-php/init.php';

Dependencies

The bindings require the following extensions in order to work properly:

  • curl, although you can use your own non-cURL client if you prefer
  • json
  • mbstring (Multibyte String)

If you use Composer, these dependencies should be handled automatically. If you install manually, you'll want to make sure that these extensions are available.

Getting Started

Simple usage looks like:

$stripe = new \Stripe\StripeClient('sk_test_BQokikJOvBiI2HlWgH4olfQ2');
$customer = $stripe->customers->create([
    'description' => 'example customer',
    'email' => '[email protected]',
    'payment_method' => 'pm_card_visa',
]);
echo $customer;

Client/service patterns vs legacy patterns

You can continue to use the legacy integration patterns used prior to version 7.33.0. Review the migration guide for the backwards-compatible client/services pattern changes.

Documentation

See the PHP API docs.

See video demonstrations covering how to use the library.

Legacy Version Support

PHP 5.4 & 5.5

If you are using PHP 5.4 or 5.5, you should consider upgrading your environment as those versions have been past end of life since September 2015 and July 2016 respectively. Otherwise, you can still use Stripe by downloading stripe-php v6.43.1 (zip, tar.gz) from our releases page. This version will work but might not support recent features we added since the version was released and upgrading PHP is the best course of action.

PHP 5.3

If you are using PHP 5.3, you should upgrade your environment as this version has been past end of life since August 2014. Otherwise, you can download v5.9.2 (zip, tar.gz) from our releases page. This version will continue to work with new versions of the Stripe API for all common uses.

Custom Request Timeouts

Note We do not recommend decreasing the timeout for non-read-only calls (e.g. charge creation), since even if you locally timeout, the request on Stripe's side can still complete. If you are decreasing timeouts on these calls, make sure to use idempotency tokens to avoid executing the same transaction twice as a result of timeout retry logic.

To modify request timeouts (connect or total, in seconds) you'll need to tell the API client to use a CurlClient other than its default. You'll set the timeouts in that CurlClient.

// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient();
$curl->setTimeout(10); // default is \Stripe\HttpClient\CurlClient::DEFAULT_TIMEOUT
$curl->setConnectTimeout(5); // default is \Stripe\HttpClient\CurlClient::DEFAULT_CONNECT_TIMEOUT

echo $curl->getTimeout(); // 10
echo $curl->getConnectTimeout(); // 5

// tell Stripe to use the tweaked client
\Stripe\ApiRequestor::setHttpClient($curl);

// use the Stripe API client as you normally would

Custom cURL Options (e.g. proxies)

Need to set a proxy for your requests? Pass in the requisite CURLOPT_* array to the CurlClient constructor, using the same syntax as curl_stopt_array(). This will set the default cURL options for each HTTP request made by the SDK, though many more common options (e.g. timeouts; see above on how to set those) will be overridden by the client even if set here.

// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient([CURLOPT_PROXY => 'proxy.local:80']);
// tell Stripe to use the tweaked client
\Stripe\ApiRequestor::setHttpClient($curl);

Alternately, a callable can be passed to the CurlClient constructor that returns the above array based on request inputs. See testDefaultOptions() in tests/CurlClientTest.php for an example of this behavior. Note that the callable is called at the beginning of every API request, before the request is sent.

Configuring a Logger

The library does minimal logging, but it can be configured with a PSR-3 compatible logger so that messages end up there instead of error_log:

\Stripe\Stripe::setLogger($logger);

Accessing response data

You can access the data from the last API response on any object via getLastResponse().

$customer = $stripe->customers->create([
    'description' => 'example customer',
]);
echo $customer->getLastResponse()->headers['Request-Id'];

SSL / TLS compatibility issues

Stripe's API now requires that all connections use TLS 1.2. Some systems (most notably some older CentOS and RHEL versions) are capable of using TLS 1.2 but will use TLS 1.0 or 1.1 by default. In this case, you'd get an invalid_request_error with the following error message: "Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.".

The recommended course of action is to upgrade your cURL and OpenSSL packages so that TLS 1.2 is used by default, but if that is not possible, you might be able to solve the issue by setting the CURLOPT_SSLVERSION option to either CURL_SSLVERSION_TLSv1 or CURL_SSLVERSION_TLSv1_2:

$curl = new \Stripe\HttpClient\CurlClient([CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1]);
\Stripe\ApiRequestor::setHttpClient($curl);

Per-request Configuration

For apps that need to use multiple keys during the lifetime of a process, like one that uses Stripe Connect, it's also possible to set a per-request key and/or account:

$customers = $stripe->customers->all([],[
    'api_key' => 'sk_test_...',
    'stripe_account' => 'acct_...'
]);

$stripe->customers->retrieve('cus_123456789', [], [
    'api_key' => 'sk_test_...',
    'stripe_account' => 'acct_...'
]);

Configuring CA Bundles

By default, the library will use its own internal bundle of known CA certificates, but it's possible to configure your own:

\Stripe\Stripe::setCABundlePath("path/to/ca/bundle");

Configuring Automatic Retries

The library can be configured to automatically retry requests that fail due to an intermittent network problem:

\Stripe\Stripe::setMaxNetworkRetries(2);

Idempotency keys are added to requests to guarantee that retries are safe.

Telemetry

By default, the library sends telemetry to Stripe regarding request latency and feature usage. These numbers help Stripe improve the overall latency of its API for all users, and improve popular features.

You can disable this behavior if you prefer:

\Stripe\Stripe::setEnableTelemetry(false);

Beta SDKs

Stripe has features in the beta phase that can be accessed via the beta version of this package. We would love for you to try these and share feedback with us before these features reach the stable phase. Use the composer require command with an exact version specified to install the beta version of the stripe-php pacakge.

composer require stripe/stripe-php:v9.2.0-beta.1

Note There can be breaking changes between beta versions. Therefore we recommend pinning the package version to a specific beta version in your composer.json file. This way you can install the same version each time without breaking changes unless you are intentionally looking for the latest beta version.

We highly recommend keeping an eye on when the beta feature you are interested in goes from beta to stable so that you can move from using a beta version of the SDK to the stable version.

If your beta feature requires a Stripe-Version header to be sent, set the apiVersion property of config object by using the function addBetaVersion:

Stripe::addBetaVersion("feature_beta", "v3");

Support

New features and bug fixes are released on the latest major version of the Stripe PHP library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.

Development

Get Composer. For example, on Mac OS:

brew install composer

Install dependencies:

composer install

The test suite depends on stripe-mock, so make sure to fetch and run it from a background terminal (stripe-mock's README also contains instructions for installing via Homebrew and other methods):

go install github.com/stripe/stripe-mock@latest
stripe-mock

Install dependencies as mentioned above (which will resolve PHPUnit), then you can run the test suite:

./vendor/bin/phpunit

Or to run an individual test file:

./vendor/bin/phpunit tests/Stripe/UtilTest.php

Update bundled CA certificates from the Mozilla cURL release:

./update_certs.php

The library uses PHP CS Fixer for code formatting. Code must be formatted before PRs are submitted, otherwise CI will fail. Run the formatter with:

./vendor/bin/php-cs-fixer fix -v .

Attention plugin developers

Are you writing a plugin that integrates Stripe and embeds our library? Then please use the setAppInfo function to identify your plugin. For example:

\Stripe\Stripe::setAppInfo("MyAwesomePlugin", "1.2.34", "https://myawesomeplugin.info");

The method should be called once, before any request is sent to the API. The second and third parameters are optional.

SSL / TLS configuration option

See the "SSL / TLS compatibility issues" paragraph above for full context. If you want to ensure that your plugin can be used on all systems, you should add a configuration option to let your users choose between different values for CURLOPT_SSLVERSION: none (default), CURL_SSLVERSION_TLSv1 and CURL_SSLVERSION_TLSv1_2.

stripe-php's People

Contributors

amber-stripe avatar anniel-stripe avatar bkrausz avatar boucher avatar brandur avatar brandur-stripe avatar chadicus avatar ctrudeau-stripe avatar dcr-stripe avatar evan-stripe avatar gdb avatar jpiasetz avatar kamil-stripe avatar kjc-stripe avatar kyleconroy avatar localheinz avatar michelle avatar michelle-stripe avatar nickdnk avatar ob-stripe avatar pakrym-stripe avatar ramya-stripe avatar rattrayalex-stripe avatar remi-stripe avatar richardm-stripe avatar richo avatar spakanati avatar stephen avatar stripe-openapi[bot] avatar yejia-stripe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stripe-php's Issues

`deleteDiscount` returns `null`

Working on an adapter for LithiumPHP and noticed that the deleteDiscount method always returns null upon success (verified coupon deletion in customer panel).

'id' field from charge no longer included in Stripe_Object::__toArray()

When creating a charge with Stripe_Charge::create() and calling __toArray() on the Stripe_Object result, the id field is no longer included in the returned array. I believe this is a regression introduced in version 1.7.14. Calling __get('id') still returns the id field correctly.

Observed in version 1.7.15.

CURLFile breaks old PHP + autoload

If you are on an older version of PHP like 5.3 and have an autoloader then our bindings break trying to find CURLFile with the following error:

include(CURLFile.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory

The error seems to be linked to this commit: 70d3599 which doesn't take the autoloader into account.

Unable to create new subscription

I am out of ideas right now so I have to report this as an issue in hopes someone knows what's going on.

When I call:

$stripe_customer = Stripe_Customer::retrieve($customer_id);
$response = $stripe_customer->subscriptions->create(array('plan' => 'test'));

I get the following error:

Call to undefined method Stripe_List::create() in...

That's where the script fails. I don't see anything else in logs. Creation of customer is successful and I can see it in dashboard logs.

Why static functions instead of OOP?

It's effectively impossible to write testable code utilising this abstraction layer, without all of your tests making real calls to the Stripe API.

Any OOP Stripe libraries available for PHP?

Error in docs for refunds

The docs say this for refunds:

$ch = Stripe_Charge::retrieve("ch_104EAo2B9zlNumWSyhdOZidB");
$re = $ch->refunds->create();

But that is not how refunds work, to make a refund you must do this:

$ch = Stripe_Charge::retrieve("ch_104EAo2B9zlNumWSyhdOZidB");
$re = $ch->refund();

Remove Support for PHP 5.2

PHP stopped supporting php 5.2 4 years ago. It does not seam reasonable to still support such an old out dated version of PHP.

I recommend move to minimum supported version of PHP >= 5.3.3 or 5.4

Undefined variable $apiBase

If connection to stripe fails (which it currently does under hhvm all the time), an error will be given that $apiBase is undefined rather than the desired Exception being thrown.

$result = stream_socket_client($url, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $sslContext);

This can be fixed by adding the following at line 325 in ApiRequestor.php

$apiBase = Stripe::$apiBase;

v1.8.0 Stripe_Customer::create not returning customer id

After updating to stripe-php 1.8.0 I started receiving problems with Stripe_Customer::create() not returning a customer id. Reverting back to 1.7.0 fixed the problem.

This was the actual error message:
Stripe_Customer instance has invalid ID

The stripe.com dashboard logs did indeed show that a customer id was being returned, but the actual response on the client side had it missing.

Simple test:

require_once('stripe-php/lib/Stripe.php');
Stripe::setApiKey(SECRET_KEY);

$response = Stripe_Customer::create(array(
    'email' => '[email protected]'
));

echo $response;

Here's an example of the response I was receiving after calling Stripe_Customer::create() - (notice the missing customer id):

{"object":"customer","created":1370198661,"livemode":false,"description":null,"active_card":null,"email":"[email protected]","delinquent":false,"subscription":null,"discount":null,"account_balance":0}

PHPUnit?

Any plans to switch to PHPUnit? Or any aversion to a pull request that replaces simpletest with PHPUnit?

Invalid Headers. Must be a string

I have modified the apiRequestor.php so I can get it to work on GAE but I'm stuck.

It is stating that one of the headers is not a string. Here is the snippet of code where the issue might be

$ua = array('bindings_version' => Stripe::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'stripe',
'uname' => $uname);
$headers = array('X-Stripe-Client-User-Agent: ' . json_encode($ua),
'User-Agent: Stripe/v1 PhpBindings/' . Stripe::VERSION,
'Authorization: Bearer ' . $myApiKey);

This occurs at line 182 - 189 in the ApiRequestor.php

Ship experimental-v2

Any other features you'd like to see in v2? I have some changes to make to the way we persist header use, was thinking of just making them in v2 and shipping it this week.

Thoughts? @chadicus @kyleconroy @alexbilbie @jacksonj04 @bakura10

I think the main thing is ability to instantiate a Stripe instance, which can be done additively.

Adding @property documentation on Stripe classes

As discussed in #65, and following the documentation added by @michelle in #75, it would be nice to add @property annotations on the Stripe classes that use the __get() magic method to emulate properties:

/**
 * @property bool $paid
 * @property bool $captured
 * @property bool $refunded
 * ...
 */
class Stripe_Charge extends ...

This allows the IDE's inspection features to properly understand the properties as if they were actual Stripe_Charge class properties, and avoid warnings.

Testing for customer.deleted generates a PHP notice

If a customer object is deleted, subsequent responses from Stripe will include a customer.deleted property. This property only exists if the customer is deleted--if a customer is NOT deleted, the property will not be "false", but rather unset.

When testing for this property in an if statement for a customer who is NOT deleted, PHP generates a warning:

$customer = Stripe_Customer::retrieve('cus_abc123');  //this customer has NOT been deleted
if($customer->deleted){
    /* do something */
}

Stripe Notice: Undefined property of Stripe_Customer instance: deleted

Which is technically correct, since the property is not set in the JSON response. However this clogs our logs files. Since there's no way to test if the property is unset (for example, calling isset($customer->deleted) generates the same warning), and no obvious way to access the raw JSON response from an object retrieved through the API, there's no obvious workaround for testing for customer.deleted without generating PHP warnings.

Latest merge broke the Invoices (0165a64)

Hello,
after the latest merge,
$invoices = \Stripe_Invoice::all(["count" => 100]);

will return the error

[ErrorException] array_keys() expects parameter 1 to be array, null given
in stripe-php/lib/Stripe/Object.php:138

Only way to have it working, at the moment, is to revert to a previous version.

Plan with ID of "0" returns Stripe_plan object without "id" key

I have a Stripe plan that has ID "0" that was created in the interface. When I request this plan with Stripe_Plan::all(), the plan with that ID is returned without an "id" key in _values. Not sure where to look in the request stack to figure this out, guessing it's being unset somewhere checking for false values? Or perhaps I'm just ignoring something obvious.

Try Catch not catching for Customer Charge

Hey all

Having some issues when attempting to charge customers. Whenever I charge a card, my try catch block works just fine. But when I try to charge a customer, it doesn't catch the error for some reason and I get the following:

Fatal error: Uncaught exception 'Stripe_CardError' with message 'Your card was declined.' in /path/to/plugin/lib/Stripe/ApiRequestor.php:92 Stack trace: 
#0 /path/to/plugin/lib/Stripe/ApiRequestor.php(136): Stripe_ApiRequestor->handleApiError('{? "error": {?...', 402, Array)
#1 /path/to/plugin/lib/Stripe/ApiRequestor.php(74): Stripe_ApiRequestor->_interpretResponse('{? "error": {?...', 402)
#2 /path/to/plugin/lib/Stripe/ApiResource.php(76): Stripe_ApiRequestor->request('post', '/v1/customers', Array)
#3 /path/to/plugin/lib/Stripe/Customer.php(26): Stripe_ApiResource::_scopedCreate('Stripe_Customer', Array, NULL)
#4 in /path/to/plugin/lib/Stripe/ApiRequestor.php on line 92

Here's the code I'm using if that helps:

    public function create_charge( $customer, $amount, $currency = 'usd' ){
    //public function create_charge( $token, $amount, $currency = 'usd' ){
        ini_set('error_reporting', E_ALL);
        try {

            $charge = Stripe_Charge::create(array(
                'customer' => $customer->id,  // Stripe Customer object
                //'card' => $token,
                'amount'   => $amount,
                'currency' => $currency
            )); 

        } catch(Stripe_CardError $e) {
          // Since it's a decline, Stripe_CardError 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");
          $charge = false;
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
            error_log_array($e);
          $charge = false;
        }   

        return $charge;
    } 

I'm not really understanding why an error charging a card would be caught, but not an error charging a customer? Any ideas?

Stripe_AttachedObject addition to Object.php (lines 146-148) outputs nasty PHP warnings in version 1.9.0

After these three lines were added in 1.9.0:

if (self::$_nestedUpdatableAttributes->includes($k))
        $this->_values[$k] = Stripe_Object::scopedConstructFrom('Stripe_AttachedObject', $v, $apiKey);
      else

These warnings are now output on the site when I create a customer, update their subscription, and then retrieve their invoices:

Warning: array_keys() expects parameter 1 to be array, null given in /includes/api/lib/Stripe/Object.php on line 134

Warning: array_diff() [function.array-diff]: Argument #2 is not an array in /includes/api/lib/Stripe/Object.php on line 134

Warning: Invalid argument supplied for foreach() in /includes/api/lib/Stripe/Object.php on line 136

Warning: Invalid argument supplied for foreach() in /includes/api/lib/Stripe/Object.php on line 142

There are no warnings when the three added lines are removed.

May be related to #60

Parse error in PlanTest.php

PHP Parse error: syntax error, unexpected ''gold'' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in lib/stripe-php/test/Stripe/PlanTest.php on line 29
Errors parsing lib/stripe-php/test/Stripe/PlanTest.php

offending line:
$p2 = Stripe_Plan::retrieve($p->'gold');

I have a commit hook for PHP lint and it caught this.

Can't/Won't Use Composer

Some of us can't or won't use Composer. Can you not include instructions for not using Composer in the readme as well?

Raise the minimum PHP version to 5.4 so that we can improve the library

I just started working with this library today and I was quite shocked at how old the code felt until I noticed that the minimum PHP requirement in the composer.json file is PHP 5.2.

In my opinion version 2.x of this library should be a top down rewrite that requires PHP 5.4 as a minimum so that we can make use of some modern practises like namespaces and DI injection. Version 1.x would still be kicking around so those that really are stuck on PHP 5.2 can still use the library.

Would you up for this? I'd rather not see yet another Stripe library appear on Packagist, I'd prefer to use an officially supported SDK and I'd be happy to contribute some time towards helping improve the library.

Token::create returns plain Object

Stripe\Token::create seems to return a vanilla Stripe\Object, not a Token object like the docs specify. Not a big deal, but good for strong typing in my application.

Perhaps I'm missing something, but my test case looks like this:

 public function testCreateCardToken(){
        $card = [
            'number' => '378282246310005',
            'exp_month' => '12',
            'exp_year' => '2017',
            'cvc' => '321',
        ];
        $token = Stripe\Token::create( compact('card') );
        $this->assertInstanceOf('Stripe\\Object', $token ); // ok
        $this->assertInstanceOf('Stripe\\Token', $token ); // nope
    }

The card object must have a value for 'number'.

While using the Stripe API, I am using the javascript checkout system to get a token, after receiving a valid token from the card, I try to charge the card.

I get back the error "The card object must have a value for 'number'. " I looke inside the token there is of course all the required data but there is no number field.

But I have charged other cards in the passed, I am pretty sure there shouldn't be a number field just a valid token.

any help on this would be great, I am not even sure if this is the right place to ask.

Make coupons updateable

The Coupon API already accepts POST requests - documentation coming soon. We need to update our PHP bindings so that coupons are update-able.

Refactor to not use static method calls

In many applications (especially where dependency injection is used), it's preferable to not have libraries that rely on global state.

The Stripe PHP library currently takes the approach that every call is done via a static method. While it's fine to retain this as an option, it would be nice if actual objects could be leveraged.

Stripe_ApiResource::instanceUrl() is missing the required param argument when creating a new Stripe_InvalidRequestError?

I'm receiving this warning when I visit my Stripe webhook listener page:

Warning: Missing argument 2 for Stripe_InvalidRequestError::__construct(), called in ApiResource.php on line 39 and defined in InvalidRequestError.php on line 5

From looking at the code, Stripe_ApiResource::instanceUrl() is missing the required param argument when creating a new Stripe_InvalidRequestError.

Perhaps it should be 'null' like in Stripe_ApiRequestor::handleApiError(...)?

Error on update customer

Stripe::setApiKey($sk);
$cu = Stripe_Customer::retrieve($cust_id);
$cu->email = $email;
$cu->save();

Fatal error: Uncaught exception 'Stripe_InvalidRequestError' with message 'Could not determine which URL to request: Stripe_Customer instance has invalid ID

I believe I downloaded the latest library. When I update the customer email/description I get an error but when I update the plan it works

Stripe::setApiKey($sk);
$cu = Stripe_Customer::retrieve($cust_id);
$cu->plan= $plan;
$cu->save();

Should $customer->deleteDiscount() really throw an exception if the customer doest not have a coupon

Seems like just returning should be expected behavior. Throwing an exception seems overkill. Most of the time, you are not going to know if the customer has a coupon attached without an extra query. Our use-case requires catching the exception, and then doing nothing.

    ////
    // Delete the customer coupon if it exists
    ////
    try {
        $customer->deleteDiscount();
    } catch(Exception $ex) {
        ////
        // Do nothing, this is thrown if the customer does not have a coupon
        ////
    }

Stripe on FuelPHP

I have created a package on FuelPHP for stripe and encountered the following error while using the simplistic example provided in the README (I was using my own key).

Runtime Notice!

ErrorException [ Runtime Notice ]: Declaration of Stripe_SingletonApiResource::_scopedRetrieve() should be compatible with that of Stripe_ApiResource::_scopedRetrieve()

PKGPATH/stripe/vendor/Stripe/SingletonApiResource.php @ line 24:
23: }
24: }

Notice: Undefined offset: 25 in /fuel/packages/stripe/vendor/Stripe/SingletonApiResource.php on line 24
25: 

Add values() to Stripe_Object

Why? Because json_encode((Stripe_Object)$ob) yields an empty object. Ideally it would serialize gracefully, but I understand why it doesn't so some way to dump the values would be ideal.

public function values()
{
   return $this->_values;
}

Create Mock Objects for PHPUnit testing Custom Integrations

I'm working on a site that requires a Stripe integration. It would be great if I could mock the Stripe API's when running the site's unit tests, as it's a lot, lot slower to connect to Stripe's servers when running the tests.

It would also be great because the mock api could return a specific set of predetermined values for given api calls, which would help test any custom integration with the Stripe API.

Is that a possibility?

Fatal error when PHP does not have mbstring extension

in lib/Stripe/ApiRequestor.php,

if (is_string($value) && mb_detect_encoding($value, "UTF-8", TRUE) != "UTF-8")

throws a fatal error when PHP does not have mbstring extension. mb_detect_encoding was added in v1.7.14 #34

According to @ebroder :

Should probably either add a check for the mbstring extension at the top of lib/Stripe.php like we do for curl and json, or work around the function not being there

__toArray

where is the documentation around the coercion methods like __toArray and __toJson ? Its unusable to return the stripe object in templates even though it tried to act like an array, with various template languages it fails.

Stripe_AuthenticationError thrown when updating customer

A Stripe_AuthenticationError (No API key provided) is thrown when updating the customer using the code below:

$customer = Stripe_Customer::retrieve($id, $apiKey);
$customer->card = $card;
$customer->save();

Have to resort to writing the code below for the update to work.

Stripe::setApiKey($apiKey);
$customer = Stripe_Customer::retrieve($id);
$customer->card = $card;
$customer->save();

However, as per Stripe Connect documentation (https://stripe.com/docs/connect/oauth), it is not recommended to set the global API key state with access tokens.

What's changed?

I've been using some code just fine and today, we've gone to take a payment and now we're getting this error:

You must supply either a source or a customer id

This is what my request is:

$charge = Stripe_Charge::create([
    "amount"      => round($chargeCost * 100, 2),
    "currency"    => "gbp",
    "card"        => $token,
    "description" => 'Bootcamp: ' . $date->name . ', for ' . $customer->name,
]);

As far as I can tell, nothing has actually changed here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.