Use Python's flask framework to build a simple digital goods payment solution _python

Source: Internet
Author: User
Tags uuid

As a programmer, I sometimes forget the ability I have. When things don't evolve the way you want them to, it's easy to forget that you have the ability to change it. Yesterday, I realized that I had been fed up with the way I paid for the books I had sold. After my book was finished, I used three different digital payment processors, and after being dissatisfied with three of them, I used Python and flask, two hours to write my own solution. That's right! Two hours! Now that the system is supporting my book-paying process, the whole process is incredibly simple and you can buy books and start reading in 20 seconds.

Look down and see how I finished my own digital goods payment solution overnight.
Payment issues for the payment processor

When I started selling books, I used two kinds of payment services (one is credit card, the other is PayPal). In the end, I found a way to support both. But I was not satisfied with them. The most commonly used payment processor requires the user to create an account in the vendor's system and enter their email address (although the mailbox is not used).

In addition, I try to use Google Analytics to track visitors, including their checkout process, in all of their visits, and this is a difficult process. I often feel that if I can get it to work and be able to do a A/b test on my book page, I can dramatically increase sales. But because I can't track it well, I'm not that lucky.

Finally, with three different payment processors, it is time-consuming to send book updates. No one can support the update very well, and I want a "one-click" Solution to send my book updates. I didn't find a service like that.
Oh yes, I'm a programmer.

Yesterday, when I received an email from a customer complaining about how difficult the payment process was and telling me that I could lose a lot of sales, I couldn't stand it. I decided to complete one of my own digital commodity management solutions. I need to do the following process:

When the customer clicks on the "Buy Now" button, they should only be asked to enter their email address and credit card information. When you click "Confirm", you are brought to a unique URL to download the book (generated specifically for this transaction). A message containing this URL should be sent to the customer (to prevent the user from having to download the book again). There should be a limit to the number of times they repeat the download (5). Transaction information and customer information should be stored in the database, and sending a book update should be just a matter of order.

Obviously, it's not that complicated. The most complex part is the dynamic generation of unique URLs that guide a particular book version. The other things are pretty simple.
"Flask come to rescue" or "a digital goods payment solution with 100 lines of code"

Spoiler: The final result of the program is exactly 100 lines of code. For Web applications of this scale, flask is a good choice. You don't need a lot of templates (cough like Django cough), but there are a lot of good plug-ins to support. Bottle would be another good choice, but I've been using flask lately, so I chose it.

In the beginning, I need to decide how to store user and transaction information. I decided to use SQLAlchemy, because Sandman reason, I am more familiar with it sqlalchemy. Flask has a plugin called Flask-sqlalchemy, which makes it easy to use both. Because I don't need any fancy database operations, I choose SQLite as my background database.

Having decided to do so, I created a 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 5 different versions of the books to the database (I created a populate_db.py file and added them as a sqlalchemy model to the database), I need to decide exactly how I am going to handle the payment. Luckily, Stripe makes it very easy to accept a credit card, and I already have one of their accounts. Their "checkout.js" program creates a form and a button on your page. When you click on this button, a simple and eye-catching floating layer will bounce out.

The action attribute of this form points to a page of your site that will be brought there when the user completes the payment. I added 5 such buttons to my book sales page and a hidden form column containing the ID of the traded product (PRODUCT_ID) (an integer between 1-5)
Process Payment

Obviously, my application requires a backend to process a successful payment. I added the following functions to do this:

 
@app. Route ('/buy ', methods=[' POST]) def buy (): Stripe_token = request.form[' stripetoken '] email = request.form[' St Ripeemail '] product_id = request.form[' product_id '] Product = Product.query.get (product_id) Try:charge = Stripe . Charge.create (Amount=int (product.price), currency= ' USD ', Card=stripe_token, Descrip Tion=email) except Stripe.  Carderror, E:return "" " 

As you can see, I was a bit lazy when I wrote the code (because I was working on angry programming ...). First, I have an inline HTML that returns when the payment is unsuccessful and returns when the purchase is successful. These things should be placed in a global variable, or the better way is to put them in a separate file. In addition, I did not make any error checking when I created the purchase. But in fact, the only thing that can go wrong is to try to insert a duplicate UUID, but I'm not worried because the probability of happening is too low (subtext: minimal).

You can see I'm using a mail object that comes from the Flask-mail package, which makes it easy to send messages. I set it to use Gmail as a server, and everything worked.
Well, now it's time to give me the book.

Now that the payment is done, I need to add a back-end feature to initialize the download after payment has been completed. Because I use the UUID as the primary key, I can also use it as a URL. When someone accesses a URL that contains a UUID, I need to check if the UUID is included in the database. If so, provide a book file and reduce the remaining download (downloads_left) Count attributes 1 times. If not, return 404 errors. Here's the code I wrote:

@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 find transaction information. If so, check to see if there are any available downloads, and then provide the files you purchased. Otherwise, the 404 error is waiting for you.

Finally, I need to add a test to allow me to simulate the trading process. Here's the code to test the code and run the app:

@app. Route ('/test ')
def Test (): Return
  "" " 
 

The greater the ability ... The greater the responsibility!

In fact, I was amazed at how quickly and simply I was able to do all this work. The entire application is contained in a file of 100 lines of code. And it replaces the important services I use every day, and I'm not satisfied with those services. Finally, I was able to track the transaction without any problems, which convinced me that I could improve my sales.

As a developer, it's good to realize that you have the ability to shape our interactions with the digital world. I would forget, for example, that if there were some technology that could not work the way I expected, I would be able to change it. From automated mechanical tasks like input data to automatic sorting and sorting emails, developers have the ability to simplify their daily work.

Having a tool like flask is very important to solve these problems. As with progress as a programmer, you should build your set of tools to solve the "core" problem. Flask is a good example, because it's a commonplace to scramble to put together a Web application.

Of course, it's also very important to share your work. If I do something that is useful to myself, but does not share it with others, I will neglect it. "Sharing" does not just mean "putting the project into a GitHub public warehouse". You also need to let people know that there is this thing. From mailing lists to forums to personal blogs, there is never a shortage of ways to let people know that you have created something. I always try to give back to the community because I get a lot of things from it.

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.