如何将Stripe支付集成到Yii2中?

Jan*_*eck 5 php stripe-payments yii2

我有以下代码,它运行时没有错误,但它不会将资金插入到 Stripe 服务器上。Stripe 库已正确安装。

配置文件

    <?php
    //require_once('vendor/autoload.php');

    $stripe = array(
      "secret_key"      => "sk_test_key",
      "publishable_key" => "pk_test_key"
    );

\Stripe\Stripe::setApiKey($stripe['secret_key']);
Run Code Online (Sandbox Code Playgroud)

站点控制器.php

public function actionSend()
    {
        $model = new SendForm();

            if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->insertCharge(); 
                //Yii::$app->session->setFlash('Successfully charged $20.00!');
                return $this->render('send-confirm', ['model' => $model]);
            } else {
                return $this->render('send', [
                    'model' => $model,
                ]);
            }

    }// end function
Run Code Online (Sandbox Code Playgroud)

发送.php

    <?php $form = ActiveForm::begin(['options' => ['method' => 'post']]); ?>

  <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="<?php echo $stripe['publishable_key']; ?>"
    data-name="TEST"
    data-description="Testing"
    data-amount="2000"
    data-locale="auto">

   </script>
   <?php ActiveForm::end(); ?>
Run Code Online (Sandbox Code Playgroud)

发送表单.php

class SendForm extends Model
{   

   public function insertCharge()
   {

     \Stripe\Stripe::setApiKey(Yii::$app->stripe->secret_key);

      $request = Yii::$app->request;

      $token = $request->post('stripeToken');

      //$token  = $_POST['stripeToken'];

      $customer = \Stripe\Customer::create(array(
          'email' => 'customer@example.com',
          'source'  => $token
      ));

      $charge = \Stripe\Charge::create(array(
          'customer' => $customer->id,
          'amount'   => 2000,
          'currency' => 'usd'
      ));

   }//end function

}//end class
Run Code Online (Sandbox Code Playgroud)

可能缺少什么或出了什么问题?谢谢。

Jan*_*eck 3

我通过删除视图上的 Yii2 表单脚手架并在控制器上添加 beforeAction 解决了这个问题。

发送.php

<form action="index.php?r=site%2Fcharge" method="post">

站点控制器.php

public function beforeAction($action)
{
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

public function actionCharge()
{
    return $this->render('charge');
}
Run Code Online (Sandbox Code Playgroud)