示例#1
0
    def connect(self):
        """Create the client and necessary mini-apis if access_token is set."""

        self.client = Client(access_token=self.settings["access_token"],
                             environment="production")
        self.orders_api = self.client.orders
        self.locations_api = self.client.locations
示例#2
0
    def refresh_access_token(self, check_expiration=True):
        """Refreshes the app's access token to the square account.

        Args:
            check_experiation (bool): If True, only refreshes if the expiration
                is more than 15 days away. If False, refresh the access token.
        """
        # if check_expiration - only refresh if token will expire in less than 15 days.
        if check_expiration:
            expiration = dateutil.parser.parse(
                self.settings["access_token_expiration"])
            time_since = datetime.now(timezone.utc) - expiration
            # just exit if expiration is more than 15 days away.
            if time_since.days < 15:
                return

        client = Client()
        o_auth_api = client.o_auth
        body = {
            "client_id": self.settings["client_id"],
            "client_secret": self.settings["client_secret"],
            "grant_type": "refresh_token",
            "refresh_token": self.settings["refresh_token"],
        }
        result = o_auth_api.obtain_token(body)

        # Save the new token and update the expiration
        self.settings["access_token"] = result.body["access_token"]
        self.settings["access_token_expiration"] = result.body["expires_at"]
        self.filehandler.dict_to_file(self.settings, self.settings_path)
        return result.body
示例#3
0
def charge(request):

    # 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',
    )
    nonce = request.POST['nonce']
    #print(nonce)

    idempotency_key = str(uuid.uuid1())

    amount = {'amount': 100, 'currency': 'CAD'}

    body = {
        'idempotency_key': idempotency_key,
        'source_id': nonce,
        'amount_money': amount
    }

    api_response = client.payments.create_payment(body)
    if api_response.is_success():
        res = api_response.body['payment']
        return JsonResponse({"success": "true", "message": "OK"})

    elif api_response.is_error():
        res = "Exception when calling PaymentsApi->create_payment: {}".format(
            api_response.errors)
        return JsonResponse({"success": "false", "message": res})
示例#4
0
    def square_si_s2s_do_transaction(self, **data):
        self.ensure_one()
        if not self.payment_token_id.acquirer_ref:
            raise UserError(
                _('Invalid token found: the Square noun is missing.'
                  'Please make sure the token has a valid acquirer reference.')
            )

        body = {
            "idempotency_key": self.get_uniq_string(),
            "source_id": self.payment_token_id.acquirer_ref,
            "amount_money": {
                'amount': int(round(self.amount * 100, 2)),
                'currency': self.currency_id.name or "USD",
            },
            "autocomplete": True,
            "reference_id": self.reference,
        }
        acquirer = self.acquirer_id
        environment = 'sandbox' if acquirer.state == 'test' else 'production'
        client = Client(
            access_token=self.acquirer_id.sq_access_token,
            environment=environment,
        )

        result = client.payments.create_payment(body)

        if result.is_success():
            return self._square_si_s2s_validate_tree(result.body)
        elif result.is_error():
            return self._square_si_s2s_validate_tree(result.errors, True)

        return self._square_si_s2s_validate_tree(result.body)
def process_payment(request):
    data = json.loads(request.body)
    amountDue = data['amountDue']
    nonce = data['nonce']

    config_type = "SANDBOX"
    access_token = "EAAAELuuq-CJ1qho_UBpAJrWMlFmA0hTS3s4dKCJOeQa6WmZLsO7PTm-1K-HiGlc"

    client = Client(
        access_token=access_token,
        environment="sandbox",
    )

    idempotency_key = str(uuid.uuid1())

    amount = {'amount': amountDue, 'currency': 'USD'}

    body = {
        'idempotency_key': idempotency_key,
        'source_id': nonce,
        'amount_money': amount
    }

    api_response = client.payments.create_payment(body)
    if api_response.is_success():
        res = api_response.body['payment']
    elif api_response.is_error():
        res = "Exception when calling PaymentsApi->create_payment: {}".format(
            api_response.errors)

    return JsonResponse('Item was added', safe=False)
示例#6
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        items_cost = self.cart_model.objects.filter(
            customer=self.request.user).values_list('amount', flat=True)
        total = 0
        for item_cost in items_cost:
            total += item_cost
        context['total'] = total
        context['app_id'] = os.getenv(
            "SQUARE_APP_ID")  # uncomment in production and development
        context['loc_id'] = os.getenv(
            "SQUARE_LOCATION_ID")  # uncomment in production and development
        access_token = os.getenv('SQUARE_API_ACCESS_TOKEN'
                                 )  # uncomment in production and development

        client = Client(
            access_token=access_token,
            environment=os.getenv('SQUARE_API_ENVIRONMENT'
                                  ),  # Uncomment in production and development
        )
        location = client.locations.retrieve_location(
            location_id=context['loc_id']).body['location']
        context['currency'] = location['currency']
        context['country'] = location['country']
        return context
示例#7
0
    def post(self, request, format=None):

        try:
            user = request.user
            client = Client(
                access_token=settings.SQUAREUP_TOKEN,
                environment=settings.SQUAREUP_ENV,
            )

            req = json.loads(request.body.decode('utf8'))

            amount = float(req.get('amount'))
            total_cents = int(float(req.get('total')) * 100)
            payment = {
                'source_id': req.get('nonce'),
                'idempotency_key': req.get('key'),
                'amount_money': {
                    'amount': total_cents,
                    'currency': 'USD'
                },
            }

            result = client.payments.create_payment(payment)

            if result.is_success():
                pmt = {
                    'date':
                    datetime.now(
                        timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
                    'amount':
                    amount
                }
                user.payments.append(pmt)
                user.save()

                try:
                    subject = 'Card Payment Received.'
                    t = float(req.get('total'))
                    a = float(req.get('amount'))
                    ct = "${:,.2f}".format(t)
                    ca = "${:,.2f}".format(a)
                    message = f'Thank you for your payment of {ct}!<br/>{ca} has been applied to your account.'
                    from_email = 'PilotAndy Aviation <*****@*****.**>'
                    msg = EmailMessage(subject,
                                       message,
                                       from_email, [str(user)],
                                       bcc=['*****@*****.**'])
                    msg.content_subtype = "html"  # Main content is now text/html
                    msg.send()
                except:
                    print(traceback.format_exc())

                return Response('Payment accepted. Thank you!')
            elif result.is_error():
                return Response(result.errors,
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Exception as exc:
            return Response(str(exc),
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
示例#8
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.APIClient = Client(
         access_token=
         "EAAAEDZZRU_aZnhAtZf4AtvDFIBHhLXsqN3kGBSq5eBKIyhPT4foUN93H8NaDQ5T",
         environment="sandbox")
     self.locationID = "MA9MJNAKD1WDG"
     self.signatureKey = ""
     self.changeQueue = list()
     self.lastInventoryRequest = datetime.datetime.utcnow()
    def get_customer(self):
        load_dotenv()

        square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                               environment="sandbox")

        customers_api = square_client.customers
        result = customers_api.retrieve_customer(self.customer_id)

        self.body = result.body["customer"]
示例#10
0
def check_access_token_status(merchant_id):
    '''The endpoint that check access token status of a merchant.

  The OAuth access token expires or is revoked due to unforeseen reasons, you need always show the correct status
  of the merchant's access token, so that the merchant can recover the access with your app whenever the access token
  becomes invalid.

  Path Parameters
  ----------------
  merchant_id : str
    The ID of the merchant whose access token you want to check. 
  '''
    # get the access_token from db
    oauth_record = get_oauth_record(merchant_id)
    if not oauth_record:
        body = '''
      <h1>merchant {0} not found.</h1>
    '''.format(merchant_id)
    else:
        access_token = fernet.decrypt(
            oauth_record['AccessToken']['B']).decode('ASCII')
        # call the list_locations to check the access token status
        # you can use other endpoint to check the access token status within the api permission scope
        square_client_with_auth = Client(environment=os.environ['environment'],
                                         access_token=access_token)
        api_payments = square_client_with_auth.payments
        response = api_payments.list_payments(begin_time=datetime.utcnow(
        ).strftime('%Y-%m-%dT%H:%M:%SZ'
                   )  # use now as begin_time to reduce the payload
                                              )
        if response.is_success():
            # successful api call indicates access token is valid
            body = '''
        <h1>Access token is valid for merchant {0}.</h1>
      '''.format(merchant_id)
        elif response.is_error():
            # get the error code from the response
            error_code = response.errors[0]['code']
            if error_code in [
                    'UNAUTHORIZED', 'ACCESS_TOKEN_EXPIRED',
                    'ACCESS_TOKEN_REVOKED', 'INSUFFICIENT_SCOPES'
            ]:
                # the error code indicates the access token is invalid
                body = '''
          <h1>Access token is invalid for merchant {0}.</h1>
        '''.format(merchant_id)
            else:
                # non-auth related error, the status becomes unknown
                # you may want to retry in case it's an transient issue
                body = '''
          <h1>Access token staus is unknown for merchant {0}.</h1>
        '''.format(merchant_id)
    return Response(body=html_template.format(body),
                    status_code=200,
                    headers={"Content-Type": "text/html"})
示例#11
0
    def __init__(self, config):
        self._refresh_token = config['refresh_token']
        self._client_id = config['client_id']
        self._client_secret = config['client_secret']

        self._environment = 'sandbox' if config.get(
            'sandbox') == 'true' else 'production'

        self._access_token = self._get_access_token()
        self._client = Client(access_token=self._access_token,
                              environment=self._environment)
示例#12
0
 def __init__(
     self,
     access_token=__ACCESS_TOKEN,
     production: bool = False,
 ):
     access_token = access_token if valid_str(
         access_token) else self.__ACCESS_TOKEN
     self.client = Client(
         access_token=access_token,
         environment='production' if production else 'sandbox',
     )
def getCards():
    load_dotenv()

    square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                           environment="sandbox")

    customers_api = square_client.customers
    # id for UwU OwO
    result = customers_api.retrieve_customer("J9XYVXV5Z4SZ77PT2NRN72XFQC")

    cards = result.body["customer"]["cards"]
    return json.dumps(cards, default=str), 200
示例#14
0
    def add_to_square(self):
        load_dotenv()

        square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                               environment="sandbox")
        catalog_api = square_client.catalog
        result = catalog_api.upsert_catalog_object(self.body)

        if result.is_success():
            print(result.body)
        elif result.is_error():
            print(result.errors)
def removeCard():
    load_dotenv()

    square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                           environment="sandbox")

    customers_api = square_client.customers
    customer_id = "J9XYVXV5Z4SZ77PT2NRN72XFQC"
    card_id = "ccof:8ywRmjQ3OeRVtRjT3GB"
    result = customers_api.delete_customer_card(customer_id, card_id)

    return {'success': 'card successfully removed'}, 200
示例#16
0
    def add_to_square(self):
        load_dotenv()

        square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                               environment="sandbox")
        orders_api = square_client.orders

        result = orders_api.create_order(self.location_id, self.body)

        if result.is_success():
            print(result.body)
        elif result.is_error():
            print(result.errors)
示例#17
0
    def create_payment_dict(self):
        load_dotenv()
        client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                        environment="sandbox")

        payments_api = client.payments
        result = payments_api.create_payment(self.body)

        if result.is_success():
            print(result.body)
            self.result = result.body
        elif result.is_error():
            raise ValueError("payment failed")
    def update_db(self):
        load_dotenv()
        mongo_client = pymongo.MongoClient(os.getenv("MONGO_NORM_USER"))
        db = mongo_client["customer"]["customers"]

        square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                               environment="sandbox")

        customers_api = square_client.customers
        result = customers_api.retrieve_customer(self.customer_id)

        mongo_data = list(db.find({"id": self.customer_id}))
        db.replace_one({"_id": mongo_data[0]["_id"]}, result.body["customer"])
示例#19
0
 def square_client(self):
     """ Method is used for create square client. """
     self.ensure_one()
     client = False
     if self.sudo().square_access_token and self.sudo(
     ).square_access_token == 'dummy':
         raise ValidationError(_("Please configure square account."))
     if self.sudo().square_access_token:
         client = Client(
             access_token=self.sudo().square_access_token,
             environment='sandbox'
             if self.state == 'test' else 'production',
         )
     return client
示例#20
0
    def create_customer_dict(self):
        load_dotenv()
        square_client = Client(
            access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
            environment="sandbox"
        )
        customers_api = square_client.customers
        result = customers_api.create_customer(self.body)

        if result.is_success():
            #print(result.body)
            self.result = result.body
            self.customer_id = self.result["customer"]["id"]
        elif result.is_error():
            print(result.errors)
    def __init__(self, cfg):
        # Get config settings
        self.cfg = cfg.get_square()
        self.site = cfg.get_site()['site']
        self.costs = cfg.get_costs()

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

        self.client = Client(
            access_token=self.cfg["access_token"],
            environment=self.cfg["environment"],
        )
        self.checkout_api = self.client.checkout
    def add_card_to_square(self):
        load_dotenv()

        square_client = Client(access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
                               environment="sandbox")

        customers_api = square_client.customers

        res = customers_api.create_customer_card(self.customer_id,
                                                 self.card_dict)

        if res.is_success():
            print(res.body)
            self.card_result = res.body
        elif res.is_error():
            print(res.errors)
示例#23
0
    def _get_access_token(self):
        body = {
            'client_id': self._client_id,
            'client_secret': self._client_secret,
            'grant_type': 'refresh_token',
            'refresh_token': self._refresh_token
        }

        client = Client(environment=self._environment)

        with singer.http_request_timer('GET access token'):
            result = client.o_auth.obtain_token(body)

        if result.is_error():
            error_message = result.errors if result.errors else result.body
            raise RuntimeError(error_message)

        return result.body['access_token']
示例#24
0
    def get_access_token(self, code=None):
        """Gets the access token from the authorization code.

        Accepts either the full url after redirect, or just the authorization code provided.
        Then gets the access token from Square. This is the second step in the Oath2 flow.

        Args:
            code (str): Either the full url, or the just the code. So either
                "www.google.com?code=123abc" or "123abc".

        Returns:
            result (Square Obtain Token Response Object):
                (https://github.com/square/square-python-sdk/blob/master/doc/models/obtain-token-response.md)
        """
        # Get the access token (initial step using the authorization code)
        client = Client()
        o_auth_api = client.o_auth

        if "?" in code:
            # if '?' present, assume the whole url was included, including the query string
            # and parse to get the code.
            psd = urlparse(code)
            query_dict = parse_qs(psd.query)
            code = query_dict["code"][0]
            # else, assume the code is the only thing included.

        body = {
            "client_id": self.settings["client_id"],
            "client_secret": self.settings["client_secret"],
            "code": code,
            "grant_type": "authorization_code",
        }
        result = o_auth_api.obtain_token(body)
        if result.is_success():
            self.settings["access_token"] = result.body["access_token"]
            self.settings["access_token_expiration"] = result.body[
                "expires_at"]
            self.settings["refresh_token"] = result.body["refresh_token"]
            self.filehandler.dict_to_file(self.settings, self.settings_path)
            self.connect()
        else:
            print(result.errors)
        return result
def payment(request):
    if request.method == 'POST':
        client = Client(
            access_token=
            'EAAAEBltDePV9iY0DTDR0lbwFKz3yWo53rQYb2j_F_xJCdg-rpu6amh-noG_sSaC',
            environment='sandbox',
        )
        payments_api = client.payments
        body = {}
        body['source_id'] = request.POST['nonce']
        body['idempotency_key'] = str(uuid.uuid1())
        body['amount_money'] = {}
        body['amount_money']['amount'] = 200
        body['amount_money']['currency'] = 'USD'

        result = payments_api.create_payment(body)
        if result.is_success():
            print('--------------------', result.body)
        elif result.is_error():
            print('+++++++++++++++++++', result.errors)
    return render(request, 'payment_demo/payment.html')
示例#26
0
 def get_square_data(self):
     self.api_instance = Client(access_token=self.zoho_token['SQUARE_KEY'])
     self.body = {
         'location_ids': [self.vans[self.van]],
         'query': {
             'filter': {
                 'date_time_filter': {
                     'created_at': {
                         'start_at':
                         dt.datetime.today().strftime('%Y-%m-%d'),
                         'end_at':
                         (dt.datetime.today() +
                          dt.timedelta(days=1)).strftime('%Y-%m-%d')
                     }
                 }
             }
         },
         'return_entries': False,
     }
     self.api_response = self.api_instance.orders.search_orders(self.body)
     return json.loads(self.api_response.text)
示例#27
0
    def add_to_db(self):
        load_dotenv()

        square_client = Client(
            access_token=os.getenv("SQUARE_ACCESS_TOKEN"),
            environment="sandbox"
        )

        customers_api = square_client.customers
        result = customers_api.retrieve_customer(self.customer_id)

        if result.is_error():
            raise ValueError("Cannot get customer")

        data = result.body
        #print(json.dumps(data, indent=4))

        mongo_client = pymongo.MongoClient(os.getenv("MONGO_NORM_USER"))
        db = mongo_client["customer"]["customers"]
        db2 = mongo_client["business"]["2020-06-29"]
        mongo_data = list(db2.find({}))
        data["customer"]["saved_business"] = random.sample(mongo_data, 5)
        db.insert_one(data["customer"])
示例#28
0
def payment(request):

    client = Client(
        access_token='SANDBOX_ACCESS_TOKEN',
        environment='sandbox',
    )
    request_body = json.loads(request.body)

    payments_api = client.payments
    idempotency_key = secrets.token_hex(22)

    body = {}
    body['source_id'] = request_body['nonce']
    body['idempotency_key'] = idempotency_key
    body['amount_money'] = {}
    body['amount_money']['amount'] = 100
    body['amount_money']['currency'] = 'USD'

    result = payments_api.create_payment(body)
    error = {}
    if result.is_success():
        return JsonResponse(result.body)
    elif result.is_error():
        return JsonResponse(result.body)
示例#29
0
 def post(self,request,*args, **kwargs):
     client = Client(
         access_token=settings.SQUARE_ACCESS_TOKEN,
         environment='sandbox',
     )
     cart = request.data
     checkout_api = client.checkout
     locationID = settings.SQUARE_LOCATION_ID
     body = {}
     body['idempotency_key'] = str(uuid.uuid1())
     body['order'] = {}
     body['order']['order'] = {}
     body['order']['order']['location_id'] = locationID
     body['ask_for_shipping_address'] = True
     body['order']['order']['reference_id'] = 'reference_id'
     body['order']['order']['customer_id'] = 'customer_id'
     body['order']['order']['line_items'] = []
     for num,item in enumerate(cart): 
         body['order']['order']['line_items'].append({})
         body['order']['order']['line_items'][num]['name'] = item['item'] + ' Size:' + item['size']
         body['order']['order']['line_items'][num]['quantity'] = item['quantity']
         body['order']['order']['line_items'][num]['note'] = item['size']
         body['order']['order']['line_items'][num]['base_price_money'] = {}
         body['order']['order']['line_items'][num]['base_price_money']['amount'] = int(float(item['price'])*100)
         body['order']['order']['line_items'][num]['base_price_money']['currency'] = 'USD'
     result = checkout_api.create_checkout(locationID, body)
     if result.is_success():
         return Response({
             "status":"success",
             "payload":result.body
         })
     else:
         return Response({
             "status":"error",
             "error_message":result.errors
         })
示例#30
0
def pull_invoice():  #reset it to the last 5 sales
    client = Client(access_token=dev_pr_secret, )
    result = client.orders.batch_retrieve_orders(
        location_id=test_id,
        body={
            client.orders.search_orders(
                body={
                    'location_ids': test_id,
                    "query": {
                        "filter": {
                            "date_time_filter": {
                                "created_at": {
                                    "start_at": [(dt.datetime.today() -
                                                  dt.timedelta(days=1)),
                                                 dt.datetime.today()],
                                    # "end_at": dt.datetime.today()
                                }
                            }
                        }
                    }
                })
        })
    df = pd.DataFrame(result.body)
    return df.head(5)