Adding card on file details with Python
Attaching a customer’s card on file to their Square profile is an important part of setting up recurring payments. Here’s how to do it with Python.
In this post we’ll be using the
CustomerCard endpoints to add a card on file to a customer that you could then use for subscription billing online or in-person. But remember, you should not link a card on file to a customer without the customer’s express permission. For example, you can include a checkbox in your purchase flow (unchecked by default) that the customer can check to specify that they wish to save their card information for future purchases.
To get started you’ll need a Square account, an application in the Square developer portal, and of course, at least one customer to attach the card to. You can create your Square account at https://squareup.com/developers, your developer application at https://connect.squareup.com/apps and to create your customer you can either use the Square Point of Sale app or use the APIs to create a customer in your customer directory.
Attaching the card on file
Adding a card on file is very similar to charging a card for an e-commerce transaction. You’ll have to generate a card nonce using the
sqpaymentform and then pass it to the CreateCustomerCard endpoint. Since the payment form will have to be embedded in a different client-facing page, and the REST request to attach the customer card will be hidden away on the server’s side, this example will just use a hardcoded testing nonce. Let’s look at the code:
Here you can see the code first initializes the Square Python SDK and imports a couple of useful tidbits, such as the CustomersAPI and the model for creating the customer card request. Then you’ll need to set the access token. I recommend using a sandbox access token so that you can use the fake card nonce also hard coded in this example.
When it comes to actually creating the
CustomerCard, the code uses the model that was imported above, and attaches the card nonce, as well as made up
cardholder_name. You also have the option to add a
billing_address but it is not required.
You can run this code snippet directly from your command line with a command link
python createCustomerCard.py (or whatever you decided to name the file). If everything goes well, you should see something like the below as your customer card details are printed on the screen.
Now you can use the card to make card-on-file purchases in person or online to meet your billing needs!
Thanks for reading. If you have any questions, comments, concerns, or excitements, feel free to comment on this post below, or reach out to us on Twitter.