Jan Beeck
Jan Beeck

Reputation: 315

How to integrate Stripe payments into Yii2?

I have the following code, it runs without error, however it does not insert funds onto the Stripe server. The Stripe library is installed correctly.

config.php

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

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

\Stripe\Stripe::setApiKey($stripe['secret_key']);

SiteController.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

send.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(); ?>

SendForm.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' => '[email protected]',
          'source'  => $token
      ));

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

   }//end function

}//end class

What could be missing or what is wrong? Thanks.

Upvotes: 5

Views: 5139

Answers (1)

Jan Beeck
Jan Beeck

Reputation: 315

I resolved the issue by removing the Yii2 form scaffolding on the view and adding a beforeAction on the controller.

send.php

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

SiteController.php

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

public function actionCharge()
{
    return $this->render('charge');
}

Upvotes: 3

Related Questions