Ejemplo n.º 1
0
import os

from square.client import Client

# Create an instance of the API Client
# and initialize it with the credentials
# for the Square account whose assets you want to manage

square_client = Client(
    access_token=os.environ.get("SQUARE_APP_TOKEN"),
    environment='sandbox',
)
Ejemplo n.º 2
0
    + 'This link will be active for two weeks; please be sure to download your pattern within that time period. '\
    + 'If you have any questions or need any assistance, please feel free to contact me by emailing me directly at '\
    + '[email protected] or by reaching out through the contact form on the website.'\
    + '\n\nDownload Link: ' + downloadLink +\
    '\n\nThank you again for your support!\nMy Crafts\n@IG\nhttps://my-site.square.site'
subject = digitalItemName + ' Download Link'

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, sent_from, subject, body)

client = Client(access_token=application_secret, environment='production')

result = client.orders.search_orders(
    body={
        "location_ids": ["SQUARE-LOCATION-ID"],
        "query": {
            "filter": {
                "state_filter": {
                    "states": ["OPEN"]
                },
                "fulfillment_filter": {
                    "fulfillment_types": ["DIGITAL"]
                }
            }
        }
    })
Ejemplo n.º 3
0
from square.client import Client

# Create an instance of the API Client
# and initialize it with the credentials
# for the Square account whose assets you want to manage

client = Client(
    access_token=
    'EAAAEL9Ne4RXFPJBh_SvhmkC80bW2n6F2izDRDSyMYeGJ3H4DCG_YPkfUPFIQQkT',
    environment='sandbox',
)

body = {}
body['source_id'] = 'ccof:uIbfJXhXETSP197M3GB'
body['idempotency_key'] = '4935a656-a929-4792-b97c-8848be85c27c'
body['amount_money'] = {}
body['amount_money']['amount'] = 200
body['amount_money']['currency'] = 'USD'
body['tip_money'] = {}
body['tip_money']['amount'] = 198
body['tip_money']['currency'] = 'USD'
body['app_fee_money'] = {}
body['app_fee_money']['amount'] = 10
body['app_fee_money']['currency'] = 'USD'
#body['delay_duration'] = 'delay_duration6'
body['autocomplete'] = False
body['order_id'] = '123'
body['customer_id'] = 'VDKXEEKPJN48QDG3BGGFAK05P8'
body['location_id'] = 'L966W4YHYGNWP'
body['reference_id'] = '123456'
body['note'] = 'Brief description'
Ejemplo n.º 4
0
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
nonce = form.getvalue('nonce')

# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
config_type = "PRODUCTION" if config.get("DEFAULT",
                                         "is_prod") == "true" else "SANDBOX"
access_token = config.get(config_type, "access_token")

# Create an instance of the API Client
# and initialize it with the credentials
# for the Square account whose assets you want to manage
client = Client(
    access_token=access_token,
    environment=config.get(config_type, "environment"),
)

# Every payment you process with the SDK must have a unique idempotency key.
# If you're unsure whether a particular payment succeeded, you can reattempt
# it with the same idempotency key without worrying about double charging
# the buyer.
idempotency_key = str(uuid.uuid1())

# Monetary amounts are specified in the smallest unit of the applicable currency.
# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
amount = {'amount': 100, 'currency': 'USD'}

# To learn more about splitting payments with additional recipients,
# see the Payments API documentation on our [developer site]
# (https://developer.squareup.com/docs/payments-api/overview).
Ejemplo n.º 5
0
from square.client import Client
client = Client(
    access_token=
    'EAAAEIl3awo49_UE8Is_9S0pAp2n_0-fIrDfgDnVoSZYU5_dD4ZhWbnPH534oBGh')
#使用Search catalog objects进行前缀查询
result = client.catalog.search_catalog_objects(
    body={
        "object_types": ["ITEM"],
        "query": {
            "prefix_query": {
                "attribute_name": "name",
                "attribute_prefix": "hot"
            }
        }
    })

if result.is_success():
    print(result.body)
elif result.is_error():
    print(result.errors)
Ejemplo n.º 6
0
#
# 1. A merchant clicks the authorization link served by the root path (http://localhost:8080/)
# 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 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.

from flask import Flask, request
from square.client import Client

client = Client(environment="production")
obtain_token = client.o_auth.obtain_token

app = Flask(__name__)

# Your application's ID and secret, available from your application dashboard.
application_id = 'REPLACE_ME'
application_secret = 'REPLACE_ME'


# Serves the link that merchants click to authorize your application
@app.route('/', methods=['GET'])
def authorize():
    return '''<a href="https://connect.squareup.com/oauth2/authorize?client_id={0}">Click here</a>
            to authorize the application.'''.format(application_id)
Ejemplo n.º 7
0
d_format = workbook.add_format({'num_format': 'yyyy/mm/dd'})

class ResultError(Exception):
    def __init__(self, salary, message="Squareup API failed. Check Access Token"):
        for error in result.errors:
            print(error['category'])
            print(error['code'])
            print(error['detail'])
        self.result = result
        super().__init__(error['detail'])
        sys.exit(1)

for access_token in token_list:
    client = Client(
        access_token=access_token,
        environment='production',
        max_retries=2,
        timeout=125
        )

    # Get Shop name and id
    result = client.locations.list_locations()
    if result.is_success():
        shop        = result.body['locations'][0]['name']
        location_id = result.body['locations'][0]['id']
    else:
        ResultError(result)
        
    # Get all payouts in given period (Weekly bank transactions)
    results = client.payouts.list_payouts(
        location_id = location_id,
        begin_time  = start_time + "T00:00:00+09:00",
Ejemplo n.º 8
0
#   http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''This module defines all the Square OAuth related operations'''

from square.client import Client
import os

client_id = os.environ['application_id']
client_secret = os.environ['application_secret']

# initialize square oauth client
square_client = Client(environment=os.environ['environment'], )
oauth_api = square_client.o_auth


def conduct_authorize_url(state):
    '''Conduct a Square authorization url 

  This method creates a Square authroization url that takes client to Square
  authorization page to finish OAuth permission grant process.

  This url contains several important query parameters:

  client_id - aka. application id, the Square application which is requesting permissions.

  scope - s space-separated list of the permissions the application is requesting, different square api require different permissions.
Ejemplo n.º 9
0
from square.client import Client
from square.configuration import Configuration


client = Client(
    access_token='AccessToken',
)

customers_api = client.customers

customer_id = 'customer_id'

result = customers_api.delete(customer_id)

if result.success():
    print(result.body)
    print("success")
elif result.error():
    print(result.errors)
Ejemplo n.º 10
0
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from square.client import Client
import random
import string

client = Client(
    access_token=
    'EAAAEAa7wVPz5T17WOrXMxCLKrzYUk76Rglo9QynVsz7KmA3z-5LxP8bCYlAQTTS',
    environment='sandbox',
)
payments_api = client.payments


class PaymentView(APIView):
    def get(self, request):
        id = self.request.query_params.get('id', None)
        if id is not None:
            result = payments_api.get_payment(id)
        else:
            result = payments_api.list_payments()
        if result.is_success():
            return Response(result.body, status=status.HTTP_200_OK)
        else:
            return Response(data=result.errors,
                            status=status.HTTP_404_NOT_FOUND)

    def post(self, request, *args, **kwargs):
        body = {}
        body['source_id'] = self.request.data.get("nonce", None)
 def __init__(self):
     self.client = Client(
         square_version=SquareApp.VERSION,
         access_token=SquareApp.ACCESS_TOKEN,
         environment=SquareApp.ENV
     )
Ejemplo n.º 12
0
def main():
    try:
        client = Client(
            square_version='2021-01-21',
            access_token=SQUARE_BEARER_TOKEN,
            environment='production',
        )
    except Exception as e:
        logging.error("Cannot connect to square : {}".format(e.message))

    body = {}
    body['location_ids'] = [SQUARE_LOCATION_ID]  # Just using one
    body['limit'] = 200
    body['query'] = {}
    body['query']['filter'] = {}
    body['query']['filter']['state_filter'] = {}
    body['query']['filter']['state_filter']['states'] = ['OPEN']
    body['query']['filter']['date_time_filter'] = {}
    body['query']['filter']['date_time_filter']['created_at'] = {}
    body['query']['filter']['date_time_filter']['created_at'][
        'start_at'] = PROCESSING_START_DATETIME
    body['query']['filter']['date_time_filter']['created_at'][
        'end_at'] = PROCESSING_END_DATETIME
    body['query']['filter']['fulfillment_filter'] = {}
    body['query']['filter']['fulfillment_filter']['fulfillment_types'] = [
        'SHIPMENT'
    ]
    body['query']['filter']['fulfillment_filter']['fulfillment_states'] = [
        'PROPOSED'
    ]
    body['return_entries'] = True
    body['query']['sort'] = {}
    body['query']['sort']['sort_field'] = 'CREATED_AT'
    body['query']['sort']['sort_order'] = 'ASC'
    body['query']['filter']['customer_filter'] = {}
    orders_api = client.orders
    orders_raw = orders_api.search_orders(body)

    if orders_raw.is_success():
        print(orders_raw.body)
    elif orders_raw.is_error():
        print(orders_raw.errors)

    all_orders = orders_raw.body.get('order_entries')
    if all_orders:
        print("Found [{}] orders in square to process.".format(
            len(all_orders)))
    for order_cursor in all_orders:
        order = orders_api.retrieve_order(
            order_cursor['order_id']).body['order']
        created_on = parse(order.get('created_at')).date()

        #check only from a certain time forward
        if created_on >= parse(PROCESSING_START_DATETIME).date(
        ) and created_on < parse(PROCESSING_END_DATETIME).date():
            #if order.get('id') == 'Hv5nLw567WQcPMvyEFRvbttF7BeZY': #me
            #if order.get('id') == 'vtwmcNbBlJCJ15WXoPQIuQVzYucZY': #sissy
            #if order.get('id') == '9q78JCThpddGoaPBemt3ukD33DIZY': #unregistered user
            #if order.get('id') == 'vJOMD95Etuokh4F2nKfO19mtFOUZY': #unregistered user

            logging.info("Processing Order: {}".format(order))

            if 'line_items' in order:
                for item in order['line_items']:
                    sr = MulchSalesReceipt()
                    logging.debug("Processing Line Item: {}".format(item))
                    if 'name' in item:
                        #print(item0)
                        if re.findall(SEARCH_KEYS, item['name'].lower()):
                            process_order = True
                            logging.debug(
                                "Processing Line Item: {}".format(item))
                            item_name = item['name'].lower()
                            item_quantity = int(item['quantity'])
                            item_variation = item['variation_name']
                            # get customer for order if we have a customer id
                            if bool(order.get('customer_id', None)):
                                logging.info(
                                    "Processing Square customer id: [{}], order id:[{}], details: [Item:{}, variation:{}, quantity:{}]"
                                    .format(order['customer_id'], order['id'],
                                            item_name, item_variation,
                                            item_quantity))
                                customer_id = order['customer_id']
                                payment_id = order['tenders'][0]['id']
                                try:
                                    payments_api = client.payments
                                    payment_raw = payments_api.get_payment(
                                        payment_id)
                                    if payment_raw.is_success():
                                        payment = payment_raw.body['payment']
                                        logging.debug(
                                            "Payment Raw: {}".format(payment))
                                        sr.customer_street = payment[
                                            'shipping_address'][
                                                'address_line_1']
                                        sr.customer_state = payment[
                                            'shipping_address'][
                                                'administrative_district_level_1']
                                        sr.customer_city = payment[
                                            'shipping_address']['locality']
                                        sr.customer_zip = payment[
                                            'shipping_address']['postal_code']
                                        sr.customer_email = payment[
                                            'buyer_email_address']
                                    else:
                                        logging.error(
                                            "Cannot find square payment for payment_id: [{}]"
                                            .format(payment_id))
                                        process_order = False
                                except Exception as e:
                                    logging.error(
                                        "Error finding square payment for payment_id: [{}], msg:[{}]"
                                        .format(payment_id, e.message))
                                    process_order = False
                                try:
                                    customers_api = client.customers
                                    customer_raw = customers_api.retrieve_customer(
                                        customer_id)
                                    if customer_raw.is_success():
                                        customer = customer_raw.body[
                                            'customer']
                                        logging.debug(
                                            "Customer Response: {}".format(
                                                customer))
                                        sr.customer_first = format(
                                            customer['given_name'])
                                        sr.customer_last = customer[
                                            'family_name']
                                        sr.customer_name = "{} {}".format(
                                            customer['given_name'],
                                            customer['family_name'])
                                        if customer.get('phone_number',
                                                        None) is not None:
                                            formatted_phone = phonenumbers.format_number(
                                                phonenumbers.parse(
                                                    customer.get(
                                                        'phone_number', None),
                                                    "US"), phonenumbers.
                                                PhoneNumberFormat.NATIONAL)
                                            sr.customer_phone = formatted_phone
                                    else:
                                        logging.error(
                                            "Cannot process square customer id: [{}]"
                                            .format(customer_id))
                                        process_order = False
                                except Exception as e:
                                    logging.error(
                                        "Error processing square customer id: [{}], msg: {}"
                                        .format(customer_id, e.message))
                                    process_order = False
                                if order['fulfillments'][0].get(
                                        'shipment_details'
                                ) and order['fulfillments'][0][
                                        'shipment_details'].get(
                                            'shipping_note'):
                                    sr.memo = order['fulfillments'][0][
                                        'shipment_details']['shipping_note']

                            else:  # otherwise get the customer from the order itself (customer not registered)
                                logging.info(
                                    "Processing Square (non-registered customer): order id:[{}], createdOn: [{}]"
                                    .format(order['id'], order['created_at']))

                                logging.debug("getting from fulfillments")
                                sr.customer_name = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'display_name']
                                sr.customer_last = sr.customer_name.split(
                                    ' ')[-1]
                                sr.customer_first = sr.customer_name.split(
                                    ' ')[0]
                                sr.customer_street = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'address']['address_line_1']
                                sr.customer_city = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'address']['locality']
                                sr.customer_state = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'address'][
                                            'administrative_district_level_1']
                                sr.customer_zip = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'address']['postal_code']
                                sr.customer_email = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'email_address']
                                sr.customer_phone = order['fulfillments'][0][
                                    'shipment_details']['recipient'][
                                        'phone_number']
                                sr.memo = order['fulfillments'][0][
                                    'shipment_details']['shipping_note']

                            #print("matched: {}".format(item0))
                            # item_name = item['name'].lower()
                            # item_quantity = int(item['quantity'])
                            # item_variation = item['variation_name']

                            #now we have a clean line item for mulch. Build the object out for importing into quickbooks
                            if process_order:
                                sr = extract_item(sr, item_quantity, item_name,
                                                  item_variation)
                                sr.date = order['created_at']
                                sr.product_price = square_money_to_decimal(
                                    item['base_price_money']['amount'])
                                sr.total_price = square_money_to_decimal(
                                    item['total_money']['amount'])
                                create_order(sr)
                                logging.debug(sr)
                            else:
                                logging.error(
                                    "Cannot process Order for orderid [{}]. Either the customer or the payment cannot be found in square...skipping"
                                    .format(order['id']))
Ejemplo n.º 13
0
import bcrypt
from flask_cors import CORS
from square.client import Client
from os import urandom, environ
from base64 import b64encode
from math import ceil
from dotenv import load_dotenv

load_dotenv()
SQUARE_TOKEN = environ['SQUARE_TOKEN']
SQUARE_ENVIRONMENT = environ['SQUARE_ENVIRONMENT']
DEBUG_ENABLED = environ['DEBUG_ENABLED']
JWT_SECRET_KEY = environ['JWT_SECRET_KEY']
SQLALCHEMY_DATABASE_URI = environ['SQLALCHEMY_DATABASE_URI']

square = Client(access_token=SQUARE_TOKEN, environment=SQUARE_ENVIRONMENT)

app = Flask(__name__)

app.config['DEBUG'] = DEBUG_ENABLED == "yes"
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI

app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = False

CORS(app)

jwt = JWTManager(app)

SQLALCHEMY_TRACK_MODIFICATIONS = True
db = SQLAlchemy(app, model_class=FlaskBaseModel)
Ejemplo n.º 14
0
 def setUpClass(cls):
     """Class method called once before running tests in a test class."""
     cls.request_timeout = 30
     cls.assert_precision = 0.01
     cls.config = ApiTestBase.create_configuration()
     cls.client = Client()
# SnackOverflow Square Inventory Updater: Restricts max number of changes made at once to 100
from square.client import Client
from datetime import datetime
import uuid
import sys
import os
import config

# Create an instance of the API Client 
# and initialize it with the credentials 
# for the Square account whose assets you want to manage

client = Client(
    access_token = config.access_token,
    environment = config.environment,
)

# Get an instance of the Square API you want to call
inventory_api = client.inventory
catalog_api = client.catalog

# This function takes in a costco id and returns the corresponding Square object id
def get_object_id(costco_id):
    # The payload sent to the API
    body = {}
    body['object_types'] = ['ITEM']
    body['include_deleted_objects'] = False
    body['include_related_objects'] = False
    body['query'] = {}
    body['query']['prefix_query'] = {}
    body['query']['prefix_query']['attribute_name'] = 'description'
Ejemplo n.º 16
0
def main():
    #Setup some quickbooks defaults
    default_deposit_account_ref = lookup_deposit_account(
        DEFAULT_DEPOSIT_ACCOUNT)
    default_pament_method_ref = lookup_payment_method('Square')

    try:
        client = Client(
            square_version='2021-01-21',
            access_token=SQUARE_BEARER_TOKEN,
            environment='production',
        )
    except Exception as e:
        logging.error("Cannot connect to square : {}".format(e.message))

    body = {}
    body['location_ids'] = [SQUARE_LOCATION_ID]  # Just using one
    body['limit'] = 200
    body['query'] = {}
    body['query']['filter'] = {}
    body['query']['filter']['state_filter'] = {}
    body['query']['filter']['state_filter']['states'] = ['OPEN']
    body['query']['filter']['date_time_filter'] = {}
    body['query']['filter']['date_time_filter']['created_at'] = {}
    body['query']['filter']['date_time_filter']['created_at'][
        'start_at'] = PROCESSING_START_DATETIME
    body['query']['filter']['date_time_filter']['created_at'][
        'end_at'] = PROCESSING_END_DATETIME
    body['query']['filter']['fulfillment_filter'] = {}
    body['query']['filter']['fulfillment_filter']['fulfillment_types'] = [
        'SHIPMENT', 'DIGITAL'
    ]
    body['query']['filter']['fulfillment_filter']['fulfillment_states'] = [
        'PROPOSED'
    ]
    body['query']['filter']['tenders_filter'] = {}
    body['query']['filter']['tenders_filter']['card_details'] = {}
    body['query']['filter']['tenders_filter']['card_details']['status'] = [
        'CAPTURED'
    ]
    body['return_entries'] = True
    body['query']['sort'] = {}
    body['query']['sort']['sort_field'] = 'CREATED_AT'
    body['query']['sort']['sort_order'] = 'ASC'
    body['query']['filter']['customer_filter'] = {}
    orders_api = client.orders
    orders_raw = orders_api.search_orders(body)

    if orders_raw.is_success():
        print(orders_raw.body)
    elif orders_raw.is_error():
        print(orders_raw.errors)

    all_orders = orders_raw.body.get('order_entries')
    if all_orders is not None:
        print("Found [{}] orders in square to process.".format(
            len(all_orders)))
        for order_cursor in all_orders:
            order = orders_api.retrieve_order(
                order_cursor['order_id']).body['order']
            created_on = parse(order.get('created_at')).date()

            #check only from a certain time forward

            #This filter area is for testing...
            #if created_on >= parse(PROCESSING_START_DATETIME).date() and created_on < parse(PROCESSING_END_DATETIME).date():
            #if order.get('id') == 'Hv5nLw567WQcPMvyEFRvbttF7BeZY': #me
            #if order.get('id') == 'vtwmcNbBlJCJ15WXoPQIuQVzYucZY': #sissy
            #if order.get('id') == '9q78JCThpddGoaPBemt3ukD33DIZY': #unregistered user
            #if order.get('id') == 'vJOMD95Etuokh4F2nKfO19mtFOUZY': #unregistered user
            #if order.get('id') == 'J8F6LmRGZHDWS26eDSnGJ2A20mSZY':   #another smith
            #if order.get('id') == 'T1jELiTjKFLhxWKlwMOVRdIos75YY':   #Bob Bethea
            #if order.get('id') == 'b5HOXgm7Y0iSv8WGIS6OdqaeY9IZY': #hartz (check after 3/5 to see if deleted)
            if True:
                logging.info("Processing Order: {}".format(order))

                if 'line_items' in order:
                    for item in order['line_items']:
                        sr = MulchSalesReceipt()
                        logging.debug("Processing Line Item: {}".format(item))
                        if 'name' in item:
                            #print(item0)
                            if re.findall(SEARCH_KEYS, item['name'].lower()):
                                process_order = True
                                logging.debug(
                                    "Processing Line Item: {}".format(item))
                                item_name = item['name'].lower()
                                item_quantity = int(item['quantity'])
                                item_variation = item['variation_name']
                                # get customer for order if we have a customer id
                                if bool(order.get('customer_id', None)):
                                    logging.info(
                                        "Processing Square customer id: [{}], order id:[{}], details: [Item:{}, variation:{}, quantity:{}]"
                                        .format(order['customer_id'],
                                                order['id'], item_name,
                                                item_variation, item_quantity))
                                    customer_id = order['customer_id']
                                    payment_id = order['tenders'][0]['id']
                                    try:
                                        payments_api = client.payments
                                        payment_raw = payments_api.get_payment(
                                            payment_id)
                                        if payment_raw.is_success():
                                            payment = payment_raw.body[
                                                'payment']
                                            logging.debug(
                                                "Payment Raw: {}".format(
                                                    payment))
                                            sr.customer_street = payment[
                                                'shipping_address'][
                                                    'address_line_1']
                                            sr.customer_state = payment[
                                                'shipping_address'][
                                                    'administrative_district_level_1']
                                            sr.customer_city = payment[
                                                'shipping_address']['locality']
                                            sr.customer_zip = payment[
                                                'shipping_address'][
                                                    'postal_code']
                                            sr.customer_email = payment[
                                                'buyer_email_address']
                                        else:
                                            logging.error(
                                                "Cannot find square payment for payment_id: [{}]"
                                                .format(payment_id))
                                            process_order = False
                                    except Exception as e:
                                        logging.error(
                                            "Error finding square payment for payment_id: [{}], msg:[{}]"
                                            .format(payment_id, e.message))
                                        process_order = False
                                    try:
                                        customers_api = client.customers
                                        customer_raw = customers_api.retrieve_customer(
                                            customer_id)
                                        if customer_raw.is_success():
                                            customer = customer_raw.body[
                                                'customer']
                                            logging.debug(
                                                "Customer Response: {}".format(
                                                    customer))
                                            sr.customer_first = format(
                                                customer['given_name']
                                            ).capitalize()
                                            sr.customer_last = customer[
                                                'family_name'].capitalize()
                                            sr.customer_name = "{} {}".format(
                                                sr.customer_first,
                                                sr.customer_last)
                                            if customer.get(
                                                    'phone_number',
                                                    None) is not None:
                                                formatted_phone = phonenumbers.format_number(
                                                    phonenumbers.parse(
                                                        customer.get(
                                                            'phone_number',
                                                            None),
                                                        "US"), phonenumbers.
                                                    PhoneNumberFormat.NATIONAL)
                                                sr.customer_phone = formatted_phone
                                        else:
                                            logging.error(
                                                "Cannot process square customer id: [{}]"
                                                .format(customer_id))
                                            process_order = False
                                    except Exception as e:
                                        logging.error(
                                            "Error processing square customer id: [{}], msg: {}"
                                            .format(customer_id, e.message))
                                        process_order = False
                                    if order['fulfillments'][0].get(
                                            'shipment_details'
                                    ) and order['fulfillments'][0][
                                            'shipment_details'].get(
                                                'shipping_note'):
                                        sr.memo = order['fulfillments'][0][
                                            'shipment_details'][
                                                'shipping_note']

                                else:  # otherwise get the customer from the order itself (customer not registered)
                                    #logging.info(
                                    #    "Skipping Square (non-registered customer): order id:[{}], createdOn: [{}]".format(order['id'], order['created_at']))
                                    #process_order = False

                                    #NOTE: This is triggering from square. But the order coming in was denied. But the order looks normal. Maybe we need to look at
                                    #receipts in square first, then walk back to the order.
                                    logging.debug("getting from fulfillments")

                                    payment_id = order['tenders'][0]['id']
                                    try:
                                        payments_api = client.payments
                                        payment_raw = payments_api.get_payment(
                                            payment_id)
                                        if payment_raw.is_success():
                                            payment = payment_raw.body[
                                                'payment']
                                            logging.debug(
                                                "Payment Raw: {}".format(
                                                    payment))
                                            sr.customer_street = payment[
                                                'shipping_address'][
                                                    'address_line_1']
                                            sr.customer_state = payment[
                                                'shipping_address'][
                                                    'administrative_district_level_1']
                                            sr.customer_city = payment[
                                                'shipping_address']['locality']
                                            sr.customer_zip = payment[
                                                'shipping_address'][
                                                    'postal_code']
                                            sr.customer_email = payment[
                                                'buyer_email_address']
                                        else:
                                            logging.error(
                                                "Cannot find square payment for payment_id: [{}]"
                                                .format(payment_id))
                                            process_order = False
                                    except Exception as e:
                                        logging.error(
                                            "Error finding square payment for payment_id: [{}], msg:[{}]"
                                            .format(payment_id, e.message))
                                        process_order = False

                                    if order['fulfillments'] and len(
                                            order['fulfillments']) > 0:
                                        if order['fulfillments'][0].get(
                                                'shipment_details'
                                        ) and order['fulfillments'][0][
                                                'shipment_details'].get(
                                                    'recipient'):
                                            sr.customer_name = order[
                                                'fulfillments'][0][
                                                    'shipment_details'][
                                                        'recipient'][
                                                            'display_name']
                                            sr.customer_last = sr.customer_name.split(
                                                ' ')[-1].capitalize()
                                            sr.customer_first = sr.customer_name.split(
                                                ' ')[0].capitalize()

                                    if sr.customer_name is None:
                                        logging.info(
                                            "Skipping Square (non-registered customer): order id:[{}], createdOn: [{}]. Could not find customer name in the order."
                                            .format(order['id'],
                                                    order['created_at']))
                                        process_order = False

                                        # sr.customer_street = order['fulfillments'][0]['shipment_details']['recipient']['address'][
                                #     'address_line_1']
                                # sr.customer_city = order['fulfillments'][0]['shipment_details']['recipient']['address'][
                                #     'locality']
                                # sr.customer_state = order['fulfillments'][0]['shipment_details']['recipient']['address'][
                                #     'administrative_district_level_1']
                                # sr.customer_zip = order['fulfillments'][0]['shipment_details']['recipient']['address'][
                                #     'postal_code']
                                # sr.customer_email = order['fulfillments'][0]['shipment_details']['recipient']['email_address']
                                # if order['fulfillments'][0]['shipment_details']['recipient'].get('phone_number', None) is not None:
                                #    formatted_order_phone = phonenumbers.format_number(
                                #        phonenumbers.parse(order['fulfillments'][0]['shipment_details']['recipient']['phone_number'], "US"),
                                #        phonenumbers.PhoneNumberFormat.NATIONAL)
                                #   sr.customer_phone = formatted_order_phone
                                #sr.memo = order['fulfillments'][0]['shipment_details'].get('shipping_note', None)

                                #print("matched: {}".format(item0))
                                # item_name = item['name'].lower()
                                # item_quantity = int(item['quantity'])
                                # item_variation = item['variation_name']

                                #now we have a clean line item for mulch. Build the object out for importing into quickbooks
                                if process_order:
                                    sr = extract_item(sr, item_quantity,
                                                      item_name,
                                                      item_variation)
                                    sr.date = order['created_at']
                                    sr.product_price = square_money_to_decimal(
                                        item['base_price_money']['amount'])
                                    sr.total_price = square_money_to_decimal(
                                        item['total_money']['amount'])
                                    sr.deposit_account_ref = default_deposit_account_ref
                                    sr.payment_method_ref = default_pament_method_ref
                                    create_order(sr)
                                    logging.debug(sr)
                                else:
                                    logging.error(
                                        "Cannot process Order for orderid [{}]. Either the customer or the payment cannot be found in square...skipping"
                                        .format(order['id']))
    else:
        logging.info(
            "There are no orders to process for the time range: {} to {}".
            format(PROCESSING_START_DATETIME, PROCESSING_END_DATETIME))
Ejemplo n.º 17
0
import os
from square.client import Client

client = Client(
    access_token=os.getenv("ACCESS_TOKEN"),
    environment='sandbox',
)

result = api_locations.list_locations()
# Call the success method to see if the call succeeded
if result.is_success():
    # The body property is a list of locations
    locations = result.body['locations']
    # Iterate over the list
    for location in locations:
        # Each location is represented as a dictionary
        for key, value in location.items():
            print(f"{key} : {value}")
        print("\n")
# Call the error method to see if the call failed
elif result.is_error():
    print('Error calling LocationsApi.listlocations')
    errors = result.errors
    # An error is returned as a list of errors
    for error in errors:
        # Each error is represented as a dictionary
        for key, value in error.items():
            print(f"{key} : {value}")
        print("\n")
Ejemplo n.º 18
0
from square.client import Client
client = Client(access_token='保密')
file_to_upload_path = "D:\\180.jpg"  # Modify this to point to your desired file.
f_stream = open(file_to_upload_path, "rb")

result = client.catalog.create_catalog_image(request={
    "idempotency_key": "1743bfa0-cc55-41ac-9895-8def9618f0f5",
    "object_id": "ZFVW6BVHWKQIWFRW5C6UPJH2",
    "image": {
        "type": "IMAGE",
        "id": "#12345",
        "image_data": {
            "name": "chocolatePic"
        }
    }
},
                                             file=f_stream)

if result.is_success():
    print(result.body)
elif result.is_error():
    print(result.errors)
Ejemplo n.º 19
0
# 3. Square sends a request to your application's Redirect URL
#    (which should be set to http://localhost:8080/callback 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.

from flask import Flask, request, render_template
from square.client import Client
from dotenv import load_dotenv
import os

load_dotenv()  # take environment variables from .env.

environment = os.getenv('SQ_ENVIRONMENT').lower()
client = Client(environment=environment)
obtain_token = client.o_auth.obtain_token

app = Flask(__name__)

# Your application's ID and secret, available from your application dashboard.
application_id = os.getenv('SQ_APPLICATION_ID')
application_secret = os.getenv('SQ_APPLICATION_SECRET')

base_url = "https://connect.squareup.com" if environment == "production" else "https://connect.squareupsandbox.com"


# Serves the link that merchants click to authorize your application
@app.route('/', methods=['GET'])
def authorize():
    url = "{0}/oauth2/authorize?client_id={1}".format(base_url, application_id)
Ejemplo n.º 20
0
config = configparser.ConfigParser()
config.read("config.ini")

# Retrieve credentials based on is_prod
CONFIG_TYPE = config.get("DEFAULT", "environment").upper()
PAYMENT_FORM_URL = (
    "https://web.squarecdn.com/v1/square.js"
    if CONFIG_TYPE == "PRODUCTION"
    else "https://sandbox.web.squarecdn.com/v1/square.js"
)
APPLICATION_ID = config.get(CONFIG_TYPE, "square_application_id")
LOCATION_ID = config.get(CONFIG_TYPE, "square_location_id")
ACCESS_TOKEN = config.get(CONFIG_TYPE, "square_access_token")

client = Client(
    access_token=ACCESS_TOKEN,
    environment=config.get("DEFAULT", "environment"),
)

location = client.locations.retrieve_location(location_id=LOCATION_ID).body["location"]
ACCOUNT_CURRENCY = location["currency"]
ACCOUNT_COUNTRY = location["country"]


def generate_index_html():
    html_content = (
        """<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Make Payment</title>
Ejemplo n.º 21
0
def process_payment(request, **kwargs):
    '''Processes the payment and returns an error or success page.'''

    context = None  #Initialize context
    template_name = 'sq-payment-result.html'
    cart_model = Cart
    program_model = Program
    # open_hockey_sessions_model = OpenHockeySessions
    # open_hockey_member_model = OpenHockeyMember
    stick_and_puck_sessions_model = StickAndPuckSession
    # thane_storck_sessions_model = SkateSession
    figure_skating_sessions_model = FigureSkatingSession
    adult_skills_sessions_model = AdultSkillsSkateSession
    # mike_schultz_sessions_model = MikeSchultzSkateSession
    yeti_sessions_model = YetiSkateSession
    womens_hockey_sessions_model = WomensHockeySkateSession
    bald_eagles_sessions_model = BaldEaglesSession
    lady_hawks_sessions_model = LadyHawksSkateSession
    # chs_alumni_sessions_model = CHSAlumniSession
    private_skate_sessions_model = PrivateSkateSession
    open_roller_sessions_model = OpenRollerSkateSession
    owhl_sessions_model = OWHLSkateSession
    kranich_sessions_model = KranichSkateSession
    nacho_skate_sessions_model = NachoSkateSession
    ament_sessions_model = AmentSkateSession
    user_credit_model = UserCredit
    today = date.today()

    if request.method == 'GET':
        return redirect('cart:shopping-cart')
    else:

        token = request.POST['payment-token']
        # print(f"Token: {token}")
        access_token = os.getenv('SQUARE_API_ACCESS_TOKEN'
                                 )  # uncomment in production and development
        cart_items = cart_model.objects.filter(
            customer=request.user).values_list('item', 'amount')
        total = 0
        programs = program_model.objects.all().values_list('program_name',
                                                           flat=True)
        note = {program: 0 for program in programs}
        private_skates = PrivateSkate.objects.all().values_list('name',
                                                                flat=True)
        for skate in private_skates:
            note[skate] = 0
        note['User Credits'] = 0

        for item, amount in cart_items:
            total += amount
            # if item == 'OH Membership':
            #     note['Open Hockey'] += amount
            # else:
            note[item] += amount
        total *= 100  #convert to pennies for square

        client = Client(
            access_token=access_token,
            # environment='sandbox', # Uncomment on local machine
            environment=os.getenv('SQUARE_API_ENVIRONMENT'
                                  ),  # Uncomment in production and development
        )

        location_id = os.getenv(
            "SQUARE_LOCATION_ID")  # uncomment in production and development
        location = client.locations.retrieve_location(
            location_id=location_id).body['location']
        currency = location['currency']

        # Assemble the body for the create_payment() api function
        idempotency_key = str(uuid.uuid1())
        amount = {'amount': total, 'currency': currency}

        # Create the note depending on what the user is paying for....
        payment_note = ''
        for k, v in note.items():
            if v != 0:
                payment_note += f'({k} ${v}) '

        body = {
            'idempotency_key': idempotency_key,
            'source_id': token,
            'amount_money': amount,
            'autocomplete': True,
            'note': payment_note
        }

        # Send info to square api and react to the response
        api_response = client.payments.create_payment(body)

        if api_response.is_success():
            res = api_response.body['payment']
            # Add payment record to Payment Model
            model = models.Payment
            payer = request.user
            square_id = res['id']
            square_receipt = res['receipt_number']
            amount = float(res['amount_money']['amount']) / 100
            note = res['note']
            payment_record = model(payer=payer,
                                   square_id=square_id,
                                   square_receipt=square_receipt,
                                   amount=amount,
                                   note=note)
            payment_record.save()

            # Update model(s) to mark items as paid.
            try:
                # open_hockey_sessions_model.objects.filter(skater=request.user, date__gte=today).update(paid=True)
                stick_and_puck_sessions_model.objects.filter(
                    guardian=request.user, session_date__gte=today,
                    paid=False).update(paid=True)
                # open_hockey_member_model.objects.filter(member=request.user).update(active=True)
                # thane_storck_sessions_model.objects.filter(skater=request.user).update(paid=True)
                figure_skating_sessions_model.objects.filter(
                    guardian=request.user,
                    session__skate_date__gte=today,
                    paid=False).update(paid=True)
                adult_skills_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
                # mike_schultz_sessions_model.objects.filter(user=request.user).update(paid=True)
                yeti_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
                womens_hockey_sessions_model.objects.filter(
                    user=request.user, paid=False).update(paid=True)
                bald_eagles_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
                lady_hawks_sessions_model.objects.filter(
                    user=request.user, paid=False).update(paid=True)
                # chs_alumni_sessions_model.objects.filter(skater=request.user).update(paid=True)
                open_roller_sessions_model.objects.filter(
                    user=request.user).update(paid=True)
                private_skate_sessions_model.objects.filter(
                    user=request.user, paid=False).update(paid=True)
                owhl_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
                kranich_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
                nacho_skate_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
                ament_sessions_model.objects.filter(
                    skater=request.user, paid=False).update(paid=True)
            except IntegrityError:
                pass

            try:
                user_credit = user_credit_model.objects.get(
                    user=request.user)  # Get user credit model instance
                if user_credit.pending > 0:  # If there are pending credits
                    user_credit.balance += user_credit.pending  # Add pending credits to credit balance
                    user_credit.pending = 0  # Set pending credits to 0
                    user_credit.paid = True  # Mark credits as paid
                    user_credit.save()  # Save user credit model
            except ObjectDoesNotExist:
                pass

            # Clear items from the Cart Model if the payment was successful
            Cart.objects.filter(customer=request.user).delete()

            # Construct context for result page.
            context = {'message': True, 'amount': amount, 'note': note}
        elif api_response.is_error():
            # Save the error in PaymentError model for debugging.
            model = models.PaymentError
            payer = request.user
            payment_error = model(payer=payer, error=api_response.errors)
            payment_error.save()

            # Create response context and send to template for display.
            error_message = api_response.errors[0]['detail']
            error_messages = {
                "Authorization error: 'ADDRESS_VERIFICATION_FAILURE'":
                "The zip code you entered was incorrect.",
                "Authorization error: 'CVV_FAILURE'":
                "The three digit security code you entered was incorrect.",
                "Authorization error: 'GENERIC_DECLINE'":
                "The credit card number you entered has been declined.",
            }
            error = error_messages.get(
                error_message, error_message
            )  # Retrieve error msg, else return raw error_message
            context = {'error': True, 'error_message': error}

        return render(request, template_name, context)