Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Python client library for the Square API

License

NotificationsYou must be signed in to change notification settings

square/square-python-sdk

Repository files navigation

fern shieldpypi

The Square Python library provides convenient access to the Square API from Python.

Installation

pip install squareup

Requirements

Use of the Square Python SDK requires:

  • Python 3.8+

Usage

Instantiate and use the client with the following:

fromsquareimportSquareclient=Square(# This is the default and can be omitted.token=os.environ.get("SQUARE_TOKEN"),)client.payments.create(source_id="ccof:GaJGNaZa8x4OgDJn4GB",idempotency_key="7b0f3ec5-086a-4871-8f13-3c81b3875218",amount_money={"amount":1000,"currency":"USD"    },app_fee_money={"amount":10,"currency":"USD"    },autocomplete=True,customer_id="W92WH6P11H4Z77CTET0RNTGFW8",location_id="L88917AVBK2S5",reference_id="123456",note="Brief description")

Async Client

The SDK also exports anasync client so that you can make non-blocking calls to our API.

importasynciofromsquareimportAsyncSquareasyncdefmain()->None:client=AsyncSquare(# This is the default and can be omitted.token=os.environ.get("SQUARE_TOKEN"),    )awaitclient.payments.create(source_id="ccof:GaJGNaZa8x4OgDJn4GB",idempotency_key="7b0f3ec5-086a-4871-8f13-3c81b3875218",amount_money={"amount":1000,"currency":"USD"        },app_fee_money={"amount":10,"currency":"USD"        },autocomplete=True,customer_id="W92WH6P11H4Z77CTET0RNTGFW8",location_id="L88917AVBK2S5",reference_id="123456",note="Brief description"    )asyncio.run(main())

Legacy SDK

While the new SDK has a lot of improvements, we at Square understand that it takes timeto upgrade when there are breaking changes. To make the migration easier, the old SDKis published assquareup_legacy so that the two SDKs can be used side-by-side in thesame project.

Check out theexample for a full demonstration, but the gist isshown below:

fromsquareimportSquarefromsquare_legacy.clientimportClientasLegacySquaredefmain():client=Square(token=os.environ.get("SQUARE_TOKEN"))legacy_client=LegacySquare(access_token=os.environ.get("SQUARE_TOKEN"))    ...

We recommend migrating to the new SDK using the following steps:

  1. Upgrade the PyPi package to ^42.0.0
  2. Runpip install squareup_legacy
  3. Search and replace all requires and imports fromsquare tosquare_legacy
  4. Gradually move over to use the new SDK by importing it from thesquare module

Versioning

By default, the SDK is pinned to the latest version. If you would liketo override this version you can specify it like so:

client=Square(version="2025-03-19")

Automatic Pagination

Paginated requests will return aSyncPager orAsyncPager, which can be usedas generators for the underlying object.

fromsquareimportSquareclient=Square()response=client.payments.list()foriteminresponse:yielditem# Alternatively, you can paginate page-by-page.forpageinresponse.iter_pages():yieldpage

File Uploads

Files are uploaded with theFile type, which is constructed as a tuple ina variety of formats. You can customize the filename andContent-Type of the individualmultipart/form-datapart like so:

invoice_pdf=client.invoices.create_invoice_attachment(invoice_id="inv:0-ChA4-3sU9GPd-uOC3HgvFjMWEL4N",image_file=(os.path.basename(pdf_filepath),# The filename to include in the `multipart/form-data` part.open(pdf_filepath,"rb"),# The file stream, read as binary data."application/pdf"# The Content-Type for this particular file.    ),request={"idempotency_key":str(uuid.uuid4()),"description":f"Invoice-{pdf_filepath}",    })

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass ofthe following error will be thrown.

fromsquare.core.api_errorimportApiErrortry:client.payments.create(...)exceptApiErrorase:print(e.status_code)print(e.body)

Webhook Signature Verification

The SDK provides utility methods that allow you to verify webhook signatures and ensurethat all webhook events originate from Square. Theverify_signature method will verifythe signature.

fromsquare.utils.webhooks_helperimportverify_signatureis_valid=verify_signature(request_body=request_body,signature_header=request.headers['x-square-hmacsha256-signature'],signature_key="YOUR_SIGNATURE_KEY",notification_url="https://example.com/webhook",# The URL where event notifications are sent.)

Advanced

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as longas the request is deemed retriable and the number of retry attempts has not grown larger than the configuredretry limit (default: 2).

A request is deemed retriable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use themax_retries request option to configure this behavior.

fromsquare.core.request_optionsimportRequestOptionsclient.payments.create(    ...,request_options=RequestOptions(max_retries=1    ))

Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

fromsquareimportSquareclient=Square(    ...,timeout=20.0,)# Override timeout for a specific methodclient.payments.create(    ...,request_options=RequestOptions(timeout_in_seconds=20    ))

Custom Client

You can override thehttpx client to customize it for your use-case. Some common use-casesinclude support for proxies and transports.

importhttpxfromsquareimportSquareclient=Square(    ...,httpx_client=httpx.Client(proxies="http://my.test.proxy.example.com",transport=httpx.HTTPTransport(local_address="0.0.0.0"),    ),)

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.Additions made directly to this library would have to be moved over to our generation code,otherwise they would be overwritten upon the next generated release. Feel free to open a PR asa proof of concept, but know that we will not be able to merge it as-is. We suggest openingan issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!


[8]ページ先頭

©2009-2025 Movatter.jp