当前位置:网站首页>Users of the Tiktok open platform are authorized to obtain the user's fan statistics and short video data
Users of the Tiktok open platform are authorized to obtain the user's fan statistics and short video data
2022-06-24 17:22:00 【Wukong codeword】
Recently, a friend asked me if I have ever worked on the Tiktok open platform , Let me have some thoughts , Actually, I have done it before . Though tiktok APP A fire , But after all, it is not like the wechat open platform , Has been deposited for many years , Basically every API As long as you are willing to look it up , There are many references on the Internet . However, the Tiktok open platform is not , It was just released , There is less information . Even for a developer , Access to third-party interfaces is similar , It's not too hard. , But I still want to write it down , Especially the pit encountered , Will be listed below , Learn together . Limited to a limited level , If there is an error , Don't hesitate to give advice . that , Let's start with the text .
1、 Registered account
Tiktok open platform address :
https://open.douyin.com/platform
Similarly, , Like other third-party platforms , Log in to the open platform after registering your account , The platform will review the submitted information , Create an application after approval ( If the audit fails , It doesn't allow you to create apps ).
2、 Create an
We usually get data for PC Website , So choose a web application to create , Fill in the information truthfully , Waiting for review . Make complaints about it here. , Compared with wechat , Tiktok is a small program or an open platform , The speed of audit is very slow , Although the platform will generally prompt for approval within three working days after submitting the information , But you may still want to send an email to urge . Here, let's take a look at the application after approval .
Click Details to enter , See the following , We have the platform issued Client Key and Client Secret You can start rolling the code .
3、 Realize the idea
There's nothing special about it , It is to guide the user to scan the QR code we access , Tiktok APP After the end scanning code is confirmed or the account password is authorized to log in , Will redirect to our callback interface , And with an authorized temporary note (code), We have it code, as well as ClientKey and ClientSecret Equal parameter , adopt API Exchange for access_token, Then you can go through access_token Make an interface call , Get basic user information and other operations . The general process is like this , Let's take a look at some details of the implementation .
4、 Development details
4.1、 Select content center -> Open Api -> Account Authorization and binding View interface documentation ,
4.2、 User code scanning authorization , Call back to our interface , Get code, Then call to get access_token The interface of , You can also get the corresponding open_id, because access_token It's time-sensitive , So we need to cache , Use before expiration refresh_token Refresh extension access_token The validity of the , After expiration, the user can only be re authorized .
Authorization related service
private static final Logger logger = LoggerFactory.getLogger(OauthServiceImpl.class);
private static final String OAUTH_STATE_SESSION_KEY = "OAUTH_STATE_SESSION_KEY";
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Value("${redis.key.douyinTokenKeyPrefix}")
private String douyinTokenKeyPrefix;
@Value("${redis.key.douyinRefreshTokenKeyPrefix}")
private String douyinRefreshTokenKeyPrefix;
@Value("${redis.key.douyinClientTokenKey}")
private String douyinClientTokenKey;
/**
* Get authorization code (code)
* @param clientKey
* @param redirectUri
* @param state
* @return
*/
@Override
public String qrcodeAuth(String clientKey,String redirectUri,String state) {
String requestUrl = Urls.BASE_URL+String.format(Urls.PERSON_CONNECT_URL,clientKey,redirectUri,state);
ShiroUtils.setSessionAttribute(OAUTH_STATE_SESSION_KEY,state);
logger.info("qrConnect requestUrl=" + requestUrl);
return requestUrl;
}
/**
* obtain access_token
* @param request
* @param clientKey
* @param clientSecret
* @return
*/
@Override
public TokenResult accessToken(HttpServletRequest request,String clientKey,String clientSecret) {
String code = request.getParameter("code");
String state = request.getParameter("state");
Object sessionState = SecurityUtils.getSubject().getSession().getAttribute(OAUTH_STATE_SESSION_KEY);
TokenResult token = new TokenResult();
// check state
if (sessionState != null && state.equalsIgnoreCase(sessionState.toString())) {
SecurityUtils.getSubject().getSession().removeAttribute(OAUTH_STATE_SESSION_KEY);
String requestUrl = Urls.BASE_URL+String.format(Urls.ACCESS_TOKEN_URL,clientKey,clientSecret,code);
JSONObject response = (CommonUtil.httpsRequestJson(requestUrl, "GET", null));
JSONObject object = response.getJSONObject("data");
logger.info("accessToken result=" + response);
int errorCode = object.getInteger("error_code");
String description = object.getString("description");
if (errorCode == 0) {
token.setErrorCode(0);
token.setAccessToken(object.getString("access_token"));
token.setExpiresIn(object.getInteger("expires_in"));
token.setRefreshToken(object.getString("refresh_token"));
token.setOpenId(object.getString("open_id"));
token.setScope(object.getString("scope"));
} else {
token.setErrorCode(errorCode);
token.setDescription(description);
}
} else {
token.setErrorCode(500);
token.setDescription("state Check failed ");
}
return token;
}
/**
* Refresh access_token
* @param clientKey
* @param refreshToken
* @return
*/
@Override
public TokenResult refreshToken(String clientKey,String refreshToken) {
String requestUrl = Urls.BASE_URL+String.format(Urls.REFRESH_TOKEN_URL,clientKey,refreshToken);
JSONObject response = (CommonUtil.httpsRequestJson(requestUrl, "GET", null));
JSONObject object = response.getJSONObject("data");
logger.info("refreshToken result=" + response);
int errorCode = object.getInteger("error_code");
String description = object.getString("description");
TokenResult token = new TokenResult();
if (errorCode == 0) {
token.setErrorCode(0);
token.setAccessToken(object.getString("access_token"));
token.setExpiresIn(object.getInteger("expires_in"));
token.setRefreshToken(object.getString("refresh_token"));
token.setOpenId(object.getString("open_id"));
token.setScope(object.getString("scope"));
} else {
token.setErrorCode(errorCode);
token.setDescription(description);
}
return token;
}Authorization related controller
@Value("${redis.key.douyinTokenKeyPrefix}")
private String douyinTokenKeyPrefix;
@Value("${redis.key.douyinRefreshTokenKeyPrefix}")
private String douyinRefreshTokenKeyPrefix;
@Value("${open.douyin.clientKey}")
private String clientKey;
@Value("${open.douyin.clientSecret}")
private String clientSecret;
/**
* Tiktok authorized login
* @param anchorUuid
* @param response
* @throws IOException
*/
@RequestMapping(value = "qrcodeAuth")
public void qrcodeAuth(String anchorUuid, HttpServletResponse response) throws IOException {
String redirectUrl = parameter.getSERVER_PATH() + "/mobile/douyin/authCallback";
String state = UuidUtils.randomUUID() + "::" + anchorUuid;
String requestUrl = oauthService.qrcodeAuth(clientKey, URLEncoder.encode(redirectUrl, "UTF-8"), state);
response.sendRedirect(requestUrl);
}
/**
* Tiktok authorization callback
* @param request
* @return
*/
@RequestMapping(value = "authCallback")
public void authCallback(HttpServletRequest request) {
String state = request.getParameter("state");
String anchorUuid = state.split("::")[1];
TokenResult result = oauthService.accessToken(request, clientKey, clientSecret);
if (result.getErrorCode() == 0) {
String openId = result.getOpenId();
String accessToken = result.getAccessToken();
// preservation accessToken Wait for the information to cache
stringRedisTemplate.opsForValue().set(douyinTokenKeyPrefix + anchorUuid,
accessToken, 14, TimeUnit.DAYS);
stringRedisTemplate.opsForValue().set(douyinRefreshTokenKeyPrefix + anchorUuid,
result.getRefreshToken(), 29, TimeUnit.DAYS);
logger.info("accessToken===" + accessToken);
anchorService.saveDouyin(accessToken, anchorUuid, openId);
}
}4.3、 according to access_token and open_id You can get the user's basic information and fan statistics
/**
* Get user information
* @param accessToken
* @param openId
* @return
*/
@Override
public JSONObject userInfo(String accessToken,String openId) {
String requestUrl = Urls.BASE_URL+String.format(Urls.USERINFO_URL,accessToken,openId);
JSONObject response = (CommonUtil.httpsRequestJson(requestUrl, "GET", null));
JSONObject object = response.getJSONObject("data");
logger.info("userInfo result=" + response);
return object;
}
/**
* Get user fan data
* @param accessToken
* @param openId
* @return
*/
@Override
public JSONObject fansData(String accessToken,String openId) {
String requestUrl = Urls.BASE_URL+String.format(Urls.FANS_DATA_URL,accessToken,openId);
JSONObject response = (CommonUtil.httpsRequestJson(requestUrl, "GET", null));
JSONObject object = response.getJSONObject("data");
logger.info("fansData result=" + response);
return object;
}The user information interface did not return the number of fans of the user , The number of fans is returned from the fan statistics interface , You can get the number of fans here and save it in the user table , Combined with front-end development , Send the data to the front end and it will be displayed . A beautiful little sister was called here to authorize , Below is a short video screenshot , Just tell me if it looks good .
Basic information of users
Age distribution of fans 、 Regional distribution and gender distribution
Active fan distribution
Fan device distribution
Fan interest distribution
4.4、 according to access_token and open_id All the Tiktok short video data of the user can be obtained
/**
* This interface is used to obtain the data of all videos of the user by paging . The returned data is real-time .
* List published videos
* @param accessToken
* @param openId
* @param cursor
* @param count
* @return
*/
@Override
public JSONObject videoList(String accessToken,String openId,Long cursor,Integer count) {
String requestUrl = Urls.BASE_URL+String.format(Urls.VIDEO_LIST_URL,accessToken,openId,cursor,count);
JSONObject response = (CommonUtil.httpsRequestJson(requestUrl, "GET", null));
logger.info("videoList result=" + response);
return response;
}Just like the number of fans , The open platform does not provide an interface to directly obtain the number of users' works 、 Number of likes 、 Total comments 、 Total shares 、 Average likes 、 The average number of comments 、 Average number of shares , So when we get all the videos, we should calculate these data according to the corresponding fields returned from each video and save them to the database , Combined with front-end development , Send the data to the front end and it will be displayed .
I have to make complaints about it , Like the number of fans 、 Number of works 、 Number of likes 、 Total comments 、 The user related fields such as the total number of shares should be counted and returned in the user information interface , This saves developers a lot of time , And more in line with common sense , I don't know what Tiktok thinks .
5、 summary
5.1、 After reading the code , It's not hard , It is the same as docking with other third-party interfaces , Just follow the document , Always bring up the results . The document of Tiktok open platform is updated , It will look better than before , No matter the layout 、 Note that there are improvements in Parameter annotation , Although still not provided demo download , However, the addition of interface call samples in several languages has no practical effect , But the palm and back of the hand are all meat , Be content .
5.2、 For the first time, the new third-party interfaces are basically connected with pits , Most of the time, we hope that our predecessors who have stepped on the pits can fill them up , Give later people some reference , Little detours , Save time , Increase of efficiency . At first, Tiktok officially established an open platform technology discussion group in Feishu , You can ask questions in it , But the work order platform was launched soon , If the developer has any questions, ask for a work order , Just shut down the flying books . Those who have experience in docking with third-party development should have feelings , The way to submit a work order is to ask how slow it is . Here are some pitfalls encountered in the development process , My friends feel a wave .
- problem : When docking , Modifying the callback domain name requires re auditing , I wonder if the platform has been changed . solve : So to be safe , Or did you fill it out correctly at the beginning , In this regard, the wechat open platform does not need to be reviewed for modifying the callback domain name .
- problem : Doing it OAuth 2.0 Authorization time ,scope Introduce more than one , like this scope=aweme.share,hotsearch,enterprise.data,user_info,fans.list,following.list,fans.data,video.create,video.delete,video.data,video.list,video.comment, Always report “ Illegal permission ”, I can just remove one , After trying many times, I guess it should be scope Is too long. , The last permission was cut off by Tiktok ( such as video.comment Truncated into video.com, and video.com Indeed, it is not a complete permission , So the error of illegal permission is reported ).
solve : And then reacted to the platform , Sure enough, this is one of them bug, Now it's fixed .
- problem : Unstable interface , Sometimes you can , Sometimes you can't . solve : All interface paths , Add... At the end “/”, such as /fans/data/, I don't know why , It was the solution given by the Tiktok staff .
- problem : When calling the authorization QR code , If you need to call back to our interface to carry your own parameters after the user scans the code to confirm authorization due to your own business , it is to be noted that , You cannot splice parameters on the path of a callback interface , Because the callback cannot get , For example, the callback interface path is /mobile/douyin/authCallback, You cannot carry parameters like this /mobile/douyin/authCallback?userId=36781631, This should also be limited by Tiktok , However, wechat scanning authorization can be used to transmit parameters in this way . solve : When scanning the code, you need to pass in a random number for security state, Can be in state Our business parameters are spliced later , And then get... From the callback state Post interception .
边栏推荐
- Hook graphics kernel subsystem
- Common GCC__ attribute__
- 实现TypeScript运行时类型检查
- [go language development] start to develop Meitu station from 0 - Lesson 5 [receive pictures and upload]
- 问题有多大,中台就有多大
- Talk about some good ways to participate in the project
- Why do you develop middleware when you are young? "You can choose your own way"
- Audio knowledge (I)
- TRCT test cloud + article online speed
- Easycvr, an urban intelligent video monitoring image analysis platform, plays national standard equipment videos and captures unstable packets for troubleshooting
猜你喜欢
Using consistent hash algorithm in Presto to enhance the data cache locality of dynamic clusters

Why do you develop middleware when you are young? "You can choose your own way"
![[leetcode108] convert an ordered array into a binary search tree (medium order traversal)](/img/e1/0fac59a531040d74fd7531e2840eb5.jpg)
[leetcode108] convert an ordered array into a binary search tree (medium order traversal)

Daily algorithm & interview questions, 28 days of special training in large factories - the 15th day (string)

MySQL learning -- table structure of SQL test questions
随机推荐
Quick view of product trends in February 2021
Markdown syntax -- Formula
Radiology: contralateral preoperative resting state MRI functional network integration is related to the surgical results of temporal lobe epilepsy
主链系统发展解析
Collect tke logs through daemonset CRD
[go language development] start to develop Meitu station from 0 - Lesson 5 [receive pictures and upload]
Several cloud products of Tencent cloud have passed IPv6 enabled cloud logo certification
Elastic searchable snapshot function (frozen Tier 3)
What is the reason for the worse website SEO ranking?
zblog系统如何根据用户ID获取用户相关信息的教程
Audio knowledge (I)
Jmeter+grafana+influxdb build a visual performance test monitoring platform
Using consistent hash algorithm in Presto to enhance the data cache locality of dynamic clusters
MySQL learning -- table structure of SQL test questions
中金证券靠谱吗?是否合法?开股票账户安全吗?
QQ domain name detection API interface sharing (with internal access automatic jump PHP code)
About with admin option and with grant option
TCB series learning articles - using redis extension in cloud functions
Zabix5.0-0 - agent2 monitoring MariaDB database (Linux based)
Analysis of signal preemptive scheduling based on go language from source code