Partage
  • Partager sur Facebook
  • Partager sur Twitter

Plusieurs Prix pour STRIPES récupération variable

Variable du prix, je n'y arrive pas

    1 février 2023 à 22:09:18

    Bonsoir a tous :)

    Je suis en train de mettre Stripe pour vendre des abonnements de mon association, cela fonctionne très bien, sauf que j'ai 3 tarifs sur la même page,  Donc j'ai mis 3 boutons "payer" et quand on clic dessus la modal avec stripe s'ouvre avec les champs pour la carte bancaire etc ...  mais j'aimerai passer le prix par ce formulaire et pouvoir le récupérer dans le fichier ci dessous "payment_init.php

    Merci beaucoup pour votre aide, je suis sur que c'est ton con ! mais j'arrive pas a récuperer le prix :/

    <!-- Stylesheet file -->
    <link rel="stylesheet" href="css/style.css">
    
    <!-- Stripe JS library -->
    <script src="https://js.stripe.com/v3/"></script>
    <script src="js/checkout.js" STRIPE_PUBLISHABLE_KEY="<?php echo STRIPE_PUBLISHABLE_KEY; ?>" defer></script>
    
    <div class="panel">
        <div class="panel-heading">
        
            <!-- Product Info -->
            <p> <?php echo $itemName; ?></p>
            <p><b>Price:</b> <?php echo '$'.$itemPrice.' '.$currency; ?></p>
        </div>
        <div class="panel-body">
            <!-- Display status message -->
            <div id="paymentResponse" class="hidden"></div>
            
            <!-- Display a payment form -->
            <form id="paymentFrm" class="hidden">
                <div class="form-group">
                    <label>NAME</label>
                    <input type="text" id="name" class="field" placeholder="Enter name" required="" autofocus="">
                </div>
                <div class="form-group">
                    <label>EMAIL</label>
                    <input type="email" id="email" class="field" placeholder="Enter email" required="">
                </div>
    
     <input type="hidden" class="field"  name="prix" id="prix" value="12" >
                
                <div id="paymentElement">
                    <!--Stripe.js injects the Payment Element-->
                </div>
                
                <!-- Form submit button -->
                <button id="submitBtn" class="btn btn-success">
                    <div class="spinner hidden" id="spinner"></div>
                    <span id="buttonText">Pay Now</span>
                </button>
            </form>
            
            <!-- Display processing notification -->
            <div id="frmProcess" class="hidden">
                <span class="ring"></span> Processing...
            </div>
            
            <!-- Display re-initiate button -->
            <div id="payReinit" class="hidden">
                <button class="btn btn-primary" onClick="window.location.href=window.location.href.split('?')[0]"><i class="rload"></i>Re-initiate Payment</button>
            </div>
        </div>
    </div>
    

    le fichier checkout.JS :

    // Get API Key let STRIPE_PUBLISHABLE_KEY = document.currentScript.getAttribute('STRIPE_PUBLISHABLE_KEY'); // Create an instance of the Stripe object and set your publishable API key const stripe = Stripe(STRIPE_PUBLISHABLE_KEY); // Define card elements let elements; // Select payment form element const paymentFrm = document.querySelector("#paymentFrm"); // Get payment_intent_client_secret param from URL const clientSecretParam = new URLSearchParams(window.location.search).get( "payment_intent_client_secret" ); // Check whether the payment_intent_client_secret is already exist in the URL setProcessing(true); if(!clientSecretParam){ setProcessing(false); // Create an instance of the Elements UI library and attach the client secret initialize(); } // Check the PaymentIntent creation status checkStatus(); // Attach an event handler to payment form paymentFrm.addEventListener("submit", handleSubmit); // Fetch a payment intent and capture the client secret let payment_intent_id; async function initialize() { const { id, clientSecret } = await fetch("payment_init.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ request_type:'create_payment_intent' }), }).then((r) => r.json()); const appearance = { theme: 'stripe', rules: { '.Label': { fontWeight: 'bold', textTransform: 'uppercase', } } }; elements = stripe.elements({ clientSecret, appearance }); const paymentElement = elements.create("payment"); paymentElement.mount("#paymentElement"); payment_intent_id = id; } // Card form submit handler async function handleSubmit(e) { e.preventDefault(); setLoading(true); let customer_name = document.getElementById("name").value; let customer_email = document.getElementById("email").value; let customer_prix = document.getElementById("prix").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, prix: customer_prix }), }).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, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { showMessage(error.message); } else { showMessage("An unexpected error occured."); } setLoading(false); } // Fetch the PaymentIntent status after payment submission async function checkStatus() { const clientSecret = new URLSearchParams(window.location.search).get( "payment_intent_client_secret" ); const customerID = new URLSearchParams(window.location.search).get( "customer_id" ); if (!clientSecret) { return; } const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret); if (paymentIntent) { switch (paymentIntent.status) { case "succeeded": // Post the transaction info to the server-side script and redirect to the payment status page fetch("payment_init.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ request_type:'payment_insert', payment_intent: paymentIntent, customer_id: customerID }), }) .then(response => response.json()) .then(data => { if (data.payment_txn_id) { window.location.href = '?o=shop&pid='+data.payment_txn_id; } else { showMessage(data.error); setReinit(); } }) .catch(console.error); break; case "processing": showMessage("Your payment is processing."); setReinit(); break; case "requires_payment_method": showMessage("Your payment was not successful, please try again."); setReinit(); break; default: showMessage("Something went wrong."); setReinit(); break; } } else { showMessage("Something went wrong."); setReinit(); } } // Display message function showMessage(messageText) { const messageContainer = document.querySelector("#paymentResponse"); messageContainer.classList.remove("hidden"); messageContainer.textContent = messageText; setTimeout(function () { messageContainer.classList.add("hidden"); messageText.textContent = ""; }, 5000); } // Show a spinner on payment submission function setLoading(isLoading) { if (isLoading) { // Disable the button and show a spinner document.querySelector("#submitBtn").disabled = true; document.querySelector("#spinner").classList.remove("hidden"); document.querySelector("#buttonText").classList.add("hidden"); } else { // Enable the button and hide spinner document.querySelector("#submitBtn").disabled = false; document.querySelector("#spinner").classList.add("hidden"); document.querySelector("#buttonText").classList.remove("hidden"); } } // Show a spinner on payment form processing function setProcessing(isProcessing) { if (isProcessing) { paymentFrm.classList.add("hidden"); document.querySelector("#frmProcess").classList.remove("hidden"); } else { paymentFrm.classList.remove("hidden"); document.querySelector("#frmProcess").classList.add("hidden"); } } // Show payment re-initiate button function setReinit() { document.querySelector("#frmProcess").classList.add("hidden"); document.querySelector("#payReinit").classList.remove("hidden"); } 

    Fichier Payment_init.php dans lequel j’aimerai récupérer via JSON ou POST la valeur du champs Hidden du formulaire ou alors avec jquery ?

    <?php // Include the configuration file  require_once 'config.php'; // Include the database connection file  include_once 'dbConnect.php'; $itemPrice = $_POST['prix']; // <<< C'est ici que j'arrive pas a récupérer le prix // Include the Stripe PHP library  //require_once 'stripe-php/init.php';  require_once('vendor/autoload.php'); // Set API key  \Stripe\Stripe::setApiKey(STRIPE_API_KEY); // Retrieve JSON from POST body  $jsonStr = file_get_contents('php://input'); $jsonObj = json_decode($jsonStr); if($jsonObj->request_type == 'create_payment_intent'){ // Define item price and convert to cents  $itemPriceCents = round($itemPrice*100); // Set content type to JSON  header('Content-Type: application/json'); try { // Create PaymentIntent with amount and currency  $paymentIntent = \Stripe\PaymentIntent::create([ 'amount' => $itemPriceCents, 'currency' => $currency, 'description' => $itemName, 'payment_method_types' => [ 'card' ] ]); $output = [ 'id' => $paymentIntent->id, 'clientSecret' => $paymentIntent->client_secret ]; echo json_encode($output); } catch (Error $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); } }elseif($jsonObj->request_type == 'create_customer'){ $payment_intent_id = !empty($jsonObj->payment_intent_id)?$jsonObj->payment_intent_id:''; $name = !empty($jsonObj->name)?$jsonObj->name:''; $email = !empty($jsonObj->email)?$jsonObj->email:''; // Ajout client a la base try { $customer = \Stripe\Customer::create(array( 'name' => $name, 'email' => $email )); }catch(Exception $e) { $api_error = $e->getMessage(); } if(empty($api_error) && $customer){ try { // Mise a jour de l'intention avec l'id du client  $paymentIntent = \Stripe\PaymentIntent::update($payment_intent_id, [ 'customer' => $customer->id ]); } catch (Exception $e) { // pour apres  } $output = [ 'id' => $payment_intent_id, 'customer_id' => $customer->id ]; echo json_encode($output); }else{ http_response_code(500); echo json_encode(['error' => $api_error]); } }elseif($jsonObj->request_type == 'payment_insert'){ $payment_intent = !empty($jsonObj->payment_intent)?$jsonObj->payment_intent:''; $customer_id = !empty($jsonObj->customer_id)?$jsonObj->customer_id:''; // Retrieve customer info  try { $customer = \Stripe\Customer::retrieve($customer_id); }catch(Exception $e) { $api_error = $e->getMessage(); } // Check whether the charge was successful  if(!empty($payment_intent) && $payment_intent->status == 'succeeded'){ // Transaction details  $transaction_id = $payment_intent->id; $paid_amount = $payment_intent->amount; $paid_amount = ($paid_amount/100); $paid_currency = $payment_intent->currency; $payment_status = $payment_intent->status; $customer_name = $customer_email = ''; if(!empty($customer)){ $customer_name = !empty($customer->name)?$customer->name:''; $customer_email = !empty($customer->email)?$customer->email:''; } // Check if any transaction data is exists already with the same TXN ID  $sqlQ = "SELECT id FROM transactions WHERE txn_id = ?"; $stmt = $db->prepare($sqlQ); $stmt->bind_param("s", $transaction_id); $stmt->execute(); $stmt->bind_result($row_id); $stmt->fetch(); $payment_id = 0; if(!empty($row_id)){ $payment_id = $row_id; }else{ // Insert transaction data into the database  $sqlQ = "INSERT INTO transactions (customer_name,customer_email,item_name,item_price,item_price_currency,paid_amount,paid_amount_currency,txn_id,payment_status,created,modified) VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())"; $stmt = $db->prepare($sqlQ); $stmt->bind_param("sssdsdsss", $customer_name, $customer_email, $itemName, $itemPrice, $currency, $paid_amount, $paid_currency, $transaction_id, $payment_status); $insert = $stmt->execute(); if($insert){ $payment_id = $stmt->insert_id; } } $output = [ 'payment_txn_id' => base64_encode($transaction_id) ]; echo json_encode($output); }else{ http_response_code(500); echo json_encode(['error' => 'Transaction has been failed!']); } } ?> 
    • Partager sur Facebook
    • Partager sur Twitter

    Plusieurs Prix pour STRIPES récupération variable

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown