A quick look at setting up the Stripe Python API with a Flask server.
mkdir python-flask-stripe && cd python-flask-stripe # pip or pip3 depending on env pip3 install Flask pip3 install stripe pip3 install -U python-dotenv touch .env server.py
Fetch your keys from Stripe and replace the following in the file:
SK_TEST_KEY=sk... # replace sk...
Set up the file to look like the following:
from flask import Flask from flask import request from dotenv import load_dotenv import stripe import os # Load local .env file and assign key load_dotenv() stripe.api_key = os.environ.get("SK_TEST_KEY") app = Flask(__name__) @app.route("/api/charge", methods = ['POST']) def charge(): try: content = request.get_json() # Print what JSON comes in for the sake of checking print(content) resp = stripe.Charge.create( amount=content['amount'], currency="usd", source="tok_visa", receipt_email=content['receiptEmail'], ) print("Success: %r" % (resp)) return "Successfully charged", 201 except Exception as e: print(e) return "Charge failed", 500 if __name__ == "__main__": app.run()
The above:
/api/charge
that only takes the POST
method and creates a charge based on the amount we pass.python3 server.py
will start the server on port 5000.
Running http POST http://localhost:5000/api/charge amount:=600 receiptEmail=hello_flask@example.com
(using HTTPie) will come back with success. Check your Stripe dashboard and you will see a charge made for US\$6.00! Hooray!