返回 AiToEarn
signature.js
根目录 / demo / xhs / signature.js
1 import axios from "axios";
2 import crypto from "crypto-js"
3 const appKey = "red.gLvsVoksierVz0uF";
4 const appSecret = "f13a2266d1e2c32a553cb7a42ea63c48";
5 let cachedAccessToken = null;
6 let accessTokenExpiresAt = 0; // 记录 access_token 过期时间
7
8 // 生成小红书签名
9 function generateSignature(appKey, nonce, timeStamp, appSecret) {
10 const params = {
11 appKey,
12 nonce,
13 timeStamp,
14 };
15 const sortedParams = Object.keys(params)
16 .sort()
17 .map((key) => `${key}=${params[key]}`)
18 .join("&");
19 const stringToSign = sortedParams + appSecret;
20 console.log(stringToSign);
21 return crypto.SHA256(stringToSign).toString();
22 }
23
24 // 获取小红书access_token
25 const getAccessToken = async (nonce, timestamp) => {
26 if (cachedAccessToken && Date.now() < accessTokenExpiresAt) {
27 // 如果 access_token 未过期,则直接返回缓存的 token
28 return cachedAccessToken;
29 }
30
31 const signature = generateSignature(appKey, nonce, timestamp, appSecret);
32 console.log({
33 app_key: appKey,
34 nonce: nonce,
35 timestamp: timestamp,
36 signature: signature,
37 });
38 try {
39 const response = await axios.post("https://edith.xiaohongshu.com/api/sns/v1/ext/access/token", {
40 app_key: appKey,
41 nonce: nonce,
42 timestamp: timestamp,
43 signature: signature,
44 }, {
45 headers: {
46 "Content-Type": "application/json",
47 },
48 });
49 console.log(response.data);
50 const { access_token, expires_in } = response.data.data;
51
52 // 缓存 access_token 和计算过期时间
53 cachedAccessToken = access_token;
54 accessTokenExpiresAt = expires_in;
55
56 return cachedAccessToken;
57 } catch (error) {
58 console.error('请求失败:', error);
59 throw error; // 处理错误
60 }
61 };
62
63 const nonce = Math.random().toString(36).substring(2);
64 const timestamp = Date.now();
65 const accessToken = await getAccessToken(nonce, timestamp);
66 const signature = generateSignature(appKey, nonce, timestamp, accessToken);
67 console.log("appKey:", appKey);
68 console.log("nonce:", nonce);
69 console.log("timestamp:", timestamp);
70 console.log("signature:", signature);
71
71 lines JAVASCRIPT