Skip to content

Commit b254b72

Browse files
author
Stephen Barlow
committed
Add a PHP payment-processing example that uses the SquareConnect PHP client library
1 parent 89b6dab commit b254b72

File tree

6 files changed

+251
-5
lines changed

6 files changed

+251
-5
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
11
target/
2+
vendor/
3+
composer.phar
4+
composer.lock

connect-examples/v2/README.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11

2-
The project is structured under two folders:
2+
This folder includes the following samples:
33

4-
* rails_payment: rails server implementation, within here it also includes frontend implementations for:
5-
* plain JS
4+
* __rails_payment__: a rails server implementation. This example includes front-end
5+
implementations for:
6+
* Standard Javascript
67
* JQuery
78
* Angular 1
89
* React
910
* Ember
1011
* JS + Bootstrap
11-
* node_payment: node server implementation, within here there is a frontend implementation:
12-
* plain JS
12+
* __node_payment__: a node server implementation. This example includes a single,
13+
standard Javascript front-end implementation.
14+
* __php_payment__: a simple PHP server implementation with an accompanying payment
15+
form.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Payment processing example: PHP
2+
3+
This sample demonstrates processing card payments with Square Connect API, using the
4+
Square Connect PHP client library.
5+
6+
## Setup
7+
8+
### Install the PHP client library
9+
10+
This sample already includes the `square/connect` dependency in its `composer.json`
11+
file. To install the client library:
12+
13+
1. Make sure you've downloaded Composer, following the instructions
14+
[here](https://getcomposer.org/download/).
15+
16+
2. Run the following command from the directory containing `composer.json`:
17+
18+
php composer.phar install
19+
20+
### Provide required credentials
21+
22+
Both `process-card.php` and `index.html` have values near the top of the file
23+
that you need to replace with various credentials associated with your application.
24+
If you're just testing things out, it's recommended that you use your _sandbox_
25+
credentials for now. See
26+
[this article](https://docs.connect.squareup.com/articles/using-sandbox/)
27+
for more information on the API sandbox.
28+
29+
You can `grep` for `REPLACE_ME` to find all of the fields to replace.
30+
31+
32+
## Running the sample
33+
34+
From the sample's root directory, run:
35+
36+
php -S localhost:8000
37+
38+
You can then visit `localhost:8000` in your browser to see the card form.
39+
40+
If you're using your sandbox credentials, you can test out an valid credit card
41+
transaction by providing the following card information in the form:
42+
43+
* Card Number 4532 7597 3454 5858
44+
* Card CVV 111
45+
* Card Expiration (Any time in the future)
46+
* Card Postal Code (Any valid US postal code)
47+
48+
**Note that if you are _not_ using your sandbox credentials and you enter _real_
49+
credit card information, YOU WILL CHARGE THE CARD.**
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"require": {
3+
"square/connect": "*"
4+
}
5+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
<html>
2+
<head>
3+
<title>My Payment Form</title>
4+
<script type="text/javascript" src="https://js.squareup.com/v2/paymentform"></script>
5+
<script type="text/javascript">
6+
var sqPaymentForm = new SqPaymentForm({
7+
8+
// Replace this value with your application's ID (available from the merchant dashboard).
9+
// If you're just testing things out, replace this with your _Sandbox_ application ID,
10+
// which is also available there.
11+
applicationId: 'REPLACE_ME',
12+
inputClass: 'sq-input',
13+
cardNumber: {
14+
elementId: 'sq-card-number',
15+
placeholder: "0000 0000 0000 0000"
16+
},
17+
cvv: {
18+
elementId: 'sq-cvv',
19+
placeholder: 'CVV'
20+
},
21+
expirationDate: {
22+
elementId: 'sq-expiration-date',
23+
placeholder: 'MM/YY'
24+
},
25+
postalCode: {
26+
elementId: 'sq-postal-code',
27+
placeholder: 'Postal Code'
28+
},
29+
inputStyles: [
30+
31+
// Because this object provides no value for mediaMaxWidth or mediaMinWidth,
32+
// these styles apply for screens of all sizes, unless overridden by another
33+
// input style below.
34+
{
35+
fontSize: '14px',
36+
padding: '3px'
37+
},
38+
39+
// These styles are applied to inputs ONLY when the screen width is 400px
40+
// or smaller. Note that because it doesn't specify a value for padding,
41+
// the padding value in the previous object is preserved.
42+
{
43+
mediaMaxWidth: '400px',
44+
fontSize: '18px',
45+
}
46+
],
47+
callbacks: {
48+
cardNonceResponseReceived: function(errors, nonce, cardData) {
49+
if (errors) {
50+
var errorDiv = document.getElementById('errors');
51+
errorDiv.innerHTML = "";
52+
errors.forEach(function(error) {
53+
var p = document.createElement('p');
54+
p.innerHTML = error.message;
55+
errorDiv.appendChild(p);
56+
});
57+
} else {
58+
// This alert is for debugging purposes only.
59+
alert('Nonce received! ' + nonce + ' ' + JSON.stringify(cardData));
60+
61+
// Assign the value of the nonce to a hidden form element
62+
var nonceField = document.getElementById('card-nonce');
63+
nonceField.value = nonce;
64+
65+
// Submit the form
66+
document.getElementById('form').submit();
67+
}
68+
},
69+
unsupportedBrowserDetected: function() {
70+
// Alert the buyer that their browser is not supported
71+
}
72+
}
73+
});
74+
function submitButtonClick() {
75+
event.preventDefault();
76+
sqPaymentForm.requestCardNonce();
77+
}
78+
</script>
79+
<style type="text/css">
80+
.sq-input {
81+
border: 1px solid #CCCCCC;
82+
margin-bottom: 10px;
83+
padding: 1px;
84+
}
85+
.sq-input--focus {
86+
outline-width: 5px;
87+
outline-color: #70ACE9;
88+
outline-offset: -1px;
89+
outline-style: auto;
90+
}
91+
.sq-input--error {
92+
outline-width: 5px;
93+
outline-color: #FF9393;
94+
outline-offset: 0px;
95+
outline-style: auto;
96+
}
97+
</style>
98+
</head>
99+
<body>
100+
101+
<h1>My Payment Form</h1>
102+
103+
<form id="form" novalidate action="/process-card.php" method="post">
104+
<label>Credit Card</label>
105+
<div id="sq-card-number"></div>
106+
<label>CVV</label>
107+
<div id="sq-cvv"></div>
108+
<label>Expiration Date</label>
109+
<div id="sq-expiration-date"></div>
110+
<label>Postal Code</label>
111+
<div id="sq-postal-code"></div>
112+
<input type="hidden" id="card-nonce" name="nonce">
113+
<input type="submit" onclick="submitButtonClick()" id="card-nonce">
114+
</form>
115+
116+
<div id="errors"></div>
117+
</body>
118+
</html>
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
3+
require 'vendor/autoload.php';
4+
5+
# Replace these values. You probably want to start with your Sandbox credentials
6+
# to start: https://docs.connect.squareup.com/articles/using-sandbox/
7+
8+
# The ID of the business location to associate processed payments with.
9+
# If you're testing things out, use a sandbox location ID.
10+
#
11+
# See [Retrieve your business's locations](https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile)
12+
# for an easy way to get your business's location IDs.
13+
$location_id = 'REPLACE_ME';
14+
15+
# The access token to use in all Connect API requests. Use your *sandbox* access
16+
# token if you're just testing things out.
17+
$access_token = 'REPLACE_ME';
18+
19+
# Helps ensure this code has been reached via form submission
20+
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
21+
error_log("Received a non-POST request");
22+
echo "Request not allowed";
23+
http_response_code(405);
24+
return;
25+
}
26+
27+
# Fail if the card form didn't send a value for `nonce` to the server
28+
$nonce = $_POST['nonce'];
29+
if (is_null($nonce)) {
30+
echo "Invalid card data";
31+
http_response_code(422);
32+
return;
33+
}
34+
35+
$transaction_api = new \SquareConnect\Api\TransactionApi();
36+
37+
$request_body = array (
38+
39+
"card_nonce" => $nonce,
40+
41+
# Monetary amounts are specified in the smallest unit of the applicable currency.
42+
# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
43+
"amount_money" => array (
44+
"amount" => 100,
45+
"currency" => "USD"
46+
),
47+
48+
# Every payment you process with the SDK must have a unique idempotency key.
49+
# If you're unsure whether a particular payment succeeded, you can reattempt
50+
# it with the same idempotency key without worrying about double charging
51+
# the buyer.
52+
"idempotency_key" => uniqid()
53+
);
54+
55+
# The SDK throws an exception if a Connect endpoint responds with anything besides
56+
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
57+
try {
58+
$result = $transaction_api->charge($access_token, $location_id, $request_body);
59+
echo "<pre>";
60+
print_r($result);
61+
echo "</pre>";
62+
} catch (\SquareConnect\ApiException $e) {
63+
echo "Caught exception!<br/>";
64+
print_r("<strong>Response body:</strong><br/>");
65+
echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
66+
echo "<br/><strong>Response headers:</strong><br/>";
67+
echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
68+
}

0 commit comments

Comments
 (0)