Wechat is the most popular IM App nowadays in China. The Wechat MP could deliver various functions to Wechat users with its Developer API.
Recently I registered a Wechat MP for my Discourse forum E1zone and developed some server-side functions to fetch users’ information from the Discourse forum. This post includes the procedure of the implementation and some notes of technical details.
The code is now hosted in Github: discourse-wechat-mp.
The implemented functions:
- reply “?” to check usage.
- reply “最新” to get weekly highlights list
- reply “绑定” to bind Discourse account to Wechat account
- reply “解除绑定” to unbind.
- reply “消息” to check recent forum notifications.
Overview
Binding Wechat OpenID to Discourse User Account
- Store Discourse user API key, identification code and username in a database.
- discourse user request for the API key—>
- Administrators generate user API key —>
- Insert the entry which contains information of api_key,Discourse username,and identification code.—>
- send Wechat identification code to user—>
- Detect identification code from user reply —>
- validate the code, update database, add user’s wechat OpenID.
Highlights of The Implementation.
Discourse API called to fetch user notifications
curl http://localhost:3000/notifications.json?api_key=test_d7fd0429940&api_username=test_user
Fetching and Analyse Json Data with PHP
Function Overloading in PHP
Define a function with no parameter:
Use sprintf() to get pre-defined string from template
Connect to MySQL in PHP
This is not a quite up-to-dated way:
It is better to use mysqli() instead:
Note on the object-oriented example above: $connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0, use the following code instead: // Check connection if (mysqli_connect_error()) { die(“Database connection failed: “ . mysqli_connect_error()); }
Verify String’s Format
Use function “preg_match(pattern,variable)” ` if (preg_match(“/[A-Za-z0-9]+/”, $form_Content) && strlen($form_Content) == 8) { …} ` The example here checks whether the $form_Content contains only letters and numbers and the length of the string is exactly 8. It is used to detect the identification code. It is better to have user operation state stored in the server-side. However, taken the Chinese’s input habit into account, it is feasible. It is really rare to have a reply which contains only letters and numbers from a Chinese user.
Basic PHP form
- Check user’s input:
The form is written as following:
-
form submit to the page self, in order to show the info in the same page:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
-
When user release a key while input, call a function
onkeyup="keyupFunction()"
Following is the function in JS: