Edit Stripe product price via input checkbox (PHP)

huangapple go评论61阅读模式
英文:

Edit Stripe product price via input checkbox (PHP)

问题

// 在 payment_init.php 中更新价格
if($jsonObj->request_type == 'create_payment_intent'){

    $itemPriceCents = round($itemPrice*100);

    // 添加复选框的价格
    if(isset($adaospret)) {
        $itemPriceCents += $adaospret;
    }
}
英文:

I'm trying to integrate stripe payment into my website. By now, it's a major success for me. But now I'm struggling to change the PHP variable (with my product price) based if one/or two checkboxes are checked.

Product price it's set on (config.php)

$itemName = "Extras Carte Funciara";
$itemPrice = 39;
$currency = "RON";

These are my checkboxes (index.php)

<input class="form-check-input" type="checkbox" value="10" id="urgentserviciu" name="urgentserviciu">

<input class="form-check-input" type="checkbox" value="2" id="whatssapserviciu" name="whatssapserviciu">

My form is handled by checkout.js

async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);

    let customer_name = document.getElementById("name").value;
    let customer_email = document.getElementById("email").value;

   const { id, customer_id } = await fetch("payment_init.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ request_type:'create_customer', payment_intent_id: payment_intent_id, name: customer_name, email: customer_email }),
    }).then((r) => r.json());

    const { error } = await stripe.confirmPayment({
        elements,
        confirmParams: {
            // Make sure to change this to your payment completion page
            return_url: window.location.href+'?customer_id='+customer_id,
        },
    });

And my payment_init.php

if($jsonObj->request_type == 'create_payment_intent'){

    $itemPriceCents = round($itemPrice*100);


So to the product price I want to add for the first checkbox +10 to final price and for the second one +2 to final price. How can I do that (without breaking any of the code).
Any ideas?
Thank you!

(P.S.: I tried to check via script if checked on submit


    if($('input[name="urgentserviciu"]').is(':checked') && $('input[name="whatssapserviciu"]').is(':checked')) {

        let adaospret = 12;

    } else if ($('input[name="urgentserviciu"]').is(':checked')) {

        let adaospret = 10;

    } else if ($('input[name="whatssapserviciu"]').is(':checked')) {

        let adaospret = 2;

    } else {

        let adaospret = 0;
    }

And then on the payment_init.php to update the price, but I failed.

答案1

得分: 0

Variables declared with let are block-scoped, so your adaospret variables are out of scope in the rest of the code. You need to declare the variable outside the if/else blocks, and assign it inside.

But instead of all those if blocks, simply loop over all the checked boxes, totaling their values.

async function handleSubmit(e) {
  e.preventDefault();
  setLoading(true);

  let customer_name = document.getElementById("name").value;
  let customer_email = document.getElementById("email").value;
  let adaospret = 0;
  $(":checkbox.form-check-input:checked").each(function() {
    adaospret += parseInt(this.value);
  });
  const { id, customer_id } = await fetch("payment_init.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      request_type: 'create_customer',
      payment_intent_id: payment_intent_id,
      name: customer_name,
      email: customer_email,
      adaospret: adaospret
    }),
  }).then((r) => r.json());

  const { error } = await stripe.confirmPayment({
    elements,
    confirmParams: {
      // Make sure to change this to your payment completion page
      return_url: window.location.href + '?customer_id=' + customer_id,
    },
  });
}

Then add this to the JSON in your AJAX call:

body: JSON.stringify({ request_type: 'create_customer', payment_intent_id: payment_intent_id, name: customer_name, email: customer_email, adaospret })

Then in payment_intent.php, you can use $jsonObj->adaospret to get this value.

Note that it's not a good idea to allow the client to specify the price because the user can easily change this using Developer Tools. The client should send the selected options, and you should calculate the price on the server.

英文:

Variables declared with let are block-scoped, so your adaospret variables are out of scope in the rest of the code. You need to declare the variable outside the if/else blocks, and assign it inside.

But instead of all those if blocks, simply loop over all the checked boxes, totaling their values.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

async function handleSubmit(e) {
  e.preventDefault();
  setLoading(true);

  let customer_name = document.getElementById(&quot;name&quot;).value;
  let customer_email = document.getElementById(&quot;email&quot;).value;
  let adaospret = 0;
  $(&quot;:checkbox.form-check-input:checked&quot;).each(function() {
    adaospret += parseInt(this.value);
  });
  const {
    id,
    customer_id
  } = await fetch(&quot;payment_init.php&quot;, {
    method: &quot;POST&quot;,
    headers: {
      &quot;Content-Type&quot;: &quot;application/json&quot;
    },
    body: JSON.stringify({
      request_type: &#39;create_customer&#39;,
      payment_intent_id: payment_intent_id,
      name: customer_name,
      email: customer_email,
      adaospret: adaospret
    }),
  }).then((r) =&gt; r.json());

  const {
    error
  } = await stripe.confirmPayment({
    elements,
    confirmParams: {
      // Make sure to change this to your payment completion page
      return_url: window.location.href + &#39;?customer_id=&#39; + customer_id,
    },
  });

<!-- end snippet -->

Then add this to the JSON in your AJAX call:

body: JSON.stringify({ request_type:&#39;create_customer&#39;, payment_intent_id: payment_intent_id, name: customer_name, email: customer_email, adaospret })

Then in payment_intent.php you can use $jsonObj-&gt;adaospret to get this value.

Note that it's not a good idea to allow the client to specify the price, because the user can easily change this using Developer Tools. The client should send the selected options, and you should calculate the price on the server.

huangapple
  • 本文由 发表于 2023年4月6日 23:46:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定