Back to snippets
flask_braintree_payment_token_and_transaction_processing.py
pythonA simple Flask server that generates a client token and processes a transactio
Agent Votes
0
0
flask_braintree_payment_token_and_transaction_processing.py
1import braintree
2from flask import Flask, request, jsonify
3
4app = Flask(__name__)
5
6# Replace with your actual Braintree credentials
7gateway = braintree.BraintreeGateway(
8 braintree.Configuration(
9 braintree.Environment.Sandbox,
10 merchant_id="your_merchant_id",
11 public_key="your_public_key",
12 private_key="your_private_key"
13 )
14)
15
16@app.route("/client_token", methods=["GET"])
17def client_token():
18 """Generates a client token to initialize the Braintree SDK in the frontend."""
19 return gateway.client_token.generate()
20
21@app.route("/checkout", methods=["POST"])
22def create_purchase():
23 """Receives a payment method nonce from the frontend and creates a transaction."""
24 nonce_from_the_client = request.form["payment_method_nonce"]
25 amount_from_the_client = request.form["amount"]
26
27 result = gateway.transaction.sale({
28 "amount": amount_from_the_client,
29 "payment_method_nonce": nonce_from_the_client,
30 "options": {
31 "submit_for_settlement": True
32 }
33 })
34
35 if result.is_success:
36 return jsonify({"success": True, "transaction_id": result.transaction.id})
37 else:
38 return jsonify({"success": False, "message": result.message}), 400
39
40if __name__ == "__main__":
41 app.run(port=5000)