Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: 1. 更改和添加请求器。 2. 通用 验证码/手机号登录组件开发。
gaoSir0cb25a6cfb98
diff --git a/eslint.config.mjs b/eslint.config.mjsindex 143326e7..da6e1b3c 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -10,37 +10,29 @@ const compat = new FlatCompat({});const eslintConfig = [+ ...compat.extends(+ "next/core-web-vitals",+ "next/typescript",+ "plugin:prettier/recommended",+ "plugin:@typescript-eslint/recommended",+ ),+ ...compat.plugins(+ '@typescript-eslint/eslint-plugin',+ 'unused-imports',+ "eslint-plugin-react"+ ),{rules: {- // 禁用所有规则'@typescript-eslint/interface-name-prefix': 'off','@typescript-eslint/explicit-function-return-type': 'off','@typescript-eslint/explicit-module-boundary-types': 'off','@typescript-eslint/no-explicit-any': 'off',- 'unused-imports/no-unused-imports': 'off',- '@typescript-eslint/no-empty-object-type': 'off',- '@typescript-eslint/no-unused-vars': 'off',- 'prettier/prettier': 'off',- '@typescript-eslint/ban-ts-comment': 'off',- 'react/react-in-jsx-scope': 'off',- 'react/prop-types': 'off',- 'react/display-name': 'off',- 'react/jsx-key': 'off',- 'react/jsx-no-target-blank': 'off',- 'react/jsx-no-undef': 'off',- 'react/jsx-uses-react': 'off',- 'react/jsx-uses-vars': 'off',- 'react/no-children-prop': 'off',- 'react/no-danger': 'off',- 'react/no-deprecated': 'off',- 'react/no-direct-mutation-state': 'off',- 'react/no-find-dom-node': 'off',- 'react/no-is-mounted': 'off',- 'react/no-render-return-value': 'off',- 'react/no-string-refs': 'off',- 'react/no-unknown-property': 'off',- 'react/require-render-return': 'off',- 'react/self-closing-comp': 'off',+ "unused-imports/no-unused-imports": "error",+ "@typescript-eslint/no-empty-object-type": "off",+ "@typescript-eslint/no-unused-vars": "warn",+ "prettier/prettier": ["error", { "endOfLine": "auto" }],+ "@typescript-eslint/ban-ts-comment": "off",+ "react-hooks/rules-of-hooks": "off",},}];diff --git a/next.config.mjs b/next.config.mjsindex e0a1fa57..6b655809 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -3,7 +3,11 @@ const nextConfig = {sassOptions: {includePaths: ['./app', '*.scss'],prependData: `@import "@/app/styles/mixin.scss";`,- }+ },+ reactStrictMode: false,+ experimental: {+ forceSwcTransforms: true,+ },};const CorsHeaders = [@@ -38,6 +42,18 @@ nextConfig.rewrites = async () => {source: `${process.env.NEXT_PUBLIC_API_URL_PROXY}:path*`,destination: `${process.env.NEXT_PUBLIC_API_URL}:path*`,},+ {+ source: `/xhsXS/:path*`,+ destination: `http://116.62.154.231:7879/:path*`,+ },+ {+ source: `/xiaohongshu/:path*`,+ destination: `https://edith.xiaohongshu.com/api/:path*`,+ },+ {+ source: `/platapiProxy/:path*`,+ destination: `https://platapi.yikart.cn/api/:path*`+ }];return {diff --git a/src/app/[lng]/accounts/components/AddAccountModal.tsx b/src/app/[lng]/accounts/components/AddAccountModal.tsxdeleted file mode 100644index ad7eb709..00000000--- a/src/app/[lng]/accounts/components/AddAccountModal.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { ForwardedRef, forwardRef, memo } from "react";-import styles from "./AddAccountModal.module.scss";-import { Button, Modal, Tooltip } from "antd";-// import { accountLogin } from "@/icp/account";-import { AccountPlatInfoArr } from "@/app/config/platConfig";-import { SocialAccount } from "@/api/types/account.type";--export interface IAddAccountModalRef {}--export interface IAddAccountModalProps {- open: boolean;- onClose: () => void;- onAddSuccess: (accountInfo: SocialAccount) => void;-}--const AddAccountModal = memo(- forwardRef(- (- { open, onClose, onAddSuccess }: IAddAccountModalProps,- ref: ForwardedRef<IAddAccountModalRef>,- ) => {- const handleOk = () => {- onClose();- };-- const handleCancel = () => {- onClose();- };-- return (- <Modal- title="账号添加"- open={open}- onOk={handleOk}- onCancel={handleCancel}- footer={null}- width={650}- >- <div className={styles.addAccountModal}>- <h1>选择平台添加账号</h1>- <div className="addAccountModal_plats">- {AccountPlatInfoArr.map(([key, value]) => {- return (- <Tooltip title={value.tips?.account} key={key}>- <Button- type="text"- className="addAccountModal_plats-item"- onClick={async () => {- // TODO 账号登录逻辑- // const res = await accountLogin(key);- // if (!res) return;- // message.success("账号添加成功");- // onAddSuccess(res);- }}- >- <div className="addAccountModal_plats-item-con">- {/*<LoadingOutlined style={{ fontSize: '20px' }} />*/}- <img src={value.icon} />- <span>{value.name}</span>- </div>- </Button>- </Tooltip>- );- })}- </div>- </div>- </Modal>- );- },- ),-);-AddAccountModal.displayName = "AddAccountModal";--export default AddAccountModal;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout/accountLoginLyaout.module.scss b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout/accountLoginLyaout.module.scssnew file mode 100644index 00000000..7ce8b0a1--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout/accountLoginLyaout.module.scss@@ -0,0 +1,66 @@+.accountLoginLyaout {+ display: flex;+ :global {+ .accountLoginLyaout-right, .accountLoginLyaout-left {+ height: 400px;+ display: flex;+ flex-direction: column;+ width: 50%;+ }+ .accountLoginLyaout-left {+ align-items: center;+ justify-content: center;+ &-qRCode {+ width: 156px;+ height: 156px;+ padding: 10px;+ background: var(--grayColor0);+ position: relative;+ img {+ border-radius: 7px;+ width: 100%;+ height: 100%;+ }+ &-expire {+ position: absolute;+ width: 100%;+ height: 100%;+ top: 0;+ left: 0;+ background: rgba(255, 255, 255, 0.9);+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ span {+ font-weight: 900;+ color: var(--error-color);+ }+ a {+ margin-top: 5px;+ }+ }+ }+ &-tips {+ margin-top: 20px;+ color: var(--grayColor8);+ font-size: var(--fs-md);+ }+ }+ .accountLoginLyaout-right {+ padding: 40px 50px 0;+ border-left: 1px solid var(--grayColor2);+ h2 {+ font-size: var(--fs-lg);+ text-align: center;+ margin-bottom: 40px;+ }+ input {+ height: 40px;+ }+ .ant-form {+ width: 100%;+ }+ }+ }+}\ No newline at end of filediff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout/index.tsx b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout/index.tsxnew file mode 100644index 00000000..9b986022--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout/index.tsx@@ -0,0 +1,137 @@+"use client";++import { ForwardedRef, forwardRef, memo } from "react";+import styles from "./accountLoginLyaout.module.scss";+import { Button, Form, Input, Spin } from "antd";+import { phoneReg } from "@/utils/regulars";+import GetCode from "@/components/GetCode/GetCode";++export interface IAccountLoginInfo {+ phone: string;+ code: string;+}++export interface IAccountLoginLyaoutRef {}++export interface IAccountLoginLyaoutProps {+ // 获取二维码loading+ qRCodeLoading: boolean;+ // 二维码是否过期+ isQRCodeExpire?: boolean;+ // 二维码过期后刷新二维码+ onFlushQRCode?: () => void;+ // 二维码URL+ qRCodeUrl: string;+ // 二维码提示信息+ qRCodeTips?: string;+ // 手机号登录配置+ phoneConfig?: {+ // 下次发送验证码时间+ codeSendTime: number;+ // 点击验证码发送事件+ onCodeSend: (phone: string) => void;+ // 点击登录事件+ onLogin: (p: IAccountLoginInfo) => void;+ // 登录loding+ loading: boolean;+ };+}++const AccountLoginLyaout = memo(+ forwardRef(+ (+ {+ qRCodeTips,+ qRCodeUrl,+ phoneConfig,+ isQRCodeExpire = false,+ qRCodeLoading,+ onFlushQRCode,+ }: IAccountLoginLyaoutProps,+ ref: ForwardedRef<IAccountLoginLyaoutRef>,+ ) => {+ const [form] = Form.useForm();++ return (+ <div className={styles.accountLoginLyaout}>+ <div className="accountLoginLyaout-left">+ <Spin+ spinning={qRCodeLoading}+ wrapperClassName="accountLoginLyaout-left-qRCode"+ >+ {qRCodeUrl && <img src={qRCodeUrl} />}+ {isQRCodeExpire && (+ <div className="accountLoginLyaout-left-qRCode-expire">+ <span>二维码已过期</span>+ <a onClick={onFlushQRCode}>点击刷新</a>+ </div>+ )}+ </Spin>+ {qRCodeTips && (+ <p className="accountLoginLyaout-left-tips">{qRCodeTips}</p>+ )}+ </div>+ {phoneConfig && (+ <div className="accountLoginLyaout-right">+ <h2>手机号登录</h2>+ <Form+ form={form}+ onFinish={(params) => {+ phoneConfig!.onLogin(params);+ }}+ >+ <Form.Item<IAccountLoginInfo>+ name="phone"+ rules={[+ { required: true, message: "请输入手机号" },+ {+ pattern: phoneReg,+ message: "手机号格式错误,请重新输入",+ },+ ]}+ >+ <Input placeholder="请输入您的手机号码" />+ </Form.Item>++ <div style={{ position: "relative", height: "40px" }}>+ <Form.Item<IAccountLoginInfo>+ name="code"+ rules={[{ required: true, message: "验证码不能为空" }]}+ >+ <Input placeholder="请输入您的验证码" />+ </Form.Item>+ <GetCode+ codeSendTime={phoneConfig!.codeSendTime}+ onGetCode={async (unlock) => {+ const validateRes = await form+ .validateFields(["phone"])+ .catch(() => unlock());+ if (!validateRes) return;+ phoneConfig!.onCodeSend(form.getFieldValue("phone"));+ }}+ />+ </div>++ <Form.Item+ wrapperCol={{ offset: 0 }}+ style={{ marginTop: "50px" }}+ >+ <Button+ htmlType="submit"+ type="primary"+ style={{ width: "100%", padding: "18px 0" }}+ loading={phoneConfig.loading}+ >+ 登录+ </Button>+ </Form.Item>+ </Form>+ </div>+ )}+ </div>+ );+ },+ ),+);++export default AccountLoginLyaout;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type.ts b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type.tsnew file mode 100644index 00000000..9574957b--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type.ts@@ -0,0 +1,3 @@+export interface IAccountLoginPlatProps {+ onLoginSuccess: (cookie: string) => void;+}diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/index.tsx b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/index.tsxnew file mode 100644index 00000000..d18dc2d7--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/index.tsx@@ -0,0 +1,67 @@+"use client";++import { ForwardedRef, forwardRef, memo, useMemo } from "react";+import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";+import DouyinLogin from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/DouyinLogin";+import WxSphLogin from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/WxSphLogin";+import XhsLogin from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/XhsLogin";+import { Modal } from "antd";+import KwaiLogin from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/KwaiLogin";++export interface IAccountLoginRef {}++export interface IAccountLoginProps {+ plat: PlatType;+ open: boolean;+ onLoginSuccess: (cookie: string) => void;+ onCancel: () => void;+}++const AccountLogin = memo(+ forwardRef(+ (+ { plat, open, onLoginSuccess, onCancel }: IAccountLoginProps,+ ref: ForwardedRef<IAccountLoginRef>,+ ) => {+ const platInfo = useMemo(() => {+ return (+ AccountPlatInfoMap.get(plat) ||+ AccountPlatInfoMap.get(PlatType.Douyin)!+ );+ }, [plat]);++ const Plat = useMemo(() => {+ switch (plat) {+ case PlatType.Douyin:+ return DouyinLogin;+ case PlatType.WxSph:+ return WxSphLogin;+ case PlatType.Xhs:+ return XhsLogin;+ case PlatType.KWAI:+ return KwaiLogin;+ }+ }, [plat]);++ return (+ <>+ <Modal+ title={`${platInfo.name}登录`}+ open={open}+ onCancel={onCancel}+ footer={null}+ width={800}+ >+ <Plat+ onLoginSuccess={() => {+ console.log("登录");+ }}+ />+ </Modal>+ </>+ );+ },+ ),+);++export default AccountLogin;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/DouyinLogin.tsx b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/DouyinLogin.tsxnew file mode 100644index 00000000..e77acc32--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/DouyinLogin.tsx@@ -0,0 +1,16 @@+"use client";++import { ForwardedRef, forwardRef, memo } from "react";+import { IAccountLoginPlatProps } from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type";++export interface IDouyinLoginRef {}++const DouyinLogin = memo(+ forwardRef(+ ({}: IAccountLoginPlatProps, ref: ForwardedRef<IDouyinLoginRef>) => {+ return <div></div>;+ },+ ),+);++export default DouyinLogin;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/KwaiLogin.tsx b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/KwaiLogin.tsxnew file mode 100644index 00000000..22cac04f--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/KwaiLogin.tsx@@ -0,0 +1,14 @@+"use client";++import { ForwardedRef, forwardRef, memo } from "react";+import { IAccountLoginPlatProps } from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type";++export interface IKwaiLoginRef {}++const KwaiLogin = memo(+ forwardRef(({}: IAccountLoginPlatProps, ref: ForwardedRef<IKwaiLoginRef>) => {+ return <div></div>;+ }),+);++export default KwaiLogin;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/WxSphLogin.tsx b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/WxSphLogin.tsxnew file mode 100644index 00000000..c1df8b69--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/WxSphLogin.tsx@@ -0,0 +1,16 @@+"use client";++import { ForwardedRef, forwardRef, memo } from "react";+import { IAccountLoginPlatProps } from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type";++export interface IWxSphLoginRef {}++const WxSphLogin = memo(+ forwardRef(+ ({}: IAccountLoginPlatProps, ref: ForwardedRef<IWxSphLoginRef>) => {+ return <div></div>;+ },+ ),+);++export default WxSphLogin;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/XhsLogin.tsx b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/XhsLogin.tsxnew file mode 100644index 00000000..52af6249--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/plats/XhsLogin.tsx@@ -0,0 +1,58 @@+"use client";++import { ForwardedRef, forwardRef, memo, useEffect, useState } from "react";+import { IAccountLoginPlatProps } from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/accountLogin.type";+import styles from "../styles/xhsLogin.module.scss";+import { requestPlatApi } from "@/utils/otherRequest";+import AccountLoginLyaout from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin/AccountLoginLyaout";++export interface IXhsLoginRef {}++const XhsLogin = memo(+ forwardRef(({}: IAccountLoginPlatProps, ref: ForwardedRef<IXhsLoginRef>) => {+ const [qsImg, setQsImg] = useState("");+ const [qRCodeLoading, setQRCodeLoading] = useState(false);+ const [isQRCodeExpire, setIsQRCodeExpire] = useState(false);+ const [loginLoading, setLoginLoading] = useState(false);++ useEffect(() => {+ getLoginQRCode();+ }, []);++ const getLoginQRCode = () => {+ setQRCodeLoading(true);+ requestPlatApi({+ url: "xhs/login_qr_code",+ method: "POST",+ }).then((res) => {+ if (qRCodeLoading) return;+ setQRCodeLoading(false);+ setQsImg("data:image/png;base64," + res.data.base64_qr_code);+ });+ };++ return (+ <div className={styles.xhsLogin}>+ <AccountLoginLyaout+ qRCodeLoading={qRCodeLoading}+ qRCodeUrl={qsImg}+ phoneConfig={{+ codeSendTime: 180,+ onCodeSend: (phone: string) => {+ console.log(phone);+ },+ onLogin: (params) => {+ console.log(params);+ },+ loading: loginLoading,+ }}+ qRCodeTips="可用小红书或微信扫码"+ isQRCodeExpire={isQRCodeExpire}+ onFlushQRCode={getLoginQRCode}+ />+ </div>+ );+ }),+);++export default XhsLogin;diff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/styles/accountLogin.module.scss b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/styles/accountLogin.module.scssnew file mode 100644index 00000000..e69de29bdiff --git a/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/styles/xhsLogin.module.scss b/src/app/[lng]/accounts/components/AddAccountModal/AccountLogin/styles/xhsLogin.module.scssnew file mode 100644index 00000000..e69de29bdiff --git a/src/app/[lng]/accounts/components/AddAccountModal/index.tsx b/src/app/[lng]/accounts/components/AddAccountModal/index.tsxnew file mode 100644index 00000000..7c1d6f27--- /dev/null+++ b/src/app/[lng]/accounts/components/AddAccountModal/index.tsx@@ -0,0 +1,87 @@+import { ForwardedRef, forwardRef, memo, useState } from "react";+import styles from "../AddAccountModal.module.scss";+import { Button, Modal, Tooltip } from "antd";+import { AccountPlatInfoArr, PlatType } from "@/app/config/platConfig";+import { SocialAccount } from "@/api/types/account.type";+import AccountLogin from "@/app/[lng]/accounts/components/AddAccountModal/AccountLogin";++export interface IAddAccountModalRef {}++export interface IAddAccountModalProps {+ open: boolean;+ onClose: () => void;+ onAddSuccess: (accountInfo: SocialAccount) => void;+}++const AddAccountModal = memo(+ forwardRef(+ (+ { open, onClose, onAddSuccess }: IAddAccountModalProps,+ ref: ForwardedRef<IAddAccountModalRef>,+ ) => {+ const [accountLoginOpen, setAccountLoginOpen] = useState(false);+ const [addPlat, setAddPlat] = useState<PlatType>();++ const handleOk = () => {+ onClose();+ };++ const handleCancel = () => {+ onClose();+ };++ return (+ <>+ {addPlat && (+ <AccountLogin+ open={accountLoginOpen}+ plat={addPlat!}+ onLoginSuccess={(cookie) => {+ console.log("登录完成:", cookie);+ }}+ onCancel={() => setAccountLoginOpen(false)}+ />+ )}++ <Modal+ title="账号添加"+ open={open}+ onOk={handleOk}+ onCancel={handleCancel}+ footer={null}+ width={650}+ >+ <div className={styles.addAccountModal}>+ <h1>选择平台添加账号</h1>+ <div className="addAccountModal_plats">+ {AccountPlatInfoArr.map(([key, value]) => {+ return (+ <Tooltip title={value.tips?.account} key={key}>+ <Button+ type="text"+ className="addAccountModal_plats-item"+ onClick={async () => {+ setAddPlat(key);+ setAccountLoginOpen(true);+ }}+ >+ <div className="addAccountModal_plats-item-con">+ {/*<LoadingOutlined style={{ fontSize: '20px' }} />*/}+ <img src={value.icon} />+ <span>{value.name}</span>+ </div>+ </Button>+ </Tooltip>+ );+ })}+ </div>+ </div>+ </Modal>+ </>+ );+ },+ ),+);+AddAccountModal.displayName = "AddAccountModal";++export default AddAccountModal;diff --git a/src/app/[lng]/page.tsx b/src/app/[lng]/page.tsxindex 00f65515..13799221 100644--- a/src/app/[lng]/page.tsx+++ b/src/app/[lng]/page.tsx@@ -1,29 +1,144 @@"use client";import styles from "@/app/styles/page.module.scss";-import React, {useState} from "react";-import {Button, Input} from "antd";+import React, {useEffect, useRef, useState} from "react";+import { Button, Input } from "antd";++// 等待n毫秒+function sleep(ms: number) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}export default function Home() {- const [phone, setPhone] = useState('');- const [code, setCode] = useState('');-- return <div className={styles.page}>- <Input placeholder="手机号" onChange={(e) => setPhone(e.target.value)} />- <Input placeholder="验证码" onChange={(e) => setCode(e.target.value)} />- <Button onClick={async () => {- const req = await fetch(`https://edith.xiaohongshu.com/api/sns/web/v2/login/send_code?phone=${phone}&zone=86&type=login`, {- method: 'GET',- headers: {- origin: 'https://www.xiaohongshu.com',- referer: "https://www.xiaohongshu.com/"- }- })+ const [phone, setPhone] = useState("");+ const [code, setCode] = useState("");+ const [qsImg, setQsImg] = useState("");+ const flag = useRef(false);++ useEffect(() => {+ (async () => {+ if (flag.current) return;+ flag.current = true;+ const req = await fetch(+ `https://platapi.yikart.cn/api/xhs/login_qr_code`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json;charset=UTF-8",+ },+ },+ );const res = await req.json();- console.log(res)- }}>发送验证码</Button>- <Button onClick={() => {+ setQsImg(+ "data:image/png;base64," + res.data.response_body.data.base64_qr_code,+ );+ document.cookie = res.data.response_body.data.cookie;+ // console.log()++ while (true) {+ const req2 = await fetch(+ `https://platapi.yikart.cn/api/xhs/check_login`,+ {+ method: "POST",+ // headers: {+ // "Content-Type": "application/json",+ // },+ body: JSON.stringify({+ code: res.data.response_body.data.code,+ qr_id: res.data.response_body.data.qr_id,+ cookie: res.data.response_body.data.cookie,+ }),+ },+ );+ await sleep(3000);+ const res2 = await req2.json();+ if (res2.data.response_body.data.code_status === 2) {+ console.log(res.data.response_body.data);+ break;+ }+ }+ })();+ }, []);++ return (+ <div className={styles.page}>+ <img src={qsImg} />++ <Input placeholder="手机号" onChange={(e) => setPhone(e.target.value)} />+ <Input placeholder="验证码" onChange={(e) => setCode(e.target.value)} />+ <Button+ onClick={async () => {+ const req = await fetch(`/xhsXS/`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json;charset=UTF-8",+ },+ body: JSON.stringify({+ url: `/api/sns/web/v2/login/send_code?phone=${phone}&zone=86&type=login`,+ cookie: document.cookie,+ }),+ });+ const xsRes = await req.json();++ const req1 = await fetch(+ `/xiaohongshu/sns/web/v2/login/send_code?phone=${phone}&zone=86&type=login`,+ {+ method: "GET",+ headers: {+ "x-s":+ "XYS_2UQhPsHCH0c1PjhIHjIj2erjwjQhyoPTqBPT49pjHjIj2eHjwjQgynEDJ74AHjIj2ePjwjQTJdPIP/ZlgMrU4SmH4ebwGFqE4pzEzrk9weHMnLMea0zH4Dk0//W3PMrUaDMeGnMzJgkO+gz+GdiI/9RynBRYzAZF8fuI/DSMG/zC+LkPaoW7cMP6PMkB+fS98Dl9N9FM+/zS+A8CnpP78BRdGMkxJBbS8omec0bfaLz3PrlhwnEhyLTIGnkeaDzPLnkSP7G38fT64A8j+dmTzflfLBT6+L+0zMb8+7zS4BL98fTfPBY+HjIj2ecjwjHjKc==",+ },+ },+ );+ console.log(req1);++ // const req = await fetch(+ // `https://platapi.yikart.cn/api/xhs/send_code`,+ // {+ // method: "POST",+ // body: JSON.stringify({+ // mobile: phone,+ // }),+ // },+ // );+ const res = await req.json();+ console.log(res);+ }}+ >+ 发送验证码+ </Button>+ <Button+ onClick={async () => {+ const req = await fetch(`/xhsXS/`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json;charset=UTF-8",+ },+ body: JSON.stringify({+ url: `/api/sns/web/v1/login/check_code?phone=17600917357&zone=86&code=123`,+ a1: `a1=1953cfa200duqccg24dtw9u1y7ubred8l9iyg1y0150000466896; webId=76f7ec5c74e78c5756fabe7b987c66bf; gid=yj2qSi0JD41Syj2qSi0J8jyv8f7ASSkJ4f9E38yj7yvW7v28DFdfYk8884KKYjK8qWDiq08i; customerClientId=412120289436764; abRequestId=76f7ec5c74e78c5756fabe7b987c66bf; x-user-id-ad-market.xiaohongshu.com=678df12c0000000004030ab9; x-user-id-creator.xiaohongshu.com=682851d50000000007000633; webBuild=4.64.0; customer-sso-sid=68c517509396918886050316tyy59dfmmpqjfyuw; access-token-creator.xiaohongshu.com=customer.creator.AT-68c517509396918886366307e9ezes1g34kgpku9; galaxy_creator_session_id=PljCqPggTFa0xI1sODUoiGq1qTakQPVXYthl; galaxy.creator.beaker.session.id=1748417718742000985340; xsecappid=xhs-pc-web; web_session=030037a0f3697c3b8debfc944e2f4a079bd40a; acw_tc=0a4adcd017484235263232839e9108cd2acbb581623e024122e2088ccbe8fe; websectiga=a9bdcaed0af874f3a1431e94fbea410e8f738542fbb02df1e8e30c29ef3d91ac; sec_poison_id=9ea1d95c-e767-4e55-8729-1ed51458d67e; loadts=1748424559788; unread={%22ub%22:%2268118988000000001201c272%22%2C%22ue%22:%2268169150000000002101ad9a%22%2C%22uc%22:29}`,+ }),+ });++ const xsRes = await req.json();+ const req2 = await fetch(+ `/xiaohongshu/sns/web/v1/login/check_code?phone=${phone}&zone=86&code=${code}`,+ {+ method: "GET",+ headers: {+ "x-s": xsRes["X-s"],+ },+ },+ );- }}>登录</Button>- </div>;+ const req3 = await fetch(`/xiaohongshu/sns/web/v2/login/code`, {+ method: "POST",+ headers: {},+ });+ }}+ >+ 登录+ </Button>+ </div>+ );}diff --git a/src/app/plat/PlatBase.ts b/src/app/plat/PlatBase.tsnew file mode 100644index 00000000..2f97607c--- /dev/null+++ b/src/app/plat/PlatBase.ts@@ -0,0 +1,5 @@+import { SocialAccount } from "@/api/types/account.type";++export abstract class PlatBase {+ abstract login(): Promise<SocialAccount>;+}diff --git a/src/app/plat/PlatManage.ts b/src/app/plat/PlatManage.tsnew file mode 100644index 00000000..2e8bc026--- /dev/null+++ b/src/app/plat/PlatManage.ts@@ -0,0 +1,3 @@+class PlatManage {+ getPlat() {}+}diff --git a/src/app/plat/plat.type.ts b/src/app/plat/plat.type.tsnew file mode 100644index 00000000..e69de29bdiff --git a/src/components/GetCode/GetCode.tsx b/src/components/GetCode/GetCode.tsxnew file mode 100644index 00000000..23ad9484--- /dev/null+++ b/src/components/GetCode/GetCode.tsx@@ -0,0 +1,63 @@+import { useRef, useState } from "react";+import { Statistic } from "antd";+import styles from "./getCode.module.scss";++const { Timer } = Statistic;++function GetCode({+ onGetCode,+ codeSendTime = 60,+}: {+ onGetCode: (unlock: () => void) => void;+ codeSendTime?: number;+}) {+ const [isCode, setIsCode] = useState(false);+ const currTime = useRef(0);++ const lockCode = () => {+ setIsCode(true);+ currTime.current = codeSendTime * 1000;+ };++ return (+ <label+ className={+ styles["loginForm-getCode"] ++ ` ${isCode ? styles["loginForm-getCode--disable"] : ""}`+ }+ onClick={() => {+ if (isCode) return;+ lockCode();+ onGetCode(() => {+ setIsCode(false);+ });+ }}+ >+ 获取验证码+ {isCode ? (+ <>+ (+ <Timer+ type="countdown"+ format="ss"+ value={Date.now() + currTime.current}+ precision={1}+ onFinish={() => {+ setIsCode(false);+ }}+ onChange={(e) => {+ if (typeof e === "number") {+ currTime.current = e;+ }+ }}+ />+ s)+ </>+ ) : (+ ""+ )}+ </label>+ );+}++export default GetCode;diff --git a/src/components/GetCode/getCode.module.scss b/src/components/GetCode/getCode.module.scssnew file mode 100644index 00000000..a5504708--- /dev/null+++ b/src/components/GetCode/getCode.module.scss@@ -0,0 +1,34 @@+.loginForm-getCode {+ color: var(--colorPrimary5);+ position: absolute;+ top: 50%;+ transform: translateY(-50%);+ right: 20px;+ cursor: pointer;+ display: flex;+ align-items: center;+ font-size: 14px;++ &:hover {+ color: var(--colorPrimary4);+ }+ &:active {+ color: var(--colorPrimary6);+ }++ :global {+ .ant-statistic-content {+ display: flex;+ align-items: center;+ }+ span {+ font-size: 14px;+ font-weight: 400;+ color: var(--colorPrimary5);+ }+ }+}++.loginForm-getCode--disable {+ cursor: no-drop;+}\ No newline at end of filediff --git a/src/constant.ts b/src/constant.tsindex 9d17623b..f546b1b3 100644--- a/src/constant.ts+++ b/src/constant.ts@@ -1,2 +1,10 @@// api urlexport const APP_HOT_URL = "https://att-contents.yikart.cn/api";++// 代理地址+export const ProxyUrls = [+ process.env.NEXT_PUBLIC_API_URL_PROXY,+ "/xhsXS",+ "/xiaohongshu/",+ "/platapiProxy/"+];diff --git a/src/middleware.ts b/src/middleware.tsindex 6ebc8a07..5e2bd085 100644--- a/src/middleware.ts+++ b/src/middleware.ts@@ -1,6 +1,7 @@import { NextResponse, NextRequest } from "next/server";import acceptLanguage from "accept-language";import { fallbackLng, languages, cookieName } from "@/app/i18n/settings";+import { ProxyUrls } from "@/constant";acceptLanguage.languages(languages);@@ -12,7 +13,7 @@ export const config = {};export function middleware(req: NextRequest) {- if (req.nextUrl.pathname.includes(process.env.NEXT_PUBLIC_API_URL_PROXY!)) {+ if (ProxyUrls.find((v) => req.nextUrl.pathname.includes(v!))) {return NextResponse.next();}diff --git a/src/types/publish.ts b/src/types/publish.tsindex 6f6f23fa..b37d5ef8 100644--- a/src/types/publish.ts+++ b/src/types/publish.ts@@ -1,7 +1,7 @@export enum PubType {- VIDEO = 'video', // 视频- ARTICLE = 'article', // 文章- IMAGE_TEXT = 'image-text', // 图文+ VIDEO = "video", // 视频+ ARTICLE = "article", // 文章+ IMAGE_TEXT = "image-text", // 图文}export enum PubStatus {@@ -12,4 +12,4 @@ export enum PubStatus {}export type PublishType = `${PubType}`;-export type PublishStatus = `${PubStatus}`;\ No newline at end of file+export type PublishStatus = `${PubStatus}`;diff --git a/src/utils/otherRequest.ts b/src/utils/otherRequest.tsnew file mode 100644index 00000000..a676d06e--- /dev/null+++ b/src/utils/otherRequest.ts@@ -0,0 +1,29 @@+import FetchService from "@/utils/FetchService/FetchService";+import { RequestParams } from "@/utils/FetchService/types";++class OtherRequest {+ fetchService;++ constructor(baseURL: string) {+ this.fetchService = new FetchService({+ baseURL,+ requestInterceptor(requestParams) {+ return requestParams;+ },+ responseInterceptor(response) {+ return response;+ },+ });+ }++ async request<T = any>(params: RequestParams) {+ const res = await this.fetchService.request(params);+ return (await res.json()) as T;+ }+}++const requestPlatapi = new OtherRequest("https://platapi.yikart.cn/api/");+export async function requestPlatApi<T = any>(params: RequestParams) {+ const res = await requestPlatapi.request(params);+ return res.data.response_body as T;+}diff --git a/src/utils/regulars.ts b/src/utils/regulars.tsnew file mode 100644index 00000000..9120920c--- /dev/null+++ b/src/utils/regulars.ts@@ -0,0 +1,10 @@+// 身份证号校验正则+export const idNumberReg =+ /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/;++// 手机号正则验证+export const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/;++// 邮箱验证+export const emailReg =+ /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;diff --git a/src/utils/request.ts b/src/utils/request.tsindex 8d4ad69a..3de505dc 100644--- a/src/utils/request.ts+++ b/src/utils/request.ts@@ -2,7 +2,6 @@ import FetchService from "@/utils/FetchService/FetchService";import { RequestParams } from "@/utils/FetchService/types";import { useUserStore } from "@/store/user";import { message } from "antd";-import {APP_HOT_URL} from "@/constant";type ResponseType<T> = {code: string | number;@@ -11,77 +10,52 @@ type ResponseType<T> = {url: string;};-class RequestClient {- fetchService: FetchService<Response>- isLogin: boolean;+const fetchService = new FetchService({+ baseURL: `${process.env.NEXT_PUBLIC_API_URL_PROXY}`,+ requestInterceptor(requestParams) {+ const token = useUserStore.getState().token;- /**- * @param baseURL- * @param isLogin 是否需要token,以及是否需要检测返回值的过期状态- */- constructor(baseURL: string, isLogin: boolean = false) {- this.isLogin = isLogin;+ requestParams.headers = {+ ...(requestParams["headers"] || {}),+ Authorization: token ? `Bearer ${token}` : "",+ };- this.fetchService = new FetchService({- baseURL,- requestInterceptor(requestParams) {-- if (isLogin) {- const token = useUserStore.getState().token;-- requestParams.headers = {- ...(requestParams["headers"] || {}),- Authorization: token ? `Bearer ${token}` : "",- };- }+ return requestParams;+ },+ responseInterceptor(response) {+ return response;+ },+});- return requestParams;- },- responseInterceptor(response) {- return response;- },- });- }+export async function request<T>(params: RequestParams) {+ try {+ const res = await fetchService.request(params);+ const data: ResponseType<T> = await res.json();- async request<T>(params: RequestParams) {- try {- const res = await this.fetchService.request(params);- const data: ResponseType<T> = await res.json();+ // @ts-ignore+ if (data.code === "1" && data.data.statusCode === 401) {+ useUserStore.getState().logout();+ message.error({+ key: "NoPermission",+ content: "登录状态过期,请重新登录",+ });+ return null;+ }- // @ts-ignore- if (this.isLogin && data.code === "1" && data.data.statusCode === 401) {- useUserStore.getState().logout();- message.error({- key: "NoPermission",- content: "登录状态过期,请重新登录",+ if (data.code !== 0) {+ if (typeof window !== "undefined")+ message.warning({+ content: data.msg || "网络繁忙,请稍后重试!",+ key: "apiErrorMessage",});- return null;- }-- if (data.code !== 0) {- if (typeof window !== "undefined")- message.warning({- content: data.msg || "网络繁忙,请稍后重试!",- key: "apiErrorMessage",- });- return null;- }-- return data;- } catch (e) {- console.warn(e);return null;}- }-}--// 基础API-const requestBase = new RequestClient(`${process.env.NEXT_PUBLIC_API_URL_PROXY}`, true);-// 热点-export const requestHot = new RequestClient(APP_HOT_URL);-export async function request<T>(params: RequestParams) {- return requestBase.request(params);+ return data;+ } catch (e) {+ console.warn(e);+ return null;+ }}export default {diff --git a/src/utils/storage.ts b/src/utils/storage.tsindex 49253f99..a1d7f797 100644--- a/src/utils/storage.ts+++ b/src/utils/storage.ts@@ -2,14 +2,17 @@ import { StateStorage } from "zustand/middleware";class IndexedDBStorage implements StateStorage {public async getItem(name: string): Promise<string | null> {+ if (typeof window === "undefined") return null;return localStorage.getItem(name);}public async setItem(name: string, value: string): Promise<void> {+ if (typeof window === "undefined") return;localStorage.setItem(name, value);}public async removeItem(name: string): Promise<void> {+ if (typeof window === "undefined") return;localStorage.removeItem(name);}