PHP Payment API Question

Assuming a successful sandbox test of the following form, lifted from github.com/square/connect-api-examples/tree/master/connect-examples/v2/php_payment

<?php
///inputs values are variables
$amount = 10;
$address = '200 Main St.';
?>
<form class="payment-form" id="fast-checkout">
  <input type="hidden" name="amount" id="amount" value="<?php echo $amount; ?>">
  <input type="hidden" name="address" id="address" value="<?php echo $address; ?>">
    <div class="wrapper"> 
      <div id="card-container"></div>
      <button id="card-button" type="button">Pay with Card</button>
      <span id="payment-flow-message"></span>
    </div>
  </form>

What is the procedure for passing the values of the input ids, address and amount to process-payment.php?

I would assume they would be passed through the sq-card-pay.js, but don’t see any clear way forward. Need these values to make it to the process-payment page, as such:

$address = $_POST['address'];
$amount = intval($_POST['amount'])

Or, need to retrieve those values as expected by the API

Yo tengo un problema similar, logre implementar todo luego de 3 dias.

estoy usando PHP y javascript.

necesito enviar hacia php unas variables con informacion del cliente como su nombre, recibirlo en el .php y ahi jugar con los datos y enviarlos a una DB .

como logro pasar datos desde mi VISTA hacia mi PHP file que tiene toda la lógica por dentras ?

intente enviando un formulario con los datos para consumirlo en mi php pero arroja error porque aparentemente estoy enviando dos veces hacia php la informacion y recibo error.

ya que cuando uno presiona pagar ahi se envian datos hacia el php pero con un document.getElementById(‘datos-consumo-form’).submit();

adicional pues se envia dos veces hacia php y recibo errores. alguien que me ilumine !

@ juankstylez
Wish I could read Spanish!

use google translate My friend !

In the PHP Payment Example, the process-payment.php file has the following:

$money = new Money();
// Monetary amounts are specified in the smallest unit of the applicable currency.
// This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
$money->setAmount(100);

The isn’t very usefull comment is certainly true!
And as far as I can tell, there’s no documentation for passing a variable.
One would expect, perhaps:

<input type="hidden" id="amount_money" value="<?php echo $total; ?>">

And a method to send that to the process-payment file as a post

money = document.getElementById('amount_money').value;

BUT - nothing about this is EVER explained.
Additionally my V1 version of this (which I’ve used for years) is not functioning anymore.
SO, yeah I need an answer on how to send the additional values, such as

<input type="hidden" id="whatever" value="<?php echo $whatever; ?>">

Really need some help. This place seems to be as empty as a school bus on Sunday…

All our examples have the amount hard coded. This is by design and they allow you to use the method that best suits your business need to calculate and pass in the amount you want to charge the customer. Most often the amount is passed in as an integer variable. :slightly_smiling_face:

Bryan!

I was hoping for an answer to my question.

Using what has been provided: the sq-card-pay.js and the sq-payment-flow.js, where within either of these scripts can I pass the POST values I need to process-payment.php and how?

Consider that these two input fields are within the form:

<input type="hidden" id="amount" value="40">
<input type="hidden" id="customer" value="Bryan Square">

Where within the provided JS files can I send post values using valueNeeded = document.getElementByID(‘value_needed’).value (for eaxmple).

I just need additional values sent as posts to the process-payment.php file…too much to ask?

You’ll want to add the data to:

window.createPayment = async function(token) {
  const dataJsonString = JSON.stringify({
    token
  });

Which POST the token to the payment request. You can include the amount and any additional information the payment request takes. :slightly_smiling_face:

1 Like

For anyone who comes along looking for the answer to my original question, Bryan is trying to be helpful, but his answer is somewhat cryptic (he’s a fine fellow).

Assuming you have input values you need to pass along to the process-payment.php file, such as:

<input type="hidden" id="amount" value="40">
<input type="hidden" id="customer" value="Bryan Square">
<input type="hidden" id="whatever" value="something else">

Crack open the provided sq-payment-flow.js file, and add to the TOP of the file the additional values you need

amount = document.getElementById('amount').value;
customer = document.getElementById('customer').value;
whatever = document.getElementById('whatever').value;

Now, add what you need to pass along in the sq-payment-flow.js file.
For example:

window.createPayment = async function(token) {
  const dataJsonString = JSON.stringify({
    token,
    amount,
    customer,
   whatever
  });

At this point, crack open the provided process-payment.php file, and roll below $data = json_decode($json);
The data you want to collect will not arrive in $_POST values - instead it is part of the $data result.
So for example, your values can be collected as follows:

$amount = $data->amount;
$customer = $data->customer;
$whatever = $data->whatever;

I hope this is helpful to anyone who is as confused about this as I was.
The documentation for this really should be in plain site for all to see, but as of right now, it’s not.

Thanks for sharing, I managed to do the same sent from javascript to PHP.

of the following please in case someone needs it.

I am using codeigniter framework.
but for normal php I suppose it is identical.

const appId = 'app id here'; const locationId = 'location id here'; // const variable, declare variable for receive data const idSolicitud = '<?php echo $idSolicitud; ?>'; // collect data from php const ListingId = '<?php echo $ListingId; ?>'; // collect data from php const aplicante = '<?php echo $aplicante; ?>'; // collect data from php async function initializeCard(payments) { const card = await payments.card(); await card.attach('#card-container'); return card; } // We send the data in Json to the controller or php file as you require async function createPayment(token) { const body = JSON.stringify({ locationId, lang, idSolicitud, ListingId, aplicante, sourceId: token, }); //I send the data in a json to the controller, in my case it is to a controller, and its method const paymentResponse = await fetch('https://myurlhere.com/payment/proccess', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body, }); that is part of my code of how to insert additional data to what the javascript sends. IN my php file receive -> //Obtenemos los datos enviados desde el Javascript v_payment_capture.php $json = json_decode($this->input->raw_input_stream); //for codeigniter // $json = json_decode(file_get_contents('php://input')); //for php pure. $cnon = $json->sourceId; //We obtain the Nonce of the card to use it below in the payment request. $languaje = $json->lang; //Get the language ES/EN passed in from the view. $solicitud = $json->idSolicitud; // Get the form request code from the view. $Idlisting = $json->ListingId; // We get the Listing ID from the view passed from the form, it is the ID of the rental or property. $Quienaplica = $json->aplicante; // Name of the applicant to the request, person who is going to pay, data comes from the view, from the form. I hope my code is helpful to understand how to send additional information from javascript to php in the card form.

Hello friend,

I think the best way to do this would be to use PHP’s sessions and a front-end field, either a hidden input or a javascript variable that you post in your AJAX query, that way, you can validate if the user has changed the amount on the front-end and you can prevent them from underpaying you.

your-payment-page.php

<?
$amount = calculateAmount(); //you could put any value or any function that adds up the amount
$_SESSION['square_amount'] = $amount; //store it in a session variable so you can use it in your other file

//option 1: hidden field?>
<input type="hidden" value="<?=$amount?>"

<? //option 2: javascript variable ?>
<script>
var amount = "<?=$amount?>";
//Use "amount" variable in your AJAX request :)

process-payment.php

$amount = $_SESSION['square_amount']; //back-end, expected amount
$frontend_amount = $_POST['amount']; //amount received from front-end

if ($amount != $frontend_amount)
{ 
// user has changed the value of the expected amount
echo "nice try.";
return;
}

Hope this helps.