x

Connect v2 - PHP API Add detailed customer info to transaction

I've been trying to make the PHP Transaction API accept customer data, such as name, address, phone, email, etc.  For the life of me I can't seem to get any of this information to pass through?  I know there's a customer API as well, but I'm just trying to run simple, one time transactions, for exactly one product, so I'd like to handle this in one simple transaction.  Is there a way to have the Transaction API accept additional customer information, or do I need to use the Customer API in conjunction?  Below is my form and processing script.  Any assistance would be greatly appreciated. 

 

<?php include ('sq-config.php'); ?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Payment Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="text/javascript" src="https://js.squareup.com/v2/paymentform"></script>
        
    <script>


    var applicationId = '<?php echo $sq_application_id; ?>';
    //var applicationId = 'sandbox-sq0idp-zFBXwgnwha2PNC8iVm6Oig'; // <-- Add your application's ID here

    // You can delete this 'if' statement. It's here to notify you that you need
    // to provide your application ID.
    if (applicationId == '') {
      alert('You need to provide a value for the applicationId variable.');
    }

    // Initializes the payment form. See the documentation for descriptions of
    // each of these parameters.
    var paymentForm = new SqPaymentForm({
      applicationId: applicationId,
      inputClass: 'sq-input',
      inputStyles: [
        {
          fontSize: '15px'
        }
      ],
      cardNumber: {
        elementId: 'sq-card-number',
        placeholder: '•••• •••• •••• ••••'
      },
      cvv: {
        elementId: 'sq-cvv',
        placeholder: 'CVV'
      },
      expirationDate: {
        elementId: 'sq-expiration-date',
        placeholder: 'MM/YY'
      },
      postalCode: {
        elementId: 'sq-postal-code'
      },
      callbacks: {

        // Called when the SqPaymentForm completes a request to generate a card
        // nonce, even if the request failed because of an error.
        cardNonceResponseReceived: function(errors, nonce, cardData) {
          if (errors) {
            console.log("Encountered errors:");

            // This logs all errors encountered during nonce generation to the
            // Javascript console.
            errors.forEach(function(error) {
              console.log('  ' + error.message);
            });

          // No errors occurred. Extract the card nonce.
          } else {

            */
            document.getElementById('card-nonce').value = nonce;
            document.getElementById('nonce-form').submit();

          }
        },

        unsupportedBrowserDetected: function() {
          // Fill in this callback to alert buyers when their browser is not supported.
		  'Your browser is not supported on this payment system.'
        },

        inputEventReceived: function(inputEvent) {
          switch (inputEvent.eventType) {
            case 'focusClassAdded':
              // Handle as desired
              break;
            case 'focusClassRemoved':
              // Handle as desired
              break;
            case 'errorClassAdded':
              // Handle as desired
              break;
            case 'errorClassRemoved':
              // Handle as desired
              break;
            case 'cardBrandChanged':
              // Handle as desired
              break;
            case 'postalCodeChanged':
              // Handle as desired
              break;
          }
        },

        paymentFormLoaded: function() {

          paymentForm.setPostalCode('94901');
        }
      }
    });

    function requestCardNonce(event) {

      event.preventDefault();

      paymentForm.requestCardNonce();
    }
    </script>

    <!--
      These styles can live in a separate .css file. They're just here to keep this
      example to a single file.
    -->
    <style type="text/css">
      .sq-input {
        border: 1px solid rgb(223, 223, 223);
        outline-offset: -5px;
        margin-bottom: 5px;
		width:400px;
		display:block;
		margin-bottom:15px;
      }
      .sq-input--focus {
        /* Indicates how form inputs should appear when they have focus */
        outline: 5px auto rgb(59, 153, 252);
      }
      .sq-input--error {
        /* Indicates how form inputs should appear when they contain invalid values */
        outline: 5px auto rgb(255, 97, 97);
      }
	  
	  #wrapper { width:600px; margin:auto; position:relative; top:30px; }
    </style>
  </head>

  <body>
    
    <div id="wrapper">
    
    <form id="nonce-form" novalidate action="sq-process7.php" method="post">
    <label>Amount:</label><br>
    <input type="text" name="amt" id="amt" value="100" class="sq-input"> 
   
    <label>First Name</label><br>
    <input type="text" name="given_name" id="given_name" class="sq-input"> 
   
    
    <label>Last Name</label><br>
    <input type="text" name="family_name" id="family_name" class="sq-input">
    
    <label>Billing Address Line </label><br>
    <input type="text" name="billing_address" id="billing_address" class="sq-input">
    
    
    <label>Billing City</label><br>
    <input type="text" name="locality" id="locality" class="sq-input">
    
    <label>Billing State</label><br>
    <input type="text" name="state" id="state" class="sq-input">
    
    <label> Billing Email Address</label><br>
    <input type="text" name="email_address" id="email_address" class="sq-input">
    <label> Billing Phone</label><br>
    <input type="text" name="phone" id="phone" class="sq-input">
    
        <label>Card Number</label>
    <div id="sq-card-number"></div>
    <label>CVV</label>
    <div id="sq-cvv"></div>
    <label>Expiration Date</label>
    <div id="sq-expiration-date"></div>
    <label>Postal Code</label>
    <div id="sq-postal-code"></div>
   
    <input type="hidden" id="card-nonce" name="nonce">
  <div class="billing-button-container">
    <input type="submit" onclick="submitButtonClick(event)" id="card-nonce-submit" class="button mid-blue-button billing-button">
   </form>  </div>

 

include ('sq-config.php');
require 'vendor/autoload.php';

$nonce = $_POST['nonce'];

$amt = (is_numeric($_POST['amt']) ? (int)$_POST['amt'] : 0);
$given_name = $_POST['given_name'];
$family_name = $_POST['family_name'];
$billing_address1 = $_POST['billing_address1'];
$billing_address2 = $_POST['billing_address2'];
$locality = $_POST['locality'];
$administrative_district_level_1 = $_POST['state'];
$postal_code = $_POST['sq-postal-code'];
$email_address = $_POST['email_address'];

$full_name = $given_name . " " . $family_name;

$access_token = $sq_access_token;

# Helps ensure this code has been reached via form submission
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  error_log("Received a non-POST request");
  echo "Request not allowed";
  http_response_code(405);
  return;
}
# Fail if the card form didn't send a value for `nonce` to the server

///// Customer //////////

$customer_info = array(
        'given_name' => $given_name,
        'family_name' => $family_name,
        'email_address' => $email_address,
		'phone_number' => $phone_number
    );
	
$customer_body = (object)$customer_info;

$api_instance = new SquareConnect\Api\CustomersApi();
$customer_body = new \SquareConnect\Model\CreateCustomerRequest(); // \SquareConnect\Model\CreateCustomerRequest | An object containing the fields to POST for the request.  See the corresponding object definition for field details.

try {
    $result = $api_instance->createCustomer($customer_info);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling CustomersApi->createCustomer: ', $e->getMessage(), PHP_EOL;
}

///////////

if (is_null($nonce)) {
  echo "Invalid card data";
  http_response_code(422);
  return;
}
\SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);

$customer_body = (object)$customer_info;

$api_instance = new SquareConnect\Api\CustomersApi();
$customer_body = new \SquareConnect\Model\CreateCustomerRequest(); // \SquareConnect\Model\CreateCustomerRequest | An object containing the fields to POST for the request.  See the corresponding object definition for field details.

try {
    $result = $api_instance->createCustomer($customer_info);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling CustomersApi->createCustomer: ', $e->getMessage(), PHP_EOL;
}

///////////


$locations_api = new \SquareConnect\Api\LocationsApi();
try {
  $locations = $locations_api->listLocations();
  #We look for a location that can process payments
  $location = current(array_filter($locations->getLocations(), function($location) {
    return !empty($location->getCapabilities()) &&
      in_array('CREDIT_CARD_PROCESSING', $location->getCapabilities());
  }));
} catch (\SquareConnect\ApiException $e) {
  echo "Caught exception!<br/>";
  print_r("<strong>Response body:</strong><br/>");
  echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
  echo "<br/><strong>Response headers:</strong><br/>";
  echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
  exit(1);
}

$api = new \SquareConnect\Api\TransactionsApi();
$idempotencyKey = uniqid();
$api->charge($location_id, array(
  'idempotency_key' => $idempotencyKey,
  'amount_money' => array(
    'amount' => $amt, 'currency' => 'USD'
  ),
  'card_nonce' => $nonce,
  'note' => $full_name,
  'buyer_email_address' => $email_address,
  
  'shipping_address' => array(
    'address_line_1' => $billing_address1,
    'locality' => $locality,
    'administrative_district_level_1' => $administrative_district_level_1,
    'postal_code' => $postal_code,
    'country' => 'US'
  ),
  
  'billing_address' => array(
    'address_line_1' => $billing_address1,
    'address_line_2' => $billing_address2,
    'administrative_district_level_1' => $administrative_district_level_1,
    'locality' => $locality,
    'postal_code' => $postal_code,
    'country' => 'US'
  ),
  
  'reference_id' => 'optional reference #112358',
  'note' => 'optional note',
  'given_name' => $given_name,
        'family_name' => $family_name,
        'email_address' => $email_address,
		'phone_number' => $phone_number
));
2,235 Views
Message 1 of 2
Report
1 REPLY 1

Never mind, I've decided to go in a different route and not use the API.

 

Thanks!

2,212 Views
Message 2 of 2
Report