Using the Python Flask framework to build a simple digital commodity payment solution, pythonflask

Source: Internet
Author: User

Using the Python Flask framework to build a simple digital commodity payment solution, pythonflask

As a programmer, I sometimes forget my abilities. When things do not develop in the way you want, it is easy to forget that you have the ability to change it. Yesterday, I realized that I was overwhelmed by the payment method of the books I sold. After my book is complete, I used three different digital product payment processors. After I was dissatisfied with all of them, I used Python and Flask, I wrote my own solution in two hours. That's right! Two hours! Now, this system supports my book payment process, and the entire process is incredibly simple. You can purchase and start reading books within 20 seconds.

Let's look at how I complete my own digital product payment solution overnight.
Payment Processor payment problems

When I started selling books, I used two payment services (one is credit card and the other is PayPal ). Finally, I found a way to support both. But I am not satisfied with them. The most commonly used payment processor requires users to create an account in the seller's system and enter their email addresses (though the mailbox is useless ).

In addition, I tried to use Google Analytics to track visitors throughout all the visits, including their checkout process, which was also very difficult. I often feel that if I can make it work and perform A/B testing on my book pages, I can greatly increase sales. But I am not so lucky because I cannot track it well.

Finally, it takes a lot of time to send book updates using three different payment processors. None of them can support updates, but I hope to have a "one-click" solution to send my book updates. I did not find a similar service.
Ouye, I am a programmer.

Yesterday, when I received an email from a Customer complaining about how difficult the payment process was and telling me that I may have lost a lot of sales, I couldn't bear it. I decided to integrate my own digital product management solution. I need to do the following process:

When the customer clicks the "Buy Now" button, they should be asked to enter their email address and credit card information. Click "Confirm" and be taken to a unique URL to download the book (generated specifically for this transaction ). An email containing this URL should be sent to the customer (to prevent users from re-downloading the book ). There should be a limit on the number of repeated downloads (5 times ). Transaction information and customer information should be stored in the database, and sending book updates should be just a command.

Obviously, this is not that complicated. The most complex part is the dynamic generation of unique URLs directed to specific book versions. Other things are quite simple.
"Flask to rescue" or "a 100-Line-of-code digital product payment solution"

Spoiler: the final result of the program is exactly 100 lines of code. Flask is a good choice for web applications of this scale. There is no need for a large number of templates (cough is like Django cough), but there are many good plug-ins for support. Bottle will be another good choice, but I have been using Flask recently, so I chose it.

At the beginning, I needed to decide how to store user and transaction information. I decided to use SQLAlchemy. For sandman reasons, I am familiar with SQLAlchemy. Flask has a plug-in named Flask-SQLAlchemy, which makes it easy to use both. Because I don't need any fancy database operations, I chose SQLite as my background database.

After deciding to do this, I created an app. py file and created the following model:

 class Product(db.Model):  __tablename__ = 'product'  id = db.Column(db.Integer, primary_key=True)  name = db.Column(db.String)  file_name = db.Column(db.String)  version = db.Column(db.String)  is_active = db.Column(db.Boolean, default=True)  price = db.Column(db.Float) class Purchase(db.Model):  __tablename__ = 'purchase'  uuid = db.Column(db.String, primary_key=True)  email = db.Column(db.String)  product_id = db.Column(db.Integer, db.ForeignKey('product.id'))  product = db.relationship(Product)  downloads_left = db.Column(db.Integer, default=5)

After adding five different versions of books to the database (I created a populate_db.py file and added these versions to the database as SQLAlchemy models ), I need to decide how to handle the payment. Fortunately, Stripe made it very easy to accept a credit card and I already have an account. Their "checkout. js" solution will create a form and button on your page. When you click this button, a concise and striking floating layer will pop up.

The action attribute of this form points to a page of your site and will be taken there after the user completes the payment. I added 5 such buttons on my book sales page, and a hidden form bar that contains an integer between product_id (1-5) of the product to be traded)
Process payment

Obviously, my application needs a backend to process a successful payment. I have added the following functions for this purpose:

 @app.route('/buy', methods=['POST'])def buy():  stripe_token = request.form['stripeToken']  email = request.form['stripeEmail']  product_id = request.form['product_id']  product = Product.query.get(product_id)  try:    charge = stripe.Charge.create(        amount=int(product.price * 100),        currency='usd',        card=stripe_token,        description=email)  except stripe.CardError, e:    return """

As you can see, I am a little lazy when writing code (because I am angry with programming ......) First, I have an inline HTML, which will be returned when the payment is unsuccessful, or when the purchase is successful. These things should be put in a global variable, or a better way is to put them in a separate file. In addition, I did not perform any error checks when creating Purchase. But in fact, the only possible error is to try to insert a duplicate uuid, but I am not worried, because the probability of occurrence is too low (subline: very small ).

As you can see, I used a mail object from the Flask-Mail package. This plug-in makes sending emails easy. I set it to use GMail as the server, and everything will work properly.
Okay, it's time to give me a book.

Now, the payment is done. I need to add a backend function to initialize the download after the payment is complete. Because I use UUID as the primary key, I can also use it as the URL. When someone accesses a URL containing a UUID, I need to check whether the UUID is included in the database. If yes, provide the Book file and reduce the number of remaining downloads_left attributes by 1. If not, Error 404 is returned. The code I wrote is as follows:
 

@app.route('/<uuid>')def download_file(uuid):  purchase = Purchase.query.get(uuid)  if purchase:    if purchase.downloads_left <= 0:      return """

Very intuitive. Use UUID as a URL variable to search for transaction information. If yes, check whether there are still available downloads and then provide the purchased files. Otherwise, we will wait for you to see the Error 404.

Finally, I need to add a test so that I can simulate the transaction process. The following is the test code and the code used to run the app:

@app.route('/test')def test():  return """

More powerful... More responsibility!

In fact, I was surprised to hear that I was able to work so quickly and easily. The entire application is contained in a 100-line code file. And it replaces the important services I use every day, and I have never been satisfied with those services. Finally, I can track transactions without any problems, which makes me confident that I can increase sales.

As a developer, it is good to realize that you have the ability to shape our interaction with the digital world. For example, I will forget that if some technologies cannot work as expected, I have the ability to change it. From automated and mechanical tasks such as input data to automatic sorting and email sorting, developers have the ability to simplify their daily work.

Tools like Flask are very important to solve these problems. As a programmer, you should build a set of tools to solve the "core" problem. Flask is a good example, because it is common to join a web application in a hurry.

Of course, sharing your work is equally important. If I do something useful to myself, but I do not share it with others, I will neglect it. "Sharing" not only means "putting a project into a GitHub public repository". You also need to let everyone know about this. From the email list to the Forum to my blog, there is no way to let everyone know that you have created something. I always try to give back to the community, because I get a lot from it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.