您现在的位置是:网站首页> 小程序设计
抖音App内H5接入
- 小程序设计
- 2021-06-04
- 1143人已阅读
获得client_token,之类
server.js
// ??注意:本文件内的逻辑请在服务端实现,本Demo只展示用
import axios from 'axios';
import md5 from 'md5';
// 获取 ClientToken
// 详细说明见 http://open-boe.douyin.com/platform/doc/JS-guide
const getClientToken = async ({ client_key, client_secret }) => {
const { data } = await axios.get('/oauth/client_token/', {
params: {
client_key,
client_secret,
grant_type: 'client_credential'
}
});
const { access_token } = data.data || {};
return access_token;
};
// 获取 Ticket
// 详细说明见 http://open-boe.douyin.com/platform/doc/JS-guide
const getTicket = async ({ access_token }) => {
const { data } = await axios.get('/js/getticket', {
params: {
access_token
}
});
const { ticket } = data.data || {};
return ticket;
};
// 计算签名
// 将从服务端获取到的 ticket,随机字串 noncestr,时间戳 timestamp和当前页面url,排序后进行md5加密生成签名
const calcSignature = ({ ticket, nonce_str, timestamp, url }) => {
const str = `jsapi_ticket=${ticket}&nonce_str=${nonce_str}×tamp=${timestamp}&url=${url}`;
const sig = md5(str);
return sig;
};
// 先获取 Client Token,然后通过 Token 获取 JS Ticket
// 详细说明见 https://open.douyin.com/platform/doc/OpenAPI-oauth2
export const getConfigParams = async ({ timestamp, nonce_str, url }) => {
const client_key = ''; // clientKey在你的网页应用申请通过后得到
const client_secret = ''; // clientSecret在你的网页应用申请通过后得到
const access_token = await getClientToken({ client_key, client_secret });
const ticket = await getTicket({ access_token });
const signature = await calcSignature({ ticket, timestamp, nonce_str, url });
return { client_key, signature };
};
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Index from './index.jsx';
ReactDOM.render(
<Index />,
document.getElementById('root')
);
index.jsx
import React, { useState, useEffect, useCallback } from 'react';
import { getConfigParams } from './server';
const { location } = window;
const url = location.href;
const timestamp = String(parseInt(Date.now() / 1000)); // 生成签名用的时间戳
const nonce_str = 'Wm3WZYTPz0wzccnW'; // 生成签名用的随机字符串
const jsb = ''; // 自定义测试用JSB方法名
const params = {}; // 自定义测试用JSB方法参数
export default () => {
const [sdk, setSdk] = useState(null);
const [ready, setReady] = useState(false);
const [configStatus, setConfigStatus] = useState('');
const [resultMsg, setResultMsg] = useState('');
const [client_key, setClientKey] = useState('');
// 打开原生授权页面JSB能力示例
const onClickAuth = () => {
if (ready) {
sdk.jumpOpenAuth({
params: {
client_key,
redirect_uri: location.href,
state: '',
scope: 'user_info',
response_type: 'code'
},
success: ({ ticket }) => setResultMsg(`Auth Success: ${ticket}`),
error: res => setResultMsg(`Auth Error: ${JSON.stringify(res)}`)
});
}
};
// 可在URL参数中自定义JSB方法名和参数以测试
const onClickJSB = () => {
if (ready) {
sdk[jsb]({
params,
success: res => setResultMsg(`JSB ${jsb} Success: ${JSON.stringify(res)}`),
error: res => setResultMsg(`JSB ${jsb} Error: ${JSON.stringify(res)}`)
});
}
};
// 使用JSB能力前,必须先通过Config验证签名
const config = useCallback(async () => {
const { client_key, signature } = await getConfigParams({ timestamp, nonce_str, url });
sdk.config({
params: {
client_key,
signature,
timestamp,
nonce_str,
url
}
});
setClientKey(client_key);
}, [sdk]);
useEffect(() => {
setSdk(window.douyin_open);
if (sdk) {
setConfigStatus('SDK Loaded');
config();
sdk.ready(() => {
setReady(true);
setConfigStatus('SDK Config Ready');
});
sdk.error(res => {
setConfigStatus(`SDK Config Error: ${JSON.stringify(res)}`);
});
}
}, [sdk, config]);
return (
<>
<p onClick={() => location.reload()} className="link">{'Reload'}</p>
<p>{configStatus} </p>
{
!ready ? <p>Loading...</p> : (
<>
<p onClick={onClickAuth} className="link">Auth</p>
{jsb && <p onClick={onClickJSB} className="link" style={{ textTransform: 'capitalize' }}>{jsb}</p>}
</>
)
}
<p>{resultMsg}</p>
</>
);
};