days since this article was written, please be aware of its timeliness
Preface
Previously, the entire website was built by a single senior developer, resulting in various bugs and incomplete details. Therefore, we decided to refactor it. Brother Hou set up the seajs development framework, so I only needed to focus on writing the frontend logic.
Current Status
Since I was responsible for the registration and login sections, I planned to add functionality for Sina Weibo and QQ login. After a user clicks to log in, their ID would be stored in the database. Of course, this requires modifying the database table fields, specifically adding a column like wb_id to identify the user.
Currently, there are two popular approaches:
- After logging in via Sina Weibo (or other methods), the backend automatically creates a unique ID for the site. The same row stores the user’s Weibo ID in
wb_id. Subsequent logins can use any account. After the first Weibo login, the user only needs to set a nickname (optional; the Weibo nickname can be used directly) and a password (mandatory, in case Sina Weibo shuts down, preventing users from logging in). - After logging in via Sina Weibo, the user is guided to manually create an account and password or bind to an existing registered account.
My Approach
The above outlines the business logic. I will implement the first approach. Below are the specific implementation details: how to use Sina Weibo’s JSSDK API.
First, as mentioned in most online tutorials, it’s necessary to understand the principles of the OAuth 2.0 protocol. However, even without deep understanding, knowing the flow is sufficient. There are plenty of resources online about the OAuth 2.0 authentication process, so I won’t elaborate further here.
Note: All steps assume you have already obtained developer permissions on the Sina Weibo Open Platform. Without these permissions, you cannot call the API. For information on applying for Sina Weibo developer status, please search online. After approval, you will receive an appid, which is crucial for Sina to identify who is calling its API and will be used in subsequent steps.
Step 1: Add Namespace and Reference the JSSDK File
Add the namespace:
<html xmlns:wb=”http://open.weibo.com/wb”>
Reference the JSSDK file:
<script src=”http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=YOUR APPKEYdebug=true” type=”text/javascript” charset=”utf-8″></script>
Replace YOUR APPKEY with the appid provided by Sina Weibo when you applied for developer status. debug=true facilitates debugging and can be removed (&debug=true) when going live.
Step 2: Use the API for Authorization Login
There are two methods here:
- Call the
WB2.login()method directly in the script after clicking a button. For details, refer to the Sina API. - Redirect the user to a URL containing your
appidand callback address (let’s call it the authorization page). The format is:
https://api.weibo.com/2/oauth2/authorize?client_id=YOUR APPKEY&response_type=token&display=js&transport=html5&referer=Your_CallBack_Address
Replace YOUR APPKEY and Your_CallBack_Address with your own. Note that Your_CallBack_Address must include `http://``. For example, my test redirect URL is:
https://api.weibo.com/2/oauth2/authorize?client_id=2177891434&response_type=token&display=js&transport=html5&referer=http://www.xheldon.com/gbtagsLogin.html
Note: It seems the callback address must end with a suffix like .php, .html, or .jsp (dynamic or static). For a homepage, it might need to be http://xheldon.com是不行的,需要加上http://xheldon.com/index.html(因为我的后台是` (Node-based), though I haven’t tested this. Those interested can experiment.
The first method displays a pop-up dialog for Weibo login authorization upon clicking the redirect entry. If you’re using Chrome, you’ll notice a lock icon next to the address bar in this small window, indicating the address is locked and unmodifiable. After entering the Weibo login credentials and authorizing, the dialog closes, the original page refreshes, and the third-party site can access your account.
The second method avoids using WB2.login() in the script. Instead, it redirects users to the aforementioned URL containing the appid and callback address. This method requires users to enter their credentials on a separate authorization page. After authorization, they are redirected back to the callback address specified in the URL.
The principle behind these two steps is essentially the authentication process of the OAuth2.0 protocol. The JSSDK simply handles the first request’s returned code and the second request’s returned access token for you. Therefore, you don’t need to follow the official API’s instructions, such as using the basic method to place the access token in the header and employing post or get methods—terms that might sound confusing. Instead, you only need to focus on the frontend logic and utilize the obtained JSON-format data.
Still referring to the same address, Weibo API Entry-Level Documentation. Of course, the term “entry-level” is my own creation. Once you understand how these five work, you can apply the same approach to other APIs in the future.
Among these APIs, WB2.login(), WB2.checklogin(), and WB2.logout are relatively simple—anyone can understand them. If not, just follow what I mentioned earlier about the WB2.login() method and place it inside a script tag. However, after guiding the login, you won’t have done anything yet.
If you want to do something after logging in (which is obvious—why ask users to log in otherwise?), such as fetching the logged-in Sina Weibo user’s ID or their follower count, it all relies on the most important of these five entry-level APIs:
the function for interacting with Weibo’s API and invoking built-in Weibo components via JavaScript (as officially described): WB2.anyWhere(callback).
For data interaction, you’ll need to use W.parseCMD(uri, callback, args, opts), where the W parameter is passed in by WB2.anyWhere(callback). If you want to call Weibo components, you can use methods like W.widget.hoverCard(…) or W.widget.followButton(…);.
The most crucial step is the data interaction between you and Sina.
The general usage of W.parseCMD follows this format:
W.parseCMD(
'/users/show.json',
function (oResult, bStatus) {
if (bStatus) {
//to do something...
}
},
{
screen_name: '姚晨',
},
{
method: 'get',
cache_time: 30,
}
);
Here, the first parameter /user/show.json in W.parseCMD() can be replaced with other endpoints, such as /statuses/user_timeline.json, to fetch data from that interface. For a full list of available endpoints and the data they return, Sina provides a Weibo API Testing Tool. Note: The login interface of this testing tool has issues. Instead of logging in directly on this page, log in on Weibo’s homepage first, then refresh the API testing tool page.
The screen_name field is optional, but the surrounding {} must remain, even if it’s empty.
The method: get parameter specifies the interaction method with the backend. Sometimes, post is required. As for cache_time, its meaning should be self-explanatory—no further explanation needed.
That’s pretty much all you need to pay attention to.
-
Previous
"Translation" Promise Anti-Patterns -
Next
A Personal Reflection on the Importance of Code Optimization/Work Experience
I often wish that when facing some key decisions in life, someone could tell me the best course of action so that I would not waste my precious time. Putting myself in others' shoes, I therefore write blogs often, hoping to record in this tiny corner of the vast Internet the once-in-a-lifetime experiences that matter to me, and to help those who seek help.