Product

Thursday, 21 March 2024

AI:python code for experience with the gorgias API, shopify API and google sheets automation. We're looking for a tool that does the following: The tool needs to analyze all tickets in gorgias from our ecommerce store and find out what the reason somebody wants to return(if the ticket is about a return). There could be a couple of options: - Generally didn't like the item - Item doesn't fit (was it too big or was it too small?) - Low quality - Defect (Could be divided into a couple of things: General defect, glue residue, scratches, broken, etc.) - Wrong size (received the wrong size) - Wrong color (received the wrong color) - Wrong product - Item looks different then pictures All of this data would need to be in a google sheet including the order number in shopify, the order date, the ticket number, and the product and size is associated with the data. Any AI that could detect this would be possible, preferably something with low costs because of the volume of tickets we receive.

 To achieve this task, you can use Python along with the Gorgias API, Shopify API, and Google Sheets API. Below is an outline of the Python code that demonstrates how to fetch tickets from Gorgias, extract relevant information, query Shopify for order details, and then populate a Google Sheet with the extracted data:

python
import requests import gspread from oauth2client.service_account import ServiceAccountCredentials import shopify # Define Gorgias API credentials GORGIAS_API_KEY = 'your_gorgias_api_key' GORGIAS_API_SECRET = 'your_gorgias_api_secret' GORGIAS_API_URL = 'https://api.gorgias.com' # Define Shopify credentials SHOPIFY_SHOP_NAME = 'your_shop_name' SHOPIFY_API_KEY = 'your_shopify_api_key' SHOPIFY_PASSWORD = 'your_shopify_password' # Define Google Sheets credentials GOOGLE_SHEETS_CREDS_FILE = 'your_google_sheets_creds_file.json' # Authenticate with Gorgias API def gorgias_auth(): response = requests.post(f'{GORGIAS_API_URL}/oauth/token', data={'grant_type': 'client_credentials', 'client_id': GORGIAS_API_KEY, 'client_secret': GORGIAS_API_SECRET}) return response.json()['access_token'] # Fetch tickets from Gorgias def fetch_tickets(access_token): headers = {'Authorization': f'Bearer {access_token}'} response = requests.get(f'{GORGIAS_API_URL}/tickets', headers=headers) return response.json()['data'] # Query Shopify for order details def query_shopify(order_number): shopify.ShopifyResource.set_site(f'https://{SHOPIFY_SHOP_NAME}.myshopify.com/admin') shopify.ShopifyResource.set_user(SHOPIFY_API_KEY) shopify.ShopifyResource.set_password(SHOPIFY_PASSWORD) order = shopify.Order.find(order_number) return order # Write data to Google Sheets def write_to_google_sheets(data): scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_SHEETS_CREDS_FILE, scope) client = gspread.authorize(creds) sheet = client.open('Gorgias Tickets').sheet1 sheet.append_row(data) # Main function def main(): access_token = gorgias_auth() tickets = fetch_tickets(access_token) for ticket in tickets: ticket_number = ticket['number'] order_number = ticket['order']['number'] reason = ticket['reason'] product = ticket['order']['items'][0]['product_title'] size = ticket['order']['items'][0]['size'] # Query Shopify for order details order = query_shopify(order_number) order_date = order.created_at # Write data to Google Sheets data = [order_number, order_date, ticket_number, reason, product, size] write_to_google_sheets(data) if __name__ == '__main__': main()

Please note that you need to replace placeholders like 'your_gorgias_api_key', 'your_shop_name', 'your_shopify_api_key', 'your_shopify_password', and 'your_google_sheets_creds_file.json' with your actual credentials.

Additionally, you may need to install the necessary Python packages using pip:

pip install requests gspread oauth2client shopify

This code outlines the process of fetching tickets from Gorgias, querying Shopify for order details, and writing the extracted data to a Google Sheet. You may need to adjust the code to fit your specific requirements and data structures.

While Python code can be used to achieve this automation, a full solution might involve multiple tools. Here's a breakdown and approach using tools with free tiers for lower costs:

1. Data Extraction and Integration:

  • Gorgias API: You can't directly use Python to access the Gorgias API due to security restrictions. However, Gorgias offers webhooks that can push data to an external URL when a ticket is created or updated. Set up a webhook to send ticket data (including reason for return) to a serverless function (like Google Cloud Functions or AWS Lambda).
  • Shopify API: Use the Shopify Python library (shopify) to access order data (order number, date, product, size) based on the ticket information from Gorgias.

2. Data Analysis and Classification:

Here, Python comes into play:

  • The serverless function triggered by the Gorgias webhook can receive the ticket data and use libraries like nltk or spaCy for basic text processing (tokenization, cleaning).
  • You can define rules or train a machine learning model (using libraries like scikit-learn) to classify the return reason based on keywords or patterns in the ticket description. The classifier can identify categories like "Didn't like the item," "Wrong size/color," "Defect," etc.

3. Google Sheets Integration:

  • Use the Google Sheets API (with libraries like gspread) to write the extracted data (order number, date, ticket number, product, size, return reason) to a Google Sheet.

Cost Considerations:

  • Gorgias webhooks and Shopify API have free tiers with limitations (check their documentation).
  • Google Cloud Functions and AWS Lambda offer free tiers with limitations on execution time and memory.
  • Python libraries mentioned are open-source and free to use.
  • Google Sheets API free tier allows access and modification of a reasonable amount of data.

Alternative (if classification is complex):

  • Consider using a low-cost cloud Natural Language Processing (NLP) API like Google Cloud Natural Language API or Amazon Comprehend to classify return reasons. These might offer better accuracy than rule-based approaches, but they often have pay-per-use costs.

Overall Tool Combination:

  1. Gorgias Webhook -> Serverless Function (Python)
  2. Serverless Function:
    • Fetch order details from Shopify API
    • Process ticket text (using Python libraries)
    • Classify return reason (rule-based or NLP API)
  3. Serverless Function -> Google Sheets API (Python)

Additional Notes:

  • This is a conceptual overview. You'll need to implement the code for each step and configure the APIs accordingly.
  • Consider error handling and edge cases in your Python code.
  • Explore pre-built solutions or connectors between these services (Gorgias, Shopify, Google Sheets) that might exist to simplify the process.
===============================================================

While custom Python code is a solution, pre-built tools can achieve this functionality with less development effort. Here's a breakdown using tools and potential Python code:

Pre-built Tools:

  • Gorgias Automations & Shopify Apps: Gorgias offers built-in automation features and a marketplace with apps that might fulfill your needs. Explore options like:

    • Setting up rules to identify return-related tickets based on keywords or tags.
    • Integrating with a Shopify app that analyzes return reasons and populates a Google Sheet.
  • Zapier: Zapier is a popular automation platform that connects various apps. You can potentially create a Zap to:

    • Trigger on new Gorgias tickets tagged as "Return."
    • Use Shopify's API to get order details (order number, date, product, size) for the ticket's order ID.
    • Extract the return reason from the ticket text using basic string matching or regular expressions (limited AI).
    • Add the extracted data (order details, return reason) to a Google Sheet.

Custom Python Code Approach:

Here's a conceptual outline for Python code (using libraries like gorgias-python, shopify, and googleapiclient):

  1. Gorgias API Integration:

    • Use the gorgias-python library to connect to your Gorgias account and access tickets.
  2. Shopify API Integration:

    • Use the shopify library to connect to your Shopify store and retrieve order details based on order IDs from Gorgias tickets.
  3. Return Reason Classification (Basic - No AI):

    • Use regular expressions or string matching techniques to identify return reasons from the ticket text. This can categorize reasons based on keywords (e.g., "didn't like", "wrong size").
  4. Google Sheets API Integration:

    • Use the googleapiclient library to connect to your Google Sheets and write data (order number, date, ticket number, product, size, return reason).

Cost Considerations:

  • Pre-built tools often have free plans with limitations or paid tiers with expanded functionality. Evaluate pricing based on your ticket volume.
  • Custom Python code requires development and maintenance effort. Consider cloud hosting costs if applicable.

AI for Return Reason Classification:

While implementing basic classification with Python is possible, true AI-powered sentiment analysis might be expensive for high volumes. Consider these options:

  • Explore pre-built AI models offered by cloud platforms like Google Cloud or Amazon Web Services. These might require integrating with your existing solution.
  • Look for third-party services specializing in AI-powered ticket analysis for e-commerce.

Conclusion:

Pre-built tools like Gorgias automations, Zapier, or Shopify apps might offer a quicker and easier solution for your needs. If you require more advanced features or AI-powered classification, consider custom Python development or third-party AI services. Remember to weigh development costs against the benefits of a custom solution.

=================

Here's a solution using Python and the relevant APIs to achieve your requirement. It leverages Google Sheets API and Shopfiy Admin API (not recommended for high-volume data due to throttling limitations) but can be extended to Gorgias API for a more robust solution. It avoids custom AI development for lower costs.

1. Setting Up:

  • Create a Google Sheet to store the return data (order number, order date, ticket number, product, size, return reason).
  • Obtain API keys and credentials for Shopify and Google Sheets API.

2. Python Libraries:

Python
import requests  # For Shopify API requests (alternative for Gorgias API later)
import gspread  # For Google Sheets API interaction

3. Shopify Return Reason Extraction (using Shopify API):

Python
def get_return_reason_shopify(order_id):
  # Replace with your Shopify store base URL and API key
  base_url = "https://your-store.myshopify.com/admin/api/2023-10/orders/" + order_id + ".json"
  headers = {"X-Shopify-Access-Token": "your_shopify_api_key"}

  try:
    response = requests.get(base_url, headers=headers)
    response.raise_for_status()  # Raise error for non-200 status codes
    order_data = response.json()
    # Extract return reason from order data (replace with your logic based on Shopify response structure)
    return_reason = order_data["fulfillments"][0]["return_reason"]  # Placeholder logic, replace as needed
    return return_reason
  except requests.exceptions.RequestException as e:
    print(f"Error getting order data for {order_id}: {e}")
    return None

4. Google Sheets Integration:

Python
def update_google_sheet(data):
  # Initialize Google Sheets API client
  gc = gspread.service_account(filename="your_google_sheet_credentials.json")  # Replace with your credentials file path
  sheet = gc.open_by_key("your_google_sheet_key").sheet1  # Replace with your sheet key

  # Append data as a new row
  sheet.append_row(data)

5. Main Script:

Python
def analyze_gorgias_tickets(gorgias_api_url, sheet):  # Replace with Gorgias API call logic
  # Simulate fetching tickets from Gorgias API (replace with actual Gorgias API call)
  tickets = [
      {"order_id": 12345, "ticket_number": "GOR-123"},
      {"order_id": 67890, "ticket_number": "GOR-456"},
  ]

  for ticket in tickets:
    order_id = ticket["order_id"]
    ticket_number = ticket["ticket_number"]

    # Extract return reason using Shopify API (replace with Gorgias API logic for return reason)
    return_reason = get_return_reason_shopify(str(order_id))
    if return_reason is not None:
      # Extract product and size information from Shopify or Gorgias API (replace with your logic)
      product = "Sample Product"  # Placeholder, replace with actual product data extraction
      size = "M"  # Placeholder, replace with actual size data extraction

      # Update Google Sheet with return data
      data = [order_id, sheet.row_count, ticket_number, product, size, return_reason]
      update_google_sheet(data)

# Replace with your actual Gorgias API endpoint (consider using their Python library)
gorgias_api_url = "https://your-gorgias-api-endpoint"
sheet = None  # Placeholder, initialize your Google Sheet object here

analyze_gorgias_tickets(gorgias_api_url, sheet)

Explanation:

  1. The get_return_reason_shopify function retrieves order data from Shopify using the order ID and extracts the return reason (replace with your logic based on Shopify's API response structure).
  2. The update_google_sheet function uses the gspread library to connect to your Google Sheet and append a new row with the extracted return data.
  3. The main script simulates fetching tickets from Gorgias (replace with actual Gorgias API call logic). It iterates through tickets, extracts the order ID and ticket number.
  4. It calls get_return_reason_shopify

No comments:

Post a Comment

Connect broadband

7 LLM Projects to Boost Your Machine Learning Portfolio

  7 LLM Projects to Boost Your Machine Learning Portfolio Introduction Large Language Models (LLMs) have transformed the landscape of artifi...