Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add PHP versions of existing code samples
- Loading branch information
Stephen Barlow
committed
Aug 6, 2015
1 parent
bfcd02e
commit 45fd6cc
Showing
11 changed files
with
474 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# Connect OAuth Flow Example (PHP) | ||
|
||
This example demonstrates a bare-bones PHP implementation of the Square Connect OAuth flow. The application links merchants to the OAuth Permissions form and handles the result of the authorization, which is sent to the application's Redirect URL. | ||
|
||
For more information, see [OAuth Overview](https://docs.connect.squareup.com/api/connect/v1/#oauth-overview), along with the comments included in `callback.php`. | ||
|
||
## Setup | ||
|
||
### Download Unirest | ||
|
||
This application requires the Unirest HTTP library for PHP. You can download it at | ||
[unirest.io/php.html](http://unirest.io/php.html). | ||
|
||
### Specify your application credentials | ||
|
||
In order for the sample to work, you must specify three fields in `callback.php`, and one field | ||
in `index.php`: | ||
|
||
* In `callback.php`, replace `path/to/Unirest.php` with the path to the Unirest PHP library. | ||
|
||
* In both files, replace the value of `$application_id` with your application's ID, available on your | ||
[application dashboard](https://connect.squareup.com/apps). | ||
|
||
* In `callback.php`, replace the value of `$applicationSecret` with your application's secret, also available on your application dashboard. | ||
|
||
### Set your application's Redirect URL | ||
|
||
On your application dashboard, set your application's Redirect URL to `http://localhost:8000/callback.php`. | ||
|
||
Note that applications that don't use a `localhost` URL must use HTTPS. HTTP is allowed for `localhost` URLs to simplify the development process. | ||
|
||
## Running the example | ||
|
||
To run the example, execute the following from the directory that containss these files: | ||
|
||
php -S localhost:8000 | ||
|
||
You can then proceed through the OAuth flow by going to `http://localhost:8000` in your web browser. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
<?php | ||
|
||
# This sample demonstrates a bare-bones implementation of the Square Connect OAuth flow: | ||
# | ||
# 1. A merchant clicks the authorization link served by the root path (http://localhost:8000/) | ||
# 2. The merchant signs in to Square and submits the Permissions form. Note that if the merchant | ||
# is already signed in to Square, and if the merchant has already authorized your application, | ||
# the OAuth flow automatically proceeds to the next step without presenting the Permissions form. | ||
# 3. Square sends a request to your application's Redirect URL | ||
# (which should be set to http://localhost:8080/callback.php on your application dashboard) | ||
# 4. The server extracts the authorization code provided in Square's request and passes it | ||
# along to the Obtain Token endpoint. | ||
# 5. The Obtain Token endpoint returns an access token your application can use in subsequent requests | ||
# to the Connect API. | ||
# | ||
# This sample requires the Unirest PHP library. Download it here: | ||
# http://unirest.io/php.html | ||
|
||
# Replace this value with the path to the Unirest PHP library | ||
require_once 'path/to/Unirest.php'; | ||
|
||
# Your application's ID and secret, available from your application dashboard | ||
$applicationId = 'REPLACE_ME'; | ||
$applicationSecret = 'REPLACE_ME'; | ||
|
||
$connectHost = 'https://connect.squareup.com'; | ||
|
||
# Headers to provide to OAuth API endpoints | ||
$oauthRequestHeaders = array ( | ||
'Authorization' => 'Client ' . $applicationSecret, | ||
'Accept' => 'application/json', | ||
'Content-Type' => 'application/json' | ||
); | ||
|
||
# Serves requests from Square to your application's redirect URL | ||
# Note that you need to set your application's Redirect URL to | ||
# http://localhost:8000/callback.php from your application dashboard | ||
function callback() { | ||
global $connectHost, $oauthRequestHeaders; | ||
|
||
# Extract the returned authorization code from the URL | ||
$authorizationCode = $_GET['code']; | ||
if ($authorizationCode) { | ||
|
||
# Provide the code in a request to the Obtain Token endpoint | ||
$oauthRequestBody = array( | ||
'client_id' => $applicationId, | ||
'client_secret' => $applicationSecret, | ||
'code' => $authorizationCode | ||
); | ||
$response = Unirest\Request::post($connectHost . '/oauth2/token', $oauthRequestBody, $requestHeaders); | ||
|
||
# Extract the returned access token from the response body | ||
if (property_exists($response, 'access_token')) { | ||
|
||
# Here, instead of printing the access token, your application server should store it securely | ||
# and use it in subsequent requests to the Connect API on behalf of the merchant. | ||
error_log('Access token: ' . $response->access_token); | ||
error_log('Authorization succeeded!'); | ||
|
||
# The response from the Obtain Token endpoint did not include an access token. Something went wrong. | ||
} else { | ||
error_log('Code exchange failed!'); | ||
} | ||
|
||
# The request to the Redirect URL did not include an authorization code. Something went wrong. | ||
} else { | ||
error_log('Authorization failed!'); | ||
} | ||
} | ||
|
||
# Execute the callback | ||
callback(); | ||
|
||
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
<?php | ||
|
||
# This file simply serves the link that merchants click to authorize your application. | ||
# When authorization completes, a notification is sent to your redirect URL, which should | ||
# be handled in callback.php. | ||
|
||
$applicationId = 'REPLACE_ME'; | ||
|
||
echo "<a href=\"https://connect.squareup.com/oauth2/authorize?client_id=$applicationId\">Click here</a> to authorize the application."; | ||
?> |
4 changes: 2 additions & 2 deletions
4
connect-examples/oauth/README.md → connect-examples/oauth/python/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
<?php | ||
|
||
# Demonstrates creating, updating, and deleting an item with the Square Connect API. | ||
# Replace the value of the `access_token` variable below before running this sample. | ||
# | ||
# This sample requires the Unirest PHP library. Download it here: | ||
# http://unirest.io/php.html | ||
# | ||
# Results are logged with error_log. | ||
|
||
|
||
# Replace this value with the path to the Unirest PHP library | ||
require_once 'path/to/Unirest.php'; | ||
|
||
|
||
# Replace this value with your application's personal access token, | ||
# available from your application dashboard (https://connect.squareup.com/apps) | ||
$accessToken = 'REPLACE_ME'; | ||
|
||
# The base URL for every Connect API request | ||
$connectHost = 'https://connect.squareup.com'; | ||
|
||
# Standard HTTP headers for every Connect API request | ||
$requestHeaders = array ( | ||
'Authorization' => 'Bearer ' . $accessToken, | ||
'Accept' => 'application/json', | ||
'Content-Type' => 'application/json' | ||
); | ||
|
||
# Creates a "Milkshake" item. | ||
function createItem() { | ||
global $accessToken, $connectHost, $requestHeaders; | ||
|
||
$request_body = array( | ||
"name"=>"Milkshake", | ||
"variations"=>array( | ||
array( | ||
"name"=>"Small", | ||
"pricing_type"=>"FIXED_PRICING", | ||
"price_money"=>array( | ||
"currency_code"=>"USD", | ||
"amount"=>400 | ||
) | ||
) | ||
) | ||
); | ||
|
||
$response = Unirest\Request::post($connectHost . '/v1/me/items', $requestHeaders, json_encode($request_body)); | ||
|
||
if ($response->code == 200) { | ||
error_log('Successfully created item:'); | ||
error_log(json_encode($response->body, JSON_PRETTY_PRINT)); | ||
return $response->body; | ||
} else { | ||
error_log('Item creation failed'); | ||
return NULL; | ||
} | ||
} | ||
|
||
# Updates the Milkshake item to rename it to "Malted Milkshake" | ||
function updateItem($itemId) { | ||
global $accessToken, $connectHost, $requestHeaders; | ||
|
||
$request_body = array( | ||
"name"=>"Malted Milkshake" | ||
); | ||
|
||
$response = Unirest\Request::put($connectHost . '/v1/me/items/' . $itemId, $requestHeaders, json_encode($request_body)); | ||
|
||
if ($response->code == 200) { | ||
error_log('Successfully updated item:'); | ||
error_log(json_encode($response->body, JSON_PRETTY_PRINT)); | ||
return $response->body; | ||
} else { | ||
error_log('Item update failed'); | ||
return NULL; | ||
} | ||
} | ||
|
||
# Deletes the Malted Milkshake item. | ||
function deleteItem($itemId) { | ||
global $accessToken, $connectHost, $requestHeaders; | ||
|
||
$response = Unirest\Request::delete($connectHost . '/v1/me/items/' . $itemId, $requestHeaders); | ||
|
||
if ($response->code == 200) { | ||
error_log('Successfully deleted item'); | ||
return $response->body; | ||
} else { | ||
error_log('Item deletion failed'); | ||
return NULL; | ||
} | ||
} | ||
|
||
$myItem = createItem(); | ||
|
||
# Update and delete the item only if it was successfully created | ||
if ($myItem) { | ||
updateItem($myItem->id); | ||
deleteItem($myItem->id); | ||
} else { | ||
error_log("Aborting"); | ||
} | ||
|
||
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
<?php | ||
|
||
# Demonstrates generating a 2014 payments report with the Square Connect API. | ||
# Replace the value of the `$accessToken` variable below before running this script. | ||
# | ||
# This sample assumes all monetary amounts are in US dollars. You can alter the | ||
# formatMoney function to display amounts in other currency formats. | ||
# | ||
# This sample requires the Unirest PHP library. Download it here: | ||
# http://unirest.io/php.html | ||
# | ||
# Results are rendered in a simple HTML pre block. | ||
|
||
|
||
# Replace this value with the path to the Unirest PHP library | ||
require_once 'path/to/Unirest.php'; | ||
|
||
# Replace this value with your application's personal access token, | ||
# available from your application dashboard (https://connect.squareup.com/apps) | ||
$accessToken = 'REPLACE_ME'; | ||
|
||
# The base URL for every Connect API request | ||
$connectHost = 'https://connect.squareup.com'; | ||
|
||
# Helper function to convert cent-based money amounts to dollars and cents | ||
function formatMoney($money) { | ||
return money_format('%+.2n', $money / 100); | ||
} | ||
|
||
# Retrieves all of a merchant's payments from 2014 | ||
function get2014Payments() { | ||
global $accessToken, $connectHost; | ||
|
||
# Restrict the request to the 2014 calendar year, eight hours behind UTC | ||
# Make sure to URL-encode all parameters | ||
$parameters = http_build_query( | ||
array( | ||
'begin_time' => '2014-01-01T00:00:00-08:00', | ||
'end_time' => '2015-01-01T00:00:00-08:00' | ||
) | ||
); | ||
|
||
# Standard HTTP headers for every Connect API request | ||
$requestHeaders = array ( | ||
'Authorization' => 'Bearer ' . $accessToken, | ||
'Accept' => 'application/json', | ||
'Content-Type' => 'application/json' | ||
); | ||
|
||
$payments = array(); | ||
$requestPath = $connectHost . '/v1/me/payments?' . $parameters; | ||
$moreResults = true; | ||
|
||
while ($moreResults) { | ||
|
||
# Send a GET request to the List Payments endpoint | ||
$response = Unirest\Request::get($requestPath, $requestHeaders); | ||
|
||
# Read the converted JSON body into the cumulative array of results | ||
$payments = array_merge($payments, $response->body); | ||
|
||
# Check whether pagination information is included in a response header, indicating more results | ||
if (array_key_exists('Link', $response->headers)) { | ||
$paginationHeader = $response->headers['Link']; | ||
if (strpos($paginationHeader, "rel='next'") !== false) { | ||
|
||
# Extract the next batch URL from the header. | ||
# | ||
# Pagination headers have the following format: | ||
# <https://connect.squareup.com/v1/MERCHANT_ID/payments?batch_token=BATCH_TOKEN>;rel='next' | ||
# This line extracts the URL from the angle brackets surrounding it. | ||
$requestPath = explode('>', explode('<', $paginationHeader)[1])[0]; | ||
} else { | ||
$moreResults = false; | ||
} | ||
} else { | ||
$moreResults = false; | ||
} | ||
} | ||
|
||
# Remove potential duplicate values from the list of payments | ||
$seenPaymentIds = array(); | ||
$uniquePayments = array(); | ||
foreach ($payments as $payment) { | ||
if (array_key_exists($payment->id, $seenPaymentIds)) { | ||
continue; | ||
} | ||
$seenPaymentIds[$payment->id] = true; | ||
array_push($uniquePayments, $payment); | ||
} | ||
|
||
return $uniquePayments; | ||
} | ||
|
||
# Prints a sales report based on an array of payments | ||
function printSalesReport($payments) { | ||
|
||
# Variables for holding cumulative values of various monetary amounts | ||
$collectedMoney = $taxes = $tips = $discounts = $processingFees = 0; | ||
$returned_processingFees = $netMoney = $refunds = 0; | ||
|
||
# Add appropriate values to each cumulative variable | ||
foreach ($payments as $payment) { | ||
$collectedMoney = $collectedMoney + $payment->total_collected_money->amount; | ||
$taxes = $taxes + $payment->tax_money->amount; | ||
$tips = $tips + $payment->tip_money->amount; | ||
$discounts = $discounts + $payment->discount_money->amount; | ||
$processingFees = $processingFees + $payment->processing_fee_money->amount; | ||
$netMoney = $netMoney + $payment->net_total_money->amount; | ||
$refunds = $refunds + $payment->refunded_money->amount; | ||
|
||
|
||
# When a refund is applied to a credit card payment, Square returns to the merchant a percentage | ||
# of the processing fee corresponding to the refunded portion of the payment. This amount | ||
# is not currently returned by the Connect API, but we can calculate it as shown: | ||
|
||
# If a processing fee was applied to the payment AND some portion of the payment was refunded... | ||
if ($payment->processing_fee_money->amount < 0 and $payment->refunded_money->amount < 0) { | ||
|
||
# ...calculate the percentage of the payment that was refunded... | ||
$percentage_refunded = $payment->refunded_money->amount / (float)$payment->total_collected_money->amount; | ||
|
||
# ...and multiply that percentage by the original processing fee | ||
$returned_processingFees = $returned_processingFees + ($payment->processing_fee_money->amount * $percentage_refunded); | ||
} | ||
} | ||
|
||
# Calculate the amount of pre-tax, pre-tip money collected | ||
$basePurchases = $collectedMoney - $taxes - $tips; | ||
|
||
|
||
# Print a sales report similar to the Sales Summary in the merchant dashboard. | ||
echo '<pre>'; | ||
echo '==SALES REPORT FOR 2014==' . '<br/>'; | ||
echo 'Gross Sales: ' . formatMoney($basePurchases - $discounts) . '<br/>'; | ||
echo 'Discounts: ' . formatMoney($discounts) . '<br/>'; | ||
echo 'Net Sales: ' . formatMoney($basePurchases) . '<br/>'; | ||
echo 'Tax collected: ' . formatMoney($taxes) . '<br/>'; | ||
echo 'Tips collected: ' . formatMoney($tips) . '<br/>'; | ||
echo 'Total collected: ' . formatMoney($basePurchases + $taxes + $tips) . '<br/>'; | ||
echo 'Fees: ' . formatMoney($processingFees) . '<br/>'; | ||
echo 'Refunds: ' . formatMoney($refunds) . '<br/>'; | ||
echo 'Fees returned: ' . formatMoney($returned_processingFees) . '<br/>'; | ||
echo 'Net total: ' . formatMoney($netMoney + $refunds + $returned_processingFees) . '<br/>'; | ||
echo '</pre>'; | ||
|
||
} | ||
|
||
# Call the functions defined above | ||
$payments = get2014Payments(); | ||
printSalesReport($payments); | ||
|
||
?> |
Oops, something went wrong.