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 :/
// 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 keyconststripe = Stripe(STRIPE_PUBLISHABLE_KEY); // Define card elements let elements; // Select payment form elementconstpaymentFrm = document.querySelector("#paymentFrm"); // Get payment_intent_client_secret param from URLconstclientSecretParam = newURLSearchParams(window.location.search).get( "payment_intent_client_secret" ); // Check whether the payment_intent_client_secret is already exist in the URLsetProcessing(true); if(!clientSecretParam){ setProcessing(false); // Create an instance of the Elements UI library and attach the client secretinitialize(); } // Check the PaymentIntent creation statuscheckStatus(); // 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 functioninitialize() { 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()); constappearance = { theme: 'stripe', rules: { '.Label': { fontWeight: 'bold', textTransform: 'uppercase', } } }; elements = stripe.elements({ clientSecret, appearance }); constpaymentElement = elements.create("payment"); paymentElement.mount("#paymentElement"); payment_intent_id = id; } // Card form submit handler async functionhandleSubmit(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 functioncheckStatus() { constclientSecret = newURLSearchParams(window.location.search).get( "payment_intent_client_secret" ); constcustomerID = newURLSearchParams(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 pagefetch("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 messagefunctionshowMessage(messageText) { constmessageContainer = document.querySelector("#paymentResponse"); messageContainer.classList.remove("hidden"); messageContainer.textContent = messageText; setTimeout(function () { messageContainer.classList.add("hidden"); messageText.textContent = ""; }, 5000); } // Show a spinner on payment submissionfunctionsetLoading(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 processingfunctionsetProcessing(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 buttonfunctionsetReinit() { 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 ]; echojson_encode($output); } catch (Error$e) { http_response_code(500); echojson_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 basetry { $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 ]; echojson_encode($output); }else{ http_response_code(500); echojson_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) ]; echojson_encode($output); }else{ http_response_code(500); echojson_encode(['error' => 'Transaction has been failed!']); } } ?>
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.