|
| 1 | +# Example OAuth workflow |
| 2 | + |
| 3 | +The Shopify Python API [validates HMAC and timing attacks](https://shopify.dev/apps/auth/oauth/getting-started#step-2-verify-the-installation-request) with the `request_token` function. Below is a basic example OAuth workflow for a FastAPI app. |
| 4 | + |
| 5 | + |
| 6 | +## Setup |
| 7 | + |
| 8 | +1. Create a new application in the Partners Dashboard, and retrieve your API key and API secret. |
| 9 | + |
| 10 | +2. Configure your app URL and Admin API version. Initialize your `shopify.Session` class with your API key and API secret for authentication. |
| 11 | + |
| 12 | +```python |
| 13 | +import shopify |
| 14 | + |
| 15 | +VERSION = "2022-07" |
| 16 | +HOST = "https://app-url" |
| 17 | + |
| 18 | +API_KEY = "api-key" |
| 19 | +API_SECRET = "api-secret" |
| 20 | + |
| 21 | +shopify.Session.setup(api_key=API_KEY, secret=API_SECRET) |
| 22 | +``` |
| 23 | + |
| 24 | +3. Request permissions from the merchant with the `auth_url` from the `create_permission_url` function. Once the merchant acccepts, a temporary token `code` is sent to the specified `redirect_uri` of your app. |
| 25 | + |
| 26 | +```python |
| 27 | +from fastapi import FastAPI, Request |
| 28 | +from fastapi.responses import RedirectResponse |
| 29 | + |
| 30 | +@app.get("/", response_class=RedirectResponse) |
| 31 | +async def install(shop_name: str): |
| 32 | + shop_url = f"{shop_name}.myshopify.com" |
| 33 | + state = binascii.b2a_hex(os.urandom(15)).decode("utf-8") |
| 34 | + redirect_uri = f"{HOST}/auth/shopify/callback" |
| 35 | + scopes = ['read_products'] |
| 36 | + |
| 37 | + new_session = shopify.Session(shop_url, VERSION) |
| 38 | + auth_url = new_session.create_permission_url(scopes, redirect_uri, state) |
| 39 | + return RedirectResponse( |
| 40 | + url=auth_url, |
| 41 | + status_code=303 |
| 42 | + ) |
| 43 | +``` |
| 44 | + |
| 45 | +4. To capture the `code`, set up a callback handler in your app. To exchange the temporary token for a permanent access token, supply the parameters from this request to the `request_token` function. |
| 46 | + |
| 47 | +```python |
| 48 | +@app.get("/auth/shopify/callback") |
| 49 | +async def auth_callback(request: Request): |
| 50 | + request_params = dict(request.query_params) |
| 51 | + shop_url = request_params.get("shop") |
| 52 | + |
| 53 | + session = shopify.Session(shop_url, VERSION) |
| 54 | + access_token = session.request_token(request_params) |
| 55 | + # store access_token |
| 56 | +``` |
| 57 | + |
| 58 | + |
0 commit comments