@aomex-contrib/wechat-mini-program-login 0.0.0-stage → 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @aomex-contrib/wechat-mini-program-login
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [`013319f`](https://github.com/aomex/aomex-contrib/commit/013319f96e95278a693f55708798733412f0a947) Thanks [@geekact](https://github.com/geekact)! - 新增微信相关包:
8
+
9
+ - `@aomex-contrib/oauth2-wechat`:开放平台扫码、公众号网页授权、App 换票;默认 profile `{ base, userinfo }`,`scopes` 必填并可收窄类型
10
+ - `@aomex-contrib/oauth2-wecom`:企微自建应用网页授权;`scopes` 必填;默认返回 `WecomProfile`(无伪装 access_token)
11
+ - `@aomex-contrib/wechat-mini-program-login`:小程序 / 小游戏 `jscode2session` 登录(非 OAuth)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2024 geekact
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @aomex-contrib/wechat-mini-program-login
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 微信**小程序 / 小游戏**登录:服务端 `jscode2session`。
4
+
5
+ > **不是 OAuth2。** 没有授权页跳转、没有 `state` / `callback` / PKCE;只是用 `wx.login` 的 `code` 换 `openid` / `session_key`。
6
+
7
+ 网页扫码 / 公众号 OAuth 请用 [`@aomex-contrib/oauth2-wechat`](../oauth2-wechat/README.md)。
8
+
9
+ ---
10
+
11
+ ## 安装
12
+
13
+ ```bash
14
+ pnpm add @aomex-contrib/wechat-mini-program-login
15
+ ```
16
+
17
+ ---
18
+
19
+ ## 用法
20
+
21
+ ### 1. 后台
22
+
23
+ 小程序后台 → 开发管理 → 开发设置,拿到 **AppID / AppSecret**。
24
+ 小游戏使用同一套 `jscode2session` 接口。
25
+
26
+ ### 2. 前端
27
+
28
+ ```js
29
+ wx.login({
30
+ success(res) {
31
+ if (res.code) {
32
+ // 把 res.code 发给服务端,不要在前端保存 AppSecret
33
+ wx.request({
34
+ url: 'https://example.com/api/mini/login',
35
+ method: 'POST',
36
+ data: { code: res.code },
37
+ });
38
+ }
39
+ },
40
+ });
41
+ ```
42
+
43
+ ### 3. 服务端
44
+
45
+ ```ts
46
+ import { WechatMiniProgramLoginClient } from '@aomex-contrib/wechat-mini-program-login';
47
+
48
+ const mini = new WechatMiniProgramLoginClient({
49
+ appId: process.env.WX_MINI_APP_ID!,
50
+ appSecret: process.env.WX_MINI_APP_SECRET!,
51
+ });
52
+
53
+ const session = await mini.code2Session(code);
54
+ // { openid, session_key, unionid? }
55
+ // session_key 仅服务端保存,用于解密手机号等;勿下发前端
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 返回字段
61
+
62
+ | 字段 | 含义 |
63
+ | ------------- | ---------------------- |
64
+ | `openid` | 用户在该小程序下的标识 |
65
+ | `session_key` | 会话密钥(仅服务端) |
66
+ | `unionid` | 绑定开放平台后可能有 |
67
+
68
+ ---
69
+
70
+ ## FAQ
71
+
72
+ **Q: 能拿到 openid,解密手机号失败?**
73
+ A: 检查是否用了同一次 `wx.login` 对应的 `session_key`;过期需重新 `code2Session`。
74
+
75
+ **Q: 想要跨公众号 / 小程序统一用户?**
76
+ A: 把公众号 / 小程序绑定到同一开放平台账号,再使用返回的 `unionid`。
@@ -0,0 +1,37 @@
1
+ type WechatMiniProgramLoginOptions = {
2
+ /** 小程序 AppID */
3
+ appId: string;
4
+ /** 小程序 AppSecret */
5
+ appSecret: string;
6
+ };
7
+ /**
8
+ * `jscode2session` 成功结果(**非 OAuth**)
9
+ * @see https://developers.weixin.qq.com/miniprogram/dev/server/API/user-login/api_code2session.html
10
+ */
11
+ type WechatMiniProgramSession = {
12
+ /** 用户唯一标识 */
13
+ openid: string;
14
+ /** 会话密钥 */
15
+ session_key: string;
16
+ /**
17
+ * 用户在开放平台的唯一标识。
18
+ * 满足 UnionID 下发条件时返回
19
+ */
20
+ unionid?: string;
21
+ };
22
+ /**
23
+ * 微信小程序 / 小游戏登录(**不是 OAuth2**)。
24
+ * 仅封装 `jscode2session`:用 `wx.login` 的 code 换 openid / session_key;
25
+ * 无授权跳转、无 state / callback。
26
+ * @see https://developers.weixin.qq.com/miniprogram/dev/server/API/user-login/api_code2session.html
27
+ */
28
+ export declare class WechatMiniProgramLoginClient {
29
+ protected readonly appId: string;
30
+ protected readonly appSecret: string;
31
+ constructor(opts: WechatMiniProgramLoginOptions);
32
+ /**
33
+ * 用 `wx.login` 得到的 `js_code` 换取 openid / session_key
34
+ */
35
+ code2Session(jsCode: string): Promise<WechatMiniProgramSession>;
36
+ }
37
+ export type { WechatMiniProgramLoginOptions, WechatMiniProgramSession };
package/dist/index.js ADDED
@@ -0,0 +1,76 @@
1
+ import { I18n, createI18n } from "@aomex/common";
2
+ // src/i18n/locales/zh-cn.ts
3
+ const zh = I18n.define({
4
+ app_id_empty: "appId 不能为空",
5
+ app_secret_empty: "appSecret 不能为空",
6
+ js_code_empty: "jsCode 不能为空",
7
+ code2session_failed: "微信 code2session 失败:{{errcode}} {{errmsg}}"
8
+ });
9
+ // src/i18n/locales/en-us.ts
10
+ const en = I18n.satisfies(zh).define({
11
+ app_id_empty: "appId must not be empty",
12
+ app_secret_empty: "appSecret must not be empty",
13
+ js_code_empty: "jsCode must not be empty",
14
+ code2session_failed: "WeChat code2session failed: {{errcode}} {{errmsg}}"
15
+ });
16
+ // src/i18n/index.ts
17
+ const i18n = createI18n({
18
+ zh,
19
+ en,
20
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
21
+ });
22
+ // src/client.ts
23
+ const CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
24
+ /**
25
+ * 微信小程序 / 小游戏登录(**不是 OAuth2**)。
26
+ * 仅封装 `jscode2session`:用 `wx.login` 的 code 换 openid / session_key;
27
+ * 无授权跳转、无 state / callback。
28
+ * @see https://developers.weixin.qq.com/miniprogram/dev/server/API/user-login/api_code2session.html
29
+ */
30
+ var WechatMiniProgramLoginClient = class {
31
+ appId;
32
+ appSecret;
33
+ constructor(opts) {
34
+ if (!opts.appId) throw new Error(i18n.t("app_id_empty"));
35
+ if (!opts.appSecret) throw new Error(i18n.t("app_secret_empty"));
36
+ this.appId = opts.appId;
37
+ this.appSecret = opts.appSecret;
38
+ }
39
+ /**
40
+ * 用 `wx.login` 得到的 `js_code` 换取 openid / session_key
41
+ */
42
+ async code2Session(jsCode) {
43
+ if (!jsCode) throw new Error(i18n.t("js_code_empty"));
44
+ const url = new URL(CODE2SESSION_URL);
45
+ url.searchParams.set("appid", this.appId);
46
+ url.searchParams.set("secret", this.appSecret);
47
+ url.searchParams.set("js_code", jsCode);
48
+ url.searchParams.set("grant_type", "authorization_code");
49
+ const res = await fetch(url);
50
+ let json;
51
+ try {
52
+ json = await res.json();
53
+ } catch {
54
+ throw new Error(i18n.t("code2session_failed", {
55
+ errcode: String(res.status),
56
+ errmsg: "invalid json"
57
+ }));
58
+ }
59
+ if (typeof json.errcode === "number" && json.errcode !== 0) throw new Error(i18n.t("code2session_failed", {
60
+ errcode: String(json.errcode),
61
+ errmsg: json.errmsg ?? ""
62
+ }));
63
+ if (typeof json["openid"] !== "string" || !json["openid"] || typeof json["session_key"] !== "string" || !json["session_key"]) throw new Error(i18n.t("code2session_failed", {
64
+ errcode: "?",
65
+ errmsg: "missing fields"
66
+ }));
67
+ return {
68
+ openid: json["openid"],
69
+ session_key: json["session_key"],
70
+ unionid: typeof json["unionid"] === "string" ? json["unionid"] : void 0
71
+ };
72
+ }
73
+ };
74
+ export { WechatMiniProgramLoginClient };
75
+
76
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/index.ts","../src/client.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n app_id_empty: 'appId 不能为空',\n app_secret_empty: 'appSecret 不能为空',\n js_code_empty: 'jsCode 不能为空',\n code2session_failed: '微信 code2session 失败:{{errcode}} {{errmsg}}',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n app_id_empty: 'appId must not be empty',\n app_secret_empty: 'appSecret must not be empty',\n js_code_empty: 'jsCode must not be empty',\n code2session_failed: 'WeChat code2session failed: {{errcode}} {{errmsg}}',\n});\n","import { createI18n } from '@aomex/common';\nimport { en } from './locales/en-us';\nimport { zh } from './locales/zh-cn';\n\nexport const i18n = createI18n({\n zh,\n en,\n load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href),\n});\n","import { i18n } from './i18n';\nimport type { WechatMiniProgramLoginOptions, WechatMiniProgramSession } from './types';\n\nconst CODE2SESSION_URL = 'https://api.weixin.qq.com/sns/jscode2session';\n\n/**\n * 微信小程序 / 小游戏登录(**不是 OAuth2**)。\n * 仅封装 `jscode2session`:用 `wx.login` 的 code 换 openid / session_key;\n * 无授权跳转、无 state / callback。\n * @see https://developers.weixin.qq.com/miniprogram/dev/server/API/user-login/api_code2session.html\n */\nexport class WechatMiniProgramLoginClient {\n protected readonly appId: string;\n protected readonly appSecret: string;\n\n constructor(opts: WechatMiniProgramLoginOptions) {\n if (!opts.appId) {\n throw new Error(i18n.t('app_id_empty'));\n }\n if (!opts.appSecret) {\n throw new Error(i18n.t('app_secret_empty'));\n }\n this.appId = opts.appId;\n this.appSecret = opts.appSecret;\n }\n\n /**\n * 用 `wx.login` 得到的 `js_code` 换取 openid / session_key\n */\n async code2Session(jsCode: string): Promise<WechatMiniProgramSession> {\n if (!jsCode) {\n throw new Error(i18n.t('js_code_empty'));\n }\n\n const url = new URL(CODE2SESSION_URL);\n url.searchParams.set('appid', this.appId);\n url.searchParams.set('secret', this.appSecret);\n url.searchParams.set('js_code', jsCode);\n url.searchParams.set('grant_type', 'authorization_code');\n\n const res = await fetch(url);\n let json: { errcode?: number; errmsg?: string; [key: string]: unknown };\n try {\n json = (await res.json()) as typeof json;\n } catch {\n throw new Error(\n i18n.t('code2session_failed', {\n errcode: String(res.status),\n errmsg: 'invalid json',\n }),\n );\n }\n\n if (typeof json.errcode === 'number' && json.errcode !== 0) {\n throw new Error(\n i18n.t('code2session_failed', {\n errcode: String(json.errcode),\n errmsg: json.errmsg ?? '',\n }),\n );\n }\n\n if (\n typeof json['openid'] !== 'string' ||\n !json['openid'] ||\n typeof json['session_key'] !== 'string' ||\n !json['session_key']\n ) {\n throw new Error(\n i18n.t('code2session_failed', { errcode: '?', errmsg: 'missing fields' }),\n );\n }\n\n return {\n openid: json['openid'],\n session_key: json['session_key'],\n unionid: typeof json['unionid'] === 'string' ? json['unionid'] : undefined,\n };\n }\n}\n"],"mappings":";;AA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B,SAAS,OAAO,KAAK,OAAO;GAC5B,QAAQ,KAAK,UAAU;EACzB,CAAC,CACH;EAGF,IACE,OAAO,KAAK,cAAc,YAC1B,CAAC,KAAK,aACN,OAAO,KAAK,mBAAmB,YAC/B,CAAC,KAAK,gBAEN,MAAM,IAAI,MACR,KAAK,EAAE,uBAAuB;GAAE,SAAS;GAAK,QAAQ;EAAiB,CAAC,CAC1E;EAGF,OAAO;GACL,QAAQ,KAAK;GACb,aAAa,KAAK;GAClB,SAAS,OAAO,KAAK,eAAe,WAAW,KAAK,aAAa,KAAA;EACnE;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@aomex-contrib/wechat-mini-program-login",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "微信小程序 / 小游戏登录(jscode2session,非 OAuth2)",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git@github.com:aomex/aomex-contrib.git"
8
+ },
9
+ "homepage": "https://aomex.js.org",
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "types": "dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "LICENSE",
24
+ "package.json",
25
+ "README.md",
26
+ "CHANGELOG.md"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "peerDependencies": {
32
+ "@aomex/common": "^4.3.0"
33
+ },
34
+ "devDependencies": {
35
+ "@aomex/common": "^4.3.0"
36
+ },
37
+ "scripts": {}
6
38
  }