Search code examples
phpyii2stripe-payments

Yii2: How to simply include and use in controllers the Stripe php lib?


So far I've used composer which puts the lib underneath the vendor folder. It goes like this : vendor\stripe\stripe-php\lib

From there I'm bit lost on how I should declare the namespace (i guess in config/web.php underneath components). The namespace declared in the Stripe.php class file is Stripe.

In the controllers I would like to use it like shown in the examples on the Stripe site.

```

// Create the charge on Stripe's servers - this will charge the user's card
    try {
        $charge = \StripeLib\Charge::create(array(
          "amount" => 1000, // amount in cents, again
          "currency" => "eur",
          "source" => $token,
          "description" => "payinguser@example.com")
        );
    } catch(\StripeLib\Error\Card $e) {
      // The card has been declined
        echo "The card has been declined. Please, try again.";
    }

```


Solution

  • I struggled with this. I added the Stripe library to my composer file

    "stripe/stripe-php" : "2.*"
    

    that created /vendor/stripe/stripe-php

    The stripe library uses just Stripe as the namespace. So then in my controller I put

    use Stripe\Stripe;  
    use Stripe\Charge;
    

    Then I was able to do things like

    Stripe::setApiKey(Yii::$app->params['sk_test'])
    

    and

    try {
        $charge = Charge::create(array(
          "amount" => round(100*100,0), // amount in cents, again
          "currency" => "usd",
          "card" => $token,
          "description" => 'description',
          ));
         $paid = true;                
    
    } // end try
    

    So far so good ...