wx-auth-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,45 @@
1
+ export declare const WxAuth: {
2
+ init(options?: Partial<WxAuthConfig>): void;
3
+ autoCheck(): Promise<boolean>;
4
+ showAuthModal(): void;
5
+ requireAuth(): Promise<boolean>;
6
+ verifyCode(): Promise<void>;
7
+ close(): void;
8
+ onVerified(user: any): void;
9
+ onError(error: any): void;
10
+ };
11
+
12
+ /**
13
+ * 微信订阅号认证 SDK - 极简版
14
+ *
15
+ * 特点:
16
+ * - 仅需配置 apiBase
17
+ * - 复用现有后端 API
18
+ * - 无额外依赖
19
+ * - 总大小 < 10KB
20
+ * - 弹窗防删除保护
21
+ *
22
+ * 使用方法:
23
+ *
24
+ * 1. 引入SDK
25
+ * import { WxAuth } from './wx-auth';
26
+ * import './wx-auth.css';
27
+ *
28
+ * 2. 初始化
29
+ * WxAuth.init({
30
+ * apiBase: 'https://your-api.com',
31
+ * onVerified: (user) => { console.log('验证通过', user); }
32
+ * });
33
+ *
34
+ * 3. 使用
35
+ * await WxAuth.requireAuth();
36
+ */
37
+ export declare interface WxAuthConfig {
38
+ apiBase: string;
39
+ onVerified?: ((user: any) => void) | null;
40
+ onError?: ((error: any) => void) | null;
41
+ wechatName?: string;
42
+ qrcodeUrl?: string;
43
+ }
44
+
45
+ export { }
@@ -0,0 +1 @@
1
+ .wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:16px;font-weight:500}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}}
@@ -0,0 +1 @@
1
+ const e={observer:null,healthCheckTimer:null,isProtected:!1},t={enable(t){if(e.isProtected||"undefined"==typeof window)return;const{modalId:o,getState:n}=t;e.observer=new MutationObserver(e=>{e.forEach(e=>{if("childList"===e.type)e.removedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const n=e;(n.id===o||n.querySelector?.(`#${o}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(t))}});else if("attributes"===e.type){const t=e.target;t.id===o&&"style"===e.attributeName&&"none"===t.style.display&&n().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),t.style.display="flex")}})}),e.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),e.healthCheckTimer=window.setInterval(()=>{this.healthCheck(t)},1e3),e.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){e.observer&&(e.observer.disconnect(),e.observer=null),e.healthCheckTimer&&(clearInterval(e.healthCheckTimer),e.healthCheckTimer=null),e.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const n=document.getElementById(t);if(!n)return console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),void this.restore(e);"none"===n.style.display&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),n.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const s=document.getElementById(t);s?s.style.display="flex":n()}},o={apiBase:"",onVerified:null,onError:null,wechatName:"公众号",qrcodeUrl:""};let n={...o},s={isOpen:!1,resolveAuth:null,currentStep:"qr"};const r={getCookie(e){const t=`; ${document.cookie}`.split(`; ${e}=`);return 2===t.length&&t.pop()?.split(";").shift()||null},setCookie(e,t){const o=/* @__PURE__ */new Date;o.setTime(o.getTime()+2592e6),document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/`},deleteCookie(e){document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},a={createModal(){const e=document.createElement("div");return e.id="wx-auth-modal",e.className="wx-auth-modal",e.innerHTML=`\n <div class="wx-auth-overlay"></div>\n <div class="wx-auth-content">\n <div class="wx-auth-header">\n <div class="wx-auth-title">微信认证</div>\n <button class="wx-auth-close" onclick="WxAuth.close()">×</button>\n </div>\n <div class="wx-auth-body">\n \x3c!-- 二维码区域 --\x3e\n <div>\n <div class="wx-auth-desc">1. 微信关注公众号</div>\n <div class="wx-auth-qrcode-container">\n <img class="wx-auth-qrcode" src="" alt="扫码关注" />\n </div>\n </div>\n\n \x3c!-- 验证码输入区域 --\x3e\n <div>\n <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>\n ${r.generateCodeInputs()}\n </div>\n\n \x3c!-- 消息提示 --\x3e\n <div class="wx-auth-message" style="display:none"></div>\n\n \x3c!-- 按钮 --\x3e\n <div class="wx-auth-actions">\n <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">验证</button>\n </div>\n </div>\n </div>\n `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",t=>{const n=t.target.value.replace(/\D/g,"");t.target.value=n,n&&o<5&&e[o+1].focus(),5===o&&n&&setTimeout(()=>i.verifyCode(),300)}),t.addEventListener("keydown",t=>{const n=t.target;"Backspace"===t.key&&!n.value&&o>0?e[o-1].focus():"ArrowLeft"===t.key&&o>0?(t.preventDefault(),e[o-1].focus()):"ArrowRight"===t.key&&o<5&&(t.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",t=>{t.preventDefault();const o=t.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);o&&(o.split("").forEach((t,o)=>{e[o]&&(e[o].value=t)}),6===o.length&&setTimeout(()=>i.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e||(e=this.createModal()),e.style.display="flex",s.isOpen=!0,t.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),n.qrcodeUrl&&this.setQrCode(n.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&n.wechatName&&(e.textContent=`1. 微信关注公众号 "${n.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",s.isOpen=!1,t.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(e=>e.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(e=>e.value=""),e[0]&&e[0].focus()}},i={init(e={}){n={...o,...e},n.apiBase?(console.log("[WxAuth] SDK initialized",n),"undefined"!=typeof window&&this.autoCheck()):console.error("[WxAuth] apiBase is required")},async autoCheck(){const e=r.getCookie("wxauth-openid");if(!e)return this.showAuthModal(),!1;try{const t=await r.request(`${n.apiBase}/api/auth/check?openid=${e}`);return t.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),this.onVerified(t.user),!0):(r.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(t){return console.error("[WxAuth] 自动验证失败:",t),this.showAuthModal(),!1}},showAuthModal(){a.show(),n.qrcodeUrl&&a.setQrCode(n.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&n.wechatName&&(e.textContent=`1. 微信关注公众号 "${n.wechatName}"`),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)},async requireAuth(){const e=r.getCookie("wxauth-openid");if(e)try{const t=await r.request(`${n.apiBase}/api/auth/check?openid=${e}`);if(t.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),this.onVerified(t.user),!0}catch(t){console.error("[WxAuth] Cookie check failed:",t)}a.show();try{n.qrcodeUrl&&a.setQrCode(n.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&(e.textContent=`1. 微信关注公众号 "${n.wechatName}"`),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)}catch(o){return a.showMessage("加载失败,请重试","error"),!1}return new Promise(e=>{s.resolveAuth=e})},async verifyCode(){const e=a.getVerifyCode();if(!e||6!==e.length)return void a.showMessage("请输入6位验证码","error");const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=await r.request(`${n.apiBase}/api/auth/check?authToken=${e}`);o.authenticated?(o.user&&o.user.openid&&r.setCookie("wxauth-openid",o.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.close(),this.onVerified(o.user)},500)):(a.showMessage("验证码错误或已过期","error"),a.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch(o){a.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(){a.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null)},onVerified(e){console.log("[WxAuth] 验证成功",e),"function"==typeof n.onVerified&&n.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),"function"==typeof n.onError&&n.onError(e)}};"undefined"!=typeof window&&(window.WxAuth=i);export{i as WxAuth};
@@ -0,0 +1 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WxAuthSDK={})}(this,function(e){"use strict";var t=document.createElement("style");t.textContent=".wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:16px;font-weight:500}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}}\n/*$vite$:1*/",document.head.appendChild(t);const o={observer:null,healthCheckTimer:null,isProtected:!1},n={enable(e){if(o.isProtected||"undefined"==typeof window)return;const{modalId:t,getState:n}=e;o.observer=new MutationObserver(o=>{o.forEach(o=>{if("childList"===o.type)o.removedNodes.forEach(o=>{if(o.nodeType===Node.ELEMENT_NODE){const n=o;(n.id===t||n.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if("attributes"===o.type){const e=o.target;e.id===t&&"style"===o.attributeName&&"none"===e.style.display&&n().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),e.style.display="flex")}})}),o.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),o.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),o.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){o.observer&&(o.observer.disconnect(),o.observer=null),o.healthCheckTimer&&(clearInterval(o.healthCheckTimer),o.healthCheckTimer=null),o.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const n=document.getElementById(t);if(!n)return console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),void this.restore(e);"none"===n.style.display&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),n.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const a=document.getElementById(t);a?a.style.display="flex":n()}},a={apiBase:"",onVerified:null,onError:null,wechatName:"公众号",qrcodeUrl:""};let r={...a},i={isOpen:!1,resolveAuth:null,currentStep:"qr"};const s={getCookie(e){const t=`; ${document.cookie}`.split(`; ${e}=`);return 2===t.length&&t.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+2592e6),document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/`},deleteCookie(e){document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},c={createModal(){const e=document.createElement("div");return e.id="wx-auth-modal",e.className="wx-auth-modal",e.innerHTML=`\n <div class="wx-auth-overlay"></div>\n <div class="wx-auth-content">\n <div class="wx-auth-header">\n <div class="wx-auth-title">微信认证</div>\n <button class="wx-auth-close" onclick="WxAuth.close()">×</button>\n </div>\n <div class="wx-auth-body">\n \x3c!-- 二维码区域 --\x3e\n <div>\n <div class="wx-auth-desc">1. 微信关注公众号</div>\n <div class="wx-auth-qrcode-container">\n <img class="wx-auth-qrcode" src="" alt="扫码关注" />\n </div>\n </div>\n\n \x3c!-- 验证码输入区域 --\x3e\n <div>\n <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>\n ${s.generateCodeInputs()}\n </div>\n\n \x3c!-- 消息提示 --\x3e\n <div class="wx-auth-message" style="display:none"></div>\n\n \x3c!-- 按钮 --\x3e\n <div class="wx-auth-actions">\n <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">验证</button>\n </div>\n </div>\n </div>\n `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",t=>{const n=t.target.value.replace(/\D/g,"");t.target.value=n,n&&o<5&&e[o+1].focus(),5===o&&n&&setTimeout(()=>d.verifyCode(),300)}),t.addEventListener("keydown",t=>{const n=t.target;"Backspace"===t.key&&!n.value&&o>0?e[o-1].focus():"ArrowLeft"===t.key&&o>0?(t.preventDefault(),e[o-1].focus()):"ArrowRight"===t.key&&o<5&&(t.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",t=>{t.preventDefault();const o=t.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);o&&(o.split("").forEach((t,o)=>{e[o]&&(e[o].value=t)}),6===o.length&&setTimeout(()=>d.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e||(e=this.createModal()),e.style.display="flex",i.isOpen=!0,n.enable({modalId:"wx-auth-modal",getState:()=>i,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&r.wechatName&&(e.textContent=`1. 微信关注公众号 "${r.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",i.isOpen=!1,n.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(e=>e.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(e=>e.value=""),e[0]&&e[0].focus()}},d={init(e={}){r={...a,...e},r.apiBase?(console.log("[WxAuth] SDK initialized",r),"undefined"!=typeof window&&this.autoCheck()):console.error("[WxAuth] apiBase is required")},async autoCheck(){const e=s.getCookie("wxauth-openid");if(!e)return this.showAuthModal(),!1;try{const t=await s.request(`${r.apiBase}/api/auth/check?openid=${e}`);return t.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),this.onVerified(t.user),!0):(s.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(t){return console.error("[WxAuth] 自动验证失败:",t),this.showAuthModal(),!1}},showAuthModal(){c.show(),r.qrcodeUrl&&c.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&r.wechatName&&(e.textContent=`1. 微信关注公众号 "${r.wechatName}"`),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)},async requireAuth(){const e=s.getCookie("wxauth-openid");if(e)try{const t=await s.request(`${r.apiBase}/api/auth/check?openid=${e}`);if(t.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),this.onVerified(t.user),!0}catch(t){console.error("[WxAuth] Cookie check failed:",t)}c.show();try{r.qrcodeUrl&&c.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&(e.textContent=`1. 微信关注公众号 "${r.wechatName}"`),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)}catch(o){return c.showMessage("加载失败,请重试","error"),!1}return new Promise(e=>{i.resolveAuth=e})},async verifyCode(){const e=c.getVerifyCode();if(!e||6!==e.length)return void c.showMessage("请输入6位验证码","error");const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=await s.request(`${r.apiBase}/api/auth/check?authToken=${e}`);o.authenticated?(o.user&&o.user.openid&&s.setCookie("wxauth-openid",o.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.close(),this.onVerified(o.user)},500)):(c.showMessage("验证码错误或已过期","error"),c.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch(o){c.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(){c.hide(),i.resolveAuth&&(i.resolveAuth(!1),i.resolveAuth=null)},onVerified(e){console.log("[WxAuth] 验证成功",e),"function"==typeof r.onVerified&&r.onVerified(e),i.resolveAuth&&(i.resolveAuth(!0),i.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),"function"==typeof r.onError&&r.onError(e)}};"undefined"!=typeof window&&(window.WxAuth=d),e.WxAuth=d,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "wx-auth-sdk",
3
+ "version": "1.0.0",
4
+ "description": "微信订阅号认证 SDK - 极简版",
5
+ "type": "module",
6
+ "main": "./dist/wx-auth.umd.js",
7
+ "module": "./dist/wx-auth.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/wx-auth.js",
13
+ "require": "./dist/wx-auth.umd.js"
14
+ },
15
+ "./dist/style.css": "./dist/wx-auth.css"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "keywords": [
21
+ "wechat",
22
+ "wx",
23
+ "auth",
24
+ "subscription",
25
+ "sdk",
26
+ "微信认证",
27
+ "订阅号",
28
+ "公众号",
29
+ "微信",
30
+ "认证",
31
+ "订阅号认证",
32
+ "公众号认证",
33
+ "微信认证",
34
+ "微信订阅号认证",
35
+ "微信订阅号认证系统",
36
+ "微信订阅号认证SDK"
37
+ ],
38
+ "author": "",
39
+ "license": "MIT",
40
+ "scripts": {
41
+ "dev": "vite",
42
+ "build": "vite build",
43
+ "preview": "vite preview",
44
+ "type-check": "tsc --noEmit"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.19.3",
48
+ "typescript": "~5.9.3",
49
+ "vite": "^7.2.4",
50
+ "vite-plugin-dts": "^4.5.4"
51
+ }
52
+ }