# Using Flask and LeanCloud to build a backend of Wechat Official Account

[Prerequisites: Master of Chinese and English reading]

During the last month, a lot of “Yellow bike” the name of which is “ofobicycle” have been sent into the campus to serve us, students, on debt. Since each bicycle possesses one fixed password to unlock, which means the best situation is that you obtain all the codes and passwords and use them as you wish, my partner and I try to do a project to get this feature.(All the contents here are just for entertainment and study, which means you can not use them in commercial affairs and please obey the law in local areas and the ToS of “ofobicycle”.)

The first thing to do is choose one language to develop this project and my partner littermonster was on duty, as our plan instructs. He use PHP and mysql to build two apis and a matrics-based database(as we desire, a lot of people can join in our project when they are using our service, which means they can add records and give feedbacks to the database to make the data more accurate, that means we should build a matrics-based database to assign this feature to this database, due to the requirements are not that complex, so we can make this feature realized). So, the last revealed result is two links:

Query:
http://bike.littermonster.net/get.php?src=app&bike_code={bike_code}

A lot of work done by littermonster after which means this project just has to be boxed and displayed to the users. But in my opinion, the api is not regulated and beautiful, so I rewrite this two links into this form:

Query:

http://somedomain.com/api/v1.0/code_pass_query/<code>

http://somedomain.com/api/v1.0/code_pass_setter/<code>/<password>

You can easily build up a Flask App or another way(which is followed to be stated).

And the main flask code are:

Then we can start the simple application to feed them some testing cases.
We can use curl command to get it.

And we can add some new codes and passes.

And sometimes the pass can be same so the matrics should be updated!

Okay, I just want to assume this feature is done.

And when this two Apis are ready, the next thing to be done is build a webpage to give the entry to the users to look for the code and add the passwords. The work is also done by littermonster, you can visit bikecode to find out how it looks like. It uses JQuery to give users best experience.

After this, you may say, Okay, there is nothing we can do any more, so let’s just go back home and sleep! No no, this is not the right thing, it can be easier and more convenient, which means it should be more easy-accessable and easy-to-use. So He gave me one suggestion, why not build a wechat official account and realize these features? If so, we can easily look for the codes and add them just in the software wechat, there will be no necessaries for us to open another application(for example, a browser, just reply on wechat). I thought that was a intelligent idea and it must be put into practice. Therefore, I went to the official document:

Official Document

Before this, the first problem I have to deal with is one server, as the program developed as plan, I have to deploy this web app on one server and make it running correctly. But my private server is LEMP-based environment, I just don’t want to make any changes to this stable environment, so, I have to choose one reliable service provider. First IBM Bluemix came to my mind, And it’s easy to use, but I didn’t want to install any softwares on my laptop, As bluemix have to install two strange softwares called CF-xxxxt to imitate the server environment. I’ve given it a try, but it was not running as expected, so I uninstalled them. After the uninstallation, I chose one service call LeanCloud(which was previously called AVOSCloud [AVOS Systems is an Internet company led by YouTube co-founders Chad Hurley and Steve Chen] , as you know, it was the child company responsible for AVOS System in China) They provide one service named lean engine, and the application maybe a little complex and troublesome, as the company have to obey China’s laws(for example, real-name confirmation). Let’s just omit the details, I was so tired of them.

I just want to assume that you have installed the python environment and Lean Environment correctly(for example python 2.7.12, pip et cetera, the details you should google it or refer to the leancloud docs) Just remember, all the things you want to do relies on a lot of documents(official or not official, which means you have to read the documents or instructions carefully, over and over again and think over and over again, then you will find how to solve the present problem，for example, you have to install the Leancloud Environment which may require to install homebrew firston your desktop or laptop, et cetera. In fact, here will be more than these things to do, e.g., install pyenv and virtualenv in which case to work together with pyenv, you have to install pyenv-virtualenv which install virtualenv as a plugin into pyenv, to make the dev environment isolated, and nvm to set up the node environment. Therefore, the next post I desire to write will state the things I did after installing OSX EI Capitan 10.11.4, so, just keep waiting!)

Then, go to your working directory and make one directory.

mkdir -p /Volume/Work/Leancloud/Wechat-example && /Volume/Work/Leancloud/Wechat-example

After this, we have to new one leancloud app.

Due to we want to build one python web app, so just choose option 1.

Open the project directory, I prefer to use Pycharm.

Find the app.py, the main code are contained in this file.

So, first thing is just finish the logical authentication of wechat, which means when the wechat server post one formatted data package(In POST Method and you should check if the token is valid, if so, you should return one response, return back one random string.)

And when completing this piece of code, you can easily use the command lean up in the working directory to run the program offline, and open terminal in one new window, to imitate POST request. However, this authentication is complex as there will be token and random string and timestamp, it’s quite hard to imitate this POST request. Also, I did not store the post-data of wechat server authentication, so I did not know what the post-data is. But this snippet is so easy that almost there will not be errors, maybe you can first deploy it to LeanEngine and get the customized domain authenticated.

First, you have to set up this domain, which can be your preference, but before you setting up the domain, you just have to do Real-name confirmation, as the picture shows. Also, you can use your own domain to, just make sure that your domain is safe and have been signed up in the Ministry of Industry and Information Technology of People’s Republic of China ICP/IP System. It depends on which server provider is, as to me, this server is hosted on Aliyun, so I just have to go to Aliyun to finish the sign up. And then, you just have to send an email to the Leancloud Support(support@leancloud.cn), which may looks like:

After receiving confirmation email from the staff of LeanCloud, they will tell you to set one CNAME record at your DNS provider to point to leanapp.cn, in my case, I have to set one CNAME record of code_pass.fairvalue.cc to leanapp.cn.

After that, we can easily use our own domain. For example, you can visit this for testing. (I highly recommend you to bind your own domain due to wechat may ban the leanapp.cn irregularly due to others’ illegal behaviour on wechat in which case their program is also hosted on LeanEngine. )

Then, we can go to the wechat dashboard to set the connection to our program.

After this, we can start writing some interesting codes.

As a matter of fact, this summer we borrow the laboratory from our teacher for reviewing for the Chinese postgraduate qualifying examination and the teacher required us to sign in and sign out every day.

Therefore, one idea came to my mind: why not use wechat to make this process smoother and easier? So, I have to write one program to make it done.

I have to interrupt you at this position, I have to state that the wechat server will post data to our server when the user do some operations, e.g. subscribe, send one message, click the menu and et cetera.

Let’s jump into one case, when the user subscribe to your Wechat official account, the wechat server will post the following data to our server. Here is one example:

Use this data we can easily imitate the POST procedure, in that case, we can add one trigger, which means when the user subscribe to this account, we send one preserved message to show to him/her, tell her something about the account.

Use the snippet above, we can extra the parameters we need to judge the type of the event and the kinda things about what the user’s account is, what official account is, what the message the user sends to our account, et cetera. Use the last command we can split the command line into separate command, in which case we desire the command should in this format:

• reg+{name} (to register in this signin system)
• {5-digit/6-digit number, code} (to query the code and get its pass)
• a+{5-digit/6-digit number, code}+{4-digit number, pass} (to add the pass of the code)
• {5-digit/6-digit number, code}-{4-digit number, pass}(to add the pass of the code)
• /h (help manual)

Register module

Check in module

Check out module

After all this completed, we can use lean up to run it, then I will show you how to tell locally.

New one terminal window, cd to the working directory, new one plain file and add some statements and save it as for example, “post-data”:

Use this command will be a better choice:
curl -H "Content-Type: applicaition/json" -d @post-data -X POST http://localhost:3000/weixin
or cat post-data | curl -H "Content-Type: applicaition/json" -d @- -X POST http://localhost:3000/weixin

And here is another third method to post the data, after the "-d " which means "–data " parameter, you can put all the post data in multiple lines, but that was more complex, so I prefer not to.

If you think the information are not verbose enough, you can easily use the “trace-ascii” parameter to print more information.

We by modify the contents of the post file, we do some more tests.

I modify the FromUserName and add one user named ‘test’ in the validation list to avoid conflicts.

Then check in and check out.

And up to here, we have finished the signin system. Whereas, can we go a little further? The answer is Yeah! We could do it! Still remember the ofobicycle? The best method to hack its passwords is collecting all the passes and store them into one database and if needed, just query! But, how can we get some many passes? That’s called “crowdsourcing”. We can invite a lot of people to join us and help us complete this job!

So, we just have to expose our Query and Add apis. Jus keep in mind, currently we have two apis:

• http://code_pass.fairvalue.cc/api/v1.0/code_pass_query/{code}
• http://code_pass.fairvalue.cc/api/v1.0/code_pass_setter/{code}/{pass}

We can also use curl command to GET the content:

Use GET to add a completely new pass:

In addition, we can update the existed pass:

You can easily find that the response is a json file, and it always have one status word and message word, so we can extract the json file to get the status, if it is 200 or 205, it means the addition is successful! When it is 404, then it means no such passes and waiting for you to add.

The complete code:

In spite of that feature, my friends asked me to make the system to checkout automatically, luckily, leanengine supports cron tasks. We have to add the following snippet to cloud.py and add the function to leanengine crontask through its dashboard.

Which means when 23:30:15 everyday, the program will call the function “autocheckinandout” in cloud.py.

And this project is hosted on Coding.net

So, above are almost all the things I am trying to state. Maybe there are some refers I have not marked, I will add some time later.

And if you are interested in my work or you just want to test my code, welcome use your wechat client so scan the following QRcode to follow my official account “Townes”.

Refer: