|
| 1 | +import { betterFetch } from "@better-fetch/fetch"; |
| 2 | +import type { OAuth2Tokens, OAuthProvider, ProviderOptions } from "../oauth2"; |
| 3 | + |
| 4 | +/** |
| 5 | + * WeChat user profile information |
| 6 | + * @see https://developers.weixin.qq.com/doc/oplatform/en/Website_App/WeChat_Login/Wechat_Login.html |
| 7 | + */ |
| 8 | +export interface WeChatProfile extends Record<string, any> { |
| 9 | + /** |
| 10 | + * User's unique OpenID |
| 11 | + */ |
| 12 | + openid: string; |
| 13 | + /** |
| 14 | + * User's nickname |
| 15 | + */ |
| 16 | + nickname: string; |
| 17 | + /** |
| 18 | + * User's avatar image URL |
| 19 | + */ |
| 20 | + headimgurl: string; |
| 21 | + /** |
| 22 | + * User's privileges |
| 23 | + */ |
| 24 | + privilege: string[]; |
| 25 | + /** |
| 26 | + * User's UnionID (unique across the developer's various applications) |
| 27 | + */ |
| 28 | + unionid?: string; |
| 29 | + /** @note Email is currently unsupported by WeChat */ |
| 30 | + email?: string; |
| 31 | +} |
| 32 | + |
| 33 | +export interface WeChatOptions extends ProviderOptions<WeChatProfile> { |
| 34 | + /** |
| 35 | + * WeChat App ID |
| 36 | + */ |
| 37 | + clientId: string; |
| 38 | + /** |
| 39 | + * WeChat App Secret |
| 40 | + */ |
| 41 | + clientSecret: string; |
| 42 | + /** |
| 43 | + * Platform type for WeChat login |
| 44 | + * - Currently only supports "WebsiteApp" for WeChat Website Application (网站应用) |
| 45 | + * @default "WebsiteApp" |
| 46 | + */ |
| 47 | + platformType?: "WebsiteApp"; |
| 48 | + |
| 49 | + /** |
| 50 | + * UI language for the WeChat login page |
| 51 | + * cn for Simplified Chinese, en for English |
| 52 | + * @default "cn" if left undefined |
| 53 | + */ |
| 54 | + lang?: "cn" | "en"; |
| 55 | +} |
| 56 | + |
| 57 | +export const wechat = (options: WeChatOptions) => { |
| 58 | + return { |
| 59 | + id: "wechat", |
| 60 | + name: "WeChat", |
| 61 | + createAuthorizationURL({ state, scopes, redirectURI }) { |
| 62 | + const _scopes = options.disableDefaultScope ? [] : ["snsapi_login"]; |
| 63 | + options.scope && _scopes.push(...options.scope); |
| 64 | + scopes && _scopes.push(...scopes); |
| 65 | + |
| 66 | + // WeChat uses non-standard OAuth2 parameters (appid instead of client_id) |
| 67 | + // and requires a fragment (#wechat_redirect), so we construct the URL manually. |
| 68 | + const url = new URL("https://open.weixin.qq.com/connect/qrconnect"); |
| 69 | + url.searchParams.set("scope", _scopes.join(",")); |
| 70 | + url.searchParams.set("response_type", "code"); |
| 71 | + url.searchParams.set("appid", options.clientId); |
| 72 | + url.searchParams.set("redirect_uri", options.redirectURI || redirectURI); |
| 73 | + url.searchParams.set("state", state); |
| 74 | + url.searchParams.set("lang", options.lang || "cn"); |
| 75 | + url.hash = "wechat_redirect"; |
| 76 | + |
| 77 | + return url; |
| 78 | + }, |
| 79 | + |
| 80 | + // WeChat uses non-standard token exchange (appid/secret instead of |
| 81 | + // client_id/client_secret, GET instead of POST), so shared helpers |
| 82 | + // like validateAuthorizationCode/getOAuth2Tokens cannot be used directly. |
| 83 | + validateAuthorizationCode: async ({ code }) => { |
| 84 | + const params = new URLSearchParams({ |
| 85 | + appid: options.clientId, |
| 86 | + secret: options.clientSecret, |
| 87 | + code: code, |
| 88 | + grant_type: "authorization_code", |
| 89 | + }); |
| 90 | + |
| 91 | + const { data: tokenData, error } = await betterFetch<{ |
| 92 | + access_token: string; |
| 93 | + expires_in: number; |
| 94 | + refresh_token: string; |
| 95 | + openid: string; |
| 96 | + scope: string; |
| 97 | + unionid?: string; |
| 98 | + errcode?: number; |
| 99 | + errmsg?: string; |
| 100 | + }>( |
| 101 | + "https://api.weixin.qq.com/sns/oauth2/access_token?" + |
| 102 | + params.toString(), |
| 103 | + { |
| 104 | + method: "GET", |
| 105 | + }, |
| 106 | + ); |
| 107 | + |
| 108 | + if (error || !tokenData || tokenData.errcode) { |
| 109 | + throw new Error( |
| 110 | + `Failed to validate authorization code: ${tokenData?.errmsg || error?.message || "Unknown error"}`, |
| 111 | + ); |
| 112 | + } |
| 113 | + |
| 114 | + return { |
| 115 | + tokenType: "Bearer" as const, |
| 116 | + accessToken: tokenData.access_token, |
| 117 | + refreshToken: tokenData.refresh_token, |
| 118 | + accessTokenExpiresAt: new Date( |
| 119 | + Date.now() + tokenData.expires_in * 1000, |
| 120 | + ), |
| 121 | + scopes: tokenData.scope.split(","), |
| 122 | + // WeChat requires openid for the userinfo endpoint, which is |
| 123 | + // returned alongside the access token. |
| 124 | + openid: tokenData.openid, |
| 125 | + unionid: tokenData.unionid, |
| 126 | + }; |
| 127 | + }, |
| 128 | + |
| 129 | + refreshAccessToken: options.refreshAccessToken |
| 130 | + ? options.refreshAccessToken |
| 131 | + : async (refreshToken) => { |
| 132 | + const params = new URLSearchParams({ |
| 133 | + appid: options.clientId, |
| 134 | + grant_type: "refresh_token", |
| 135 | + refresh_token: refreshToken, |
| 136 | + }); |
| 137 | + |
| 138 | + const { data: tokenData, error } = await betterFetch<{ |
| 139 | + access_token: string; |
| 140 | + expires_in: number; |
| 141 | + refresh_token: string; |
| 142 | + openid: string; |
| 143 | + scope: string; |
| 144 | + errcode?: number; |
| 145 | + errmsg?: string; |
| 146 | + }>( |
| 147 | + "https://api.weixin.qq.com/sns/oauth2/refresh_token?" + |
| 148 | + params.toString(), |
| 149 | + { |
| 150 | + method: "GET", |
| 151 | + }, |
| 152 | + ); |
| 153 | + |
| 154 | + if (error || !tokenData || tokenData.errcode) { |
| 155 | + throw new Error( |
| 156 | + `Failed to refresh access token: ${tokenData?.errmsg || error?.message || "Unknown error"}`, |
| 157 | + ); |
| 158 | + } |
| 159 | + |
| 160 | + return { |
| 161 | + tokenType: "Bearer" as const, |
| 162 | + accessToken: tokenData.access_token, |
| 163 | + refreshToken: tokenData.refresh_token, |
| 164 | + accessTokenExpiresAt: new Date( |
| 165 | + Date.now() + tokenData.expires_in * 1000, |
| 166 | + ), |
| 167 | + scopes: tokenData.scope.split(","), |
| 168 | + }; |
| 169 | + }, |
| 170 | + |
| 171 | + async getUserInfo(token) { |
| 172 | + if (options.getUserInfo) { |
| 173 | + return options.getUserInfo(token); |
| 174 | + } |
| 175 | + |
| 176 | + const openid = (token as OAuth2Tokens & { openid?: string }).openid; |
| 177 | + |
| 178 | + if (!openid) { |
| 179 | + return null; |
| 180 | + } |
| 181 | + |
| 182 | + const params = new URLSearchParams({ |
| 183 | + access_token: token.accessToken || "", |
| 184 | + openid: openid, |
| 185 | + lang: "zh_CN", |
| 186 | + }); |
| 187 | + |
| 188 | + const { data: profile, error } = await betterFetch< |
| 189 | + WeChatProfile & { errcode?: number; errmsg?: string } |
| 190 | + >("https://api.weixin.qq.com/sns/userinfo?" + params.toString(), { |
| 191 | + method: "GET", |
| 192 | + }); |
| 193 | + |
| 194 | + if (error || !profile || profile.errcode) { |
| 195 | + return null; |
| 196 | + } |
| 197 | + |
| 198 | + const userMap = await options.mapProfileToUser?.(profile); |
| 199 | + return { |
| 200 | + user: { |
| 201 | + id: profile.unionid || profile.openid || openid, |
| 202 | + name: profile.nickname, |
| 203 | + email: profile.email || null, |
| 204 | + image: profile.headimgurl, |
| 205 | + emailVerified: false, |
| 206 | + ...userMap, |
| 207 | + }, |
| 208 | + data: profile, |
| 209 | + }; |
| 210 | + }, |
| 211 | + options, |
| 212 | + } satisfies OAuthProvider<WeChatProfile, WeChatOptions>; |
| 213 | +}; |
0 commit comments