Ad

How To Setup A Raspberry Pi To Receive Webhooks

- 1 answer

I am currently working on a little project that will have my raspberry pi light up a unicornhat whenever a new order is created on Shopify. I have never worked with webhooks nor web servers, much less Flask or Zappa before, and I was curious as to how I would set this up without exposing the pi to the open internet on my home network.

I had read that this would be simple to do using Amazon's Lambda in conjunction with Flask and something called Zappa, however I am rather lost. This is what I have so far:

from time import sleep
from flask import Flask, request
import unicornhat as unicorn
import light.py

app = Flask(__name__)
@app.route('/', methods = ['POST'])

def index():
    data = request.get_json()
    if data['orders/create'] == null:
        light.light() //lights uHat on new order creation
    return "Success"

Any pointers would be much appreciated, I've been banging my head over this for several weeks (in my spare time) and my inexperience in webdev shows. I'm not even sure if I read Shopify's API information correctly for it to even be listening for the correct webhook.

Thanks again!

Ad

Answer

Shopify has a Python module, shopifyapi that allows you to register your webhook.

import shopify

shop_url = "https://%s:%[email protected]%s.myshopify.com/admin" % (API_KEY, PASSWORD, SHOP_NAME)
shopify.ShopifyResource.set_site(shop_url)
shopify.Session.setup(api_key=API_KEY, secret=SHARED_SECRET)

new_webhook = shopify.Webhook()
new_webhook.address = 'http://your.pi.address'
new_webhook.topic = 'orders/create'
new_webhook.save()

Once that's done any orders created will call the webhook to send order data to your pi's address. For additional events you can use as a trigger see the API docs.

Your Flask app could accept posts like this:

from flask import Flask, request
import light

app = Flask(__name__)

@app.route('/', methods = ['POST'])
def index():
    data = request.json  # optional
    light.blink()
    return "Success"

if __name__ == '__main__':
    app.run()

For what you're trying to accomplish you don't need to do anything with the order data, but it might be nice to inspect and/or log.

Ad
source: stackoverflow.com
Ad