Let’s start by creating a payment workflow using the Rapyd API. For this purpose, you’ll instruct ChatGPT to create it using the following prompt:
Hello ChatGPT. I want to create a secure payment form and workflow using Rapyd's API. Specifically, I want:
- To use Python
- To use a Flask Server
- Create a form where I can create payment requests for a credit card
- The form should be nice looking and incorporate some .css
- To get the code step-by-step + explanations
As an answer, ChatGPT immediately generates the entire code base. While doing so, the AI breaks down the code into several parts. Let’s discuss each part in detail.
Step 1: Initialize as Flask App
First, ChatGPT creates a Python file named app.py
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
This section of code sets up a very basic Flask application with a single route that serves an HTML template (index.html) when the root URL is accessed.
The @app.route('/')
decorator specifies that this function should be triggered when the root URL (/
) is accessed. Essentially, it’s telling Flask to execute the following function whenever someone visits the home page of your app.
The function index()
is defined immediately after the route decorator. This function will be executed when the route is accessed. render_template('index.html')
is called within index()
. Flask then looks for an HTML file named index.html within a folder named templates
in the same directory as the Flask app. It will render this template and send it as the response to the client’s request.
Step 2: Create HTML/CSS for the Form
Next, ChatGPT creates an index.html file with the instruction to store it in a templates
folder on the same level as app.py. This HTML file provides the form where the user will enter the data to make a credit card payment. Specifically, the user must enter their name, amount to transfer, currency, card number, expiration month and year, and CVV.
<!DOCTYPE html>
<html>
<head>
<title>Payment Form</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Create a Payment</h1>
<form action="/create_payment" method="post">
Name: <input type="text" name="name"><br>
Amount: <input type="text" name="amount"><br>
Currency: <input type="text" name="currency"><br>
Card Number: <input type="text" name="card_number"><br>
Expiration Month: <input type="text" name="expiration_month"><br>
Expiration Year: <input type="text" name="expiration_year"><br>
CVV: <input type="text" name="cvv"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
After that, ChatGPT requests that the user add some custom CSS to a styles.css file within the static
folder to make the form more visually appealing. Noticeably, ChatGPT did not provide CSS, as specifically requested in the prompt. This will be addressed later.
Step 3: Use Python to Interact with Rapyd’s API
Next, ChatGPT provides the Python code that integrates with Rapyd’s API to create a payment charge. It defines a Flask route and associated function for handling the payment. In the following, the code is broken down into smaller parts and explained step by step:
RAPYD_ACCESS_KEY = 'your_rapyd_access_key_here'
RAPYD_SECRET_KEY = 'your_rapyd_secret_key_here'
BASE_URL = 'https://sandboxapi.rapyd.net'
RAPYD_ACCESS_KEY
and RAPYD_SECRET_KEY
are placeholders for the Rapyd API keys, and the BASE_URL
is the base URL for the Rapyd API call.
The following code is used to generate the salt
and the signature
:
def generate_salt(length=8):
letters_and_digits = string.ascii_letters + string.digits
return ''.join(random.choice(letters_and_digits) for i in range(length))
def create_signature(http_method, url_path, salt, timestamp, body=""):
to_sign = (http_method + url_path + salt + str(timestamp) + RAPYD_ACCESS_KEY + RAPYD_SECRET_KEY + body).encode('utf-8')
return hashlib.sha256(to_sign).hexdigest()
The utility function generate_salt()
generates a random “salt” string using ASCII letters and digits. create_signature()
generates an SHA-256 hash 1, which is used as a signature for API requests to Rapyd. The signature is computed using several pieces of information, including the HTTP method, URL path, salt, timestamp, and your API keys.
The following code defines a Flask API endpoint that accepts POST
requests to create a new payment using Rapyd’s payment service:
@app.route('/create_payment', methods=['POST'])
def create_payment():
amount = request.form['amount']
currency = request.form['currency']
card_number = request.form['card_number']
expiration_month = request.form['expiration_month']
expiration_year = request.form['expiration_year']
cvv = request.form['cvv']
name = request.form['name']
timestamp = int(time.time())
salt = generate_salt()
url_path = '/v1/charges'
http_method = 'post'
body = json.dumps({
'amount': amount,
'currency': currency,
'payment_method': {
'type': 'card',
'fields': {
'number': card_number,
'expiration_month': expiration_month,
'expiration_year': expiration_year,
'cvv': cvv,
'name': name
}
}
})
signature = create_signature(http_method, url_path, salt, timestamp, body)
headers = {
'access_key': RAPYD_ACCESS_KEY,
'salt': salt,
'timestamp': str(timestamp),
'signature': signature,
'Content-Type': 'application/json'
}
response = requests.post(BASE_URL + url_path, headers=headers, data=body)
return jsonify(response.json())
The Flask route for creating payment is defined with the @app.route('/create_payment', methods=['POST'])
decorator, which means that the server will listen for POST
requests at the /create_payment
endpoint. When a POST
request is received at this endpoint, the associated create_payment
function is invoked.
Inside the function, several variables like amount
, currency
, card_number
, expiration_month
, expiration_year
, and cvv
are initialized by extracting the corresponding values from the form data in the POST
request. Then, the function generates a timestamp
and a random salt
string, which are used along with other details like the HTTP method and API keys to create an SHA-256 signature. This signature authenticates the subsequent API request to Rapyd’s service.
The function prepares a JSON payload, specifying all necessary payment details, including the amount, currency, and card information. This payload is then sent as the body of an HTTP POST request to Rapyd’s API, specifically to the /v1/charges
endpoint. You should note that ChatGPT has provided an incorrect endpoint that does not exist. When working with APIs, especially for payment processing, you should refer to the official documentation provided by the service provider to ensure accurate and secure transactions. The API request is made with headers, including the previously generated salt, timestamp, and signature, and the API access key.
Finally, the function receives the API response, which contains information about the success or failure of the payment operation, and returns this as a JSON object to the client.
Step 4: Make the Form More Visually Appealing
By now, the code is finished and is ready to be tested. But before that, you’ll first want to make the form more visually appealing. Although ChatGPT was instructed to provide some CSS for the form, the AI did not do it and instead instructed you to provide your own code. The form without the CSS does not look great.