2016-06-27 2 views
2

Так что я хочу, чтобы выставить счет клиентов (которые не являются пользователями) столько же, сколько то, что отображается в виде полосынашивки биллинг с той же цене, как форма

<form action="/charge" method="POST"> 
       {!! csrf_field() !!} 
        <script 
        src="https://checkout.stripe.com/checkout.js" class="stripe-button" 
        data-key="pk_test_key" 
        data-amount="{{ $note->price*100 }}" 
        data-name="Hello World" 
        data-description="{{$note->title}}" 
        data-image="/img/documentation/checkout/marketplace.png" 
        data-locale="auto" 
        data-currency="aud"> 
        </script> 
       </form> 

В форме отображается цена указана цена в соответствующей модели примечаний * 100. Я бы хотел, чтобы на самом деле клиент выставил эту сумму, она изменится в зависимости от примечания.

Вот мой сервер биллинга

public function charge() 
{ 
    // Set your secret key: remember to change this to your live secret key in production 
    // See your keys here https://dashboard.stripe.com/account/apikeys 
    \Stripe\Stripe::setApiKey("sk_test_key"); 

    // 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" => 100, // amount in cents, again 
     "currency" => "aud", 
     "source" => $token, 
     "description" => "Example charge" 
     )); 
    } catch(\Stripe\Error\Card $e) { 
     // The card has been declined 
    } 

    return 'payment succesful'; 
} 

Мне нужно установить «количество», равное значению ноты.

В противном случае оплата будет проходить на моей тестовой учетной записи кассира, и в основном все остальное должно работать.

Клиенты пока не зарегистрированы.

ответ

2

Сумма должна быть той, что вы рассчитываете на стороне сервера, иначе люди могут просто изменить DOM и передать любую сумму, которую они хотели бы.

Вместо хранения id в кэше на стороне сервера, и передать note в качестве зависимости от функции charge, а затем сравнить 2.

/** 
* Assuming name of "view" page 
*/ 
public function checkout(Note $note) 
{ 
    /** 
    * Always forget this on each page load, so we can switch seamlessly between Notes. 
    */ 
    Illuminate\Support\Facades\Cache::forget('nid')->put('nid', $note->id); 
} 

Не забудьте изменить charge маршрут, чтобы включить новую ссылку на наш Note зависимость

route::post('charge/{note}', '[email protected]')->name('charge'); 

Убедитесь, чтобы обновить форму, чтобы передать note а

<form action="{{route('charge', $note)}}" method="POST"> 

sidenote Мне нравятся названные маршруты, но это не требуется.

Затем, когда вы обрабатываете запрос, сравнить $nid и $note->id

public function charge(Illuminate\Http\Request $request, Note $note) 
{ 
    $nid = Illuminate\Support\Facades\Cache::get('nid'); 

    // id's match, no sneaky stuff. safe to use $note->price now 
    if ($nid === $note->id) { 
     //now we can process our payment. 
     // Set your secret key: remember to change this to your live secret key in production 
     // See your keys here https://dashboard.stripe.com/account/apikeys 
     \Stripe\Stripe::setApiKey("sk_test_key"); 

     // Get the credit card details submitted by the form 
     $token = $request->get('stripeToken'); 

     // Create the charge on Stripe's servers - this will charge the user's card 
     try { 
      $charge = \Stripe\Charge::create(array(
       "amount" => number_format($note->price, 0, '', ''), // amount in cents, again 
       "currency" => "aud", 
       "source" => $token, 
       "description" => "Example charge" 
      )); 
     } catch(\Stripe\Error\Card $e) { 
      // The card has been declined 
     }  
    } 
} 
+0

бы положить его в сессии и работать? – DanielPahor

+0

@ DanielPahor Вы можете, но я не использую 'session' и использую redis для своего кеша. Мне больше нравится контроль и безопасность. Однако сделайте мое мнение с солью. – Ohgodwhy

 Смежные вопросы

  • Нет связанных вопросов^_^