PHP code example of square / connect

1. Go to this page and download the library: Download square/connect library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

square / connect example snippets




use SquareConnect\Configuration;
use SquareConnect\ApiClient;

$access_token = 'YOUR_ACCESS_TOKEN';
# setup authorization
$api_config = new Configuration();
$api_config->setHost("https://connect.squareup.com");
$api_config->setAccessToken($access_token);
$api_client = new ApiClient($api_config);




use Square\SquareClient;
use Square\Environment;

// Initialize the Square client.
$api_client = new SquareClient([
  'accessToken' => "YOUR_ACCESS_TOKEN",
  'environment' => Environment::SANDBOX
]); // In production, the environment arg is 'production'

# Fail if the card form didn't send a value for `nonce` to the server
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
  echo "Invalid card data";
  http_response_code(422);
  return;
}

use SquareConnect\Api\PaymentsApi;
use SquareConnect\ApiException;

$payments_api = new PaymentsApi($api_client);
$request_body = array (
  "source_id" => $nonce,
  "amount_money" => array (
    "amount" => 100,
    "currency" => "USD"
  ),
  "idempotency_key" => uniqid()
);
try {
  $result = $payments_api->createPayment($request_body);
  echo "<pre>";
  print_r($result);
  echo "</pre>";
} catch (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>";
}



use Square\Environment;
use Square\Exceptions\ApiException;
use Square\SquareClient;
use Square\Models\CreatePaymentRequest;
use Square\Models\Money;

$payments_api = $api_client->getPaymentsApi();

$money = new Money();
$money->setAmount(100);
$money->setCurrency('USD');
$create_payment_request = new CreatePaymentRequest($nonce, uniqid(), $money);
try {
  $response = $payments_api->createPayment($create_payment_request);
  if ($response->isError()) {
    echo 'Api response has Errors';
    $errors = $response->getErrors();
    exit();
  }
  echo '<pre>';
  print_r($response);
  echo '</pre>';
} catch (ApiException $e) {
  echo 'Caught exception!<br/>';
  exit();
}