【问题标题】:Yii2: How to simply include and use in controllers the Stripe php lib?Yii2:如何在控制器中简单地包含和使用 Stripe php 库?
【发布时间】:2015-05-02 06:03:30
【问题描述】:

到目前为止,我使用了将 lib 放在 vendor 文件夹下的 composer。 它是这样的:vendor\stripe\stripe-php\lib

从那里我有点迷失了我应该如何声明命名空间(我猜在组件下面的 config/web.php 中)。 Stripe.php 类文件中声明的命名空间是 Stripe。

我想在控制器中使用它,如 Stripe 网站上的示例所示。

```

// 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.";
    }

```

【问题讨论】:

  • 你用的是什么框架?
  • @david s Yii2 框架

标签: php yii2 stripe-payments


【解决方案1】:

我为此苦苦挣扎。我将 Stripe 库添加到了我的作曲家文件中

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

创建 /vendor/stripe/stripe-php

stripe 库仅使用 Stripe 作为命名空间。所以然后在我的控制器中我放了

use Stripe\Stripe;  
use Stripe\Charge;

然后我可以做类似的事情

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

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

} // end try

到目前为止一切都很好......

【讨论】:

    【解决方案2】:

    好的,事情就是这样。使用composer包含lib后,您可以在vendor/stripe/stripe-php/lib/stripe下找到stripe类。所以,在我的控制器中我这样做了

    use app\stripe\stripe-php\lib\Stripe;
    

    但由于连字符,它不起作用,所以我不得不将文件夹 stripe-php 重命名为 stripephp(我知道这根本不好),因为我猜它不会被 composer 更新。

    最后,我在控制器的开头有这个

    use app\stripe\stripephp\lib\Stripe;
    

    然后在我的操作中我使用类似这样的东西

    \Stripe\Stripe::setApiKey(Yii::$app->stripe->privateKey);
            //we got the token, we must then charge the customer
            // Get the credit card details submitted by the form
            $token = $_POST['stripeToken'];
    
    
            // Create the charge on Stripe's servers - this will charge the user's card
            try {
                $charge = \Stripe\Charge::create(array(
                  "amount" => 1000, // amount in cents, again
                  ...
    

    别忘了把你的私钥/公钥放在你的配置文件中。

    如果您有更好的解决方案(更优雅),不客气。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2011-12-30
      • 2020-02-05
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      相关资源
      最近更新 更多