Skip to content

Commit

Permalink
Fixed Ruby V1 Example
Browse files Browse the repository at this point in the history
Fixed dates and error checking.
  • Loading branch information
StephenJosey authored Sep 5, 2018
1 parent d4c7ae4 commit 71aca02
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 33 deletions.
18 changes: 18 additions & 0 deletions connect-examples/v1/ruby/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
## Ruby V1 example

The samples in this directory demonstrate basic use of Square Connect API v1 in Ruby. Before you run any of these samples, be sure to complete the steps described below.

### How to run
* First, install `unirest` by opening your terminal
and typing:
```
gem install unirest
gem install sinatra
```
* Fill in the required variables (`REPLACE_ME`)
in all of the files
* Then run each file individually:
```
ruby item-management.rb
ruby payments-report.rb
```
3 changes: 3 additions & 0 deletions connect-examples/v1/ruby/item-management.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ def update_item(item_id)
return response.body
else
puts 'Item update failed'
puts response.body
return nil
end
end
Expand All @@ -88,6 +89,7 @@ def delete_item(item_id)
return response.body
else
puts 'Item deletion failed'
puts response.body
return nil
end
end
Expand All @@ -100,4 +102,5 @@ def delete_item(item_id)
delete_item(my_item['id'])
else
puts 'Aborting'
puts response.body
end
79 changes: 46 additions & 33 deletions connect-examples/v1/ruby/payments-report.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Demonstrates generating a 2015 payments report with the Square Connect API.
# Demonstrates generating the last year's payments report with the Square Connect API.
# Replace the value of the `ACCESS_TOKEN` variable below before running this script.
#
# This sample assumes all monetary amounts are in US dollars. You can alter the
Expand All @@ -10,6 +10,7 @@
require 'set'
require 'unirest'
require 'uri'
require 'date'


# Replace this value with your application's personal access token,
Expand Down Expand Up @@ -40,24 +41,28 @@ def get_location_ids()
request_path = '/v1/me/locations'
response = Unirest.get CONNECT_HOST + request_path,
headers: REQUEST_HEADERS
locations = response.body
location_ids = []
if response.code == 200
locations = response.body

for location in locations
location_ids.push(location['id'])
for location in locations
location_ids.push(location['id'])
end
else
raise response.body.to_s
end

return location_ids
end

# Retrieves all of a merchant's payments from 2015
def get_2015_payments(location_ids)
# Retrieves all of a merchant's payments from last year
def get_payments(location_ids)

# Restrict the request to the 2015 calendar year, eight hours behind UTC
# Restrict the request to the last calendar year, eight hours behind UTC
# Make sure to URL-encode all parameters
parameters = URI.encode_www_form(
'begin_time' => '2015-01-01T00:00:00-08:00',
'end_time' => '2016-01-01T00:00:00-08:00'
'begin_time' => Date.new(Time.now.year - 1, 1, 1).iso8601.to_s,
'end_time' => Date.new(Time.now.year, 1, 1).iso8601.to_s
)

payments = []
Expand All @@ -76,26 +81,30 @@ def get_2015_payments(location_ids)
response = Unirest.get request_path,
headers: REQUEST_HEADERS,
parameters: parameters

# Read the converted JSON body into the cumulative array of results
payments += response.body

# Check whether pagination information is included in a response header, indicating more results
if response.headers.has_key?(:link)
pagination_header = response.headers[:link]
if pagination_header.include? "rel='next'"

# 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.
request_path = pagination_header.split('<')[1].split('>')[0]
if response.code == 200

# Read the converted JSON body into the cumulative array of results
payments += response.body

# Check whether pagination information is included in a response header, indicating more results
if response.headers.has_key?(:link)
pagination_header = response.headers[:link]
if pagination_header.include? "rel='next'"

# 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.
request_path = pagination_header.split('<')[1].split('>')[0]
else
more_results = false
end
else
more_results = false
end
else
more_results = false
raise response.body.to_s
end
end
end
Expand All @@ -106,7 +115,7 @@ def get_2015_payments(location_ids)
unique_payments = []
for payment in payments
if seen_payment_ids.include? payment['id']
next
next
end
seen_payment_ids.add(payment['id'])
unique_payments.push(payment)
Expand Down Expand Up @@ -134,31 +143,31 @@ def print_sales_report(payments)
refunds = refunds + payment['refunded_money']['amount']


# When a refund is applied to a credit card payment, Square returns to the merchant a percentage
# 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 && payment['refunded_money']['amount'] < 0

# ...calculate the percentage of the payment that was refunded...
percentage_refunded = payment['refunded_money']['amount'] /
percentage_refunded = payment['refunded_money']['amount'] /
payment['total_collected_money']['amount'].to_f

# ...and multiply that percentage by the original processing fee
returned_processing_fees = returned_processing_fees +
returned_processing_fees = returned_processing_fees +
(payment['processing_fee_money']['amount'] * percentage_refunded)
end
end



# Calculate the amount of pre-tax, pre-tip money collected
base_purchases = collected_money - taxes - tips

# Print a sales report similar to the Sales Summary in the merchant dashboard.
puts ''
puts '==SALES REPORT FOR 2015=='
puts '==SALES REPORT FOR ' + (Time.now.year - 1).to_s + '=='
puts 'Gross Sales: ' + format_money(base_purchases - discounts)
puts 'Discounts: ' + format_money(discounts)
puts 'Net Sales: ' + format_money(base_purchases)
Expand All @@ -172,5 +181,9 @@ def print_sales_report(payments)
end

# Call the functions defined above
payments = get_2015_payments(get_location_ids())
print_sales_report(payments)
begin
payments = get_payments(get_location_ids())
print_sales_report(payments)
rescue StandardError => e
puts e.message
end

0 comments on commit 71aca02

Please sign in to comment.