Skip to content

Commit

Permalink
feat(mp): add mp get phone number function
Browse files Browse the repository at this point in the history
  • Loading branch information
jay committed Jul 7, 2022
1 parent c6c2e77 commit f003582
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 10 deletions.
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ export class AppModule {
+ forRoot配置注册

```javascript
import { Module } from '@nestjs/common';
import { CACHE_MANAGER, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

import { WeChatModule } from 'nest-wechat';
import { Cache } from 'cache-manager';
import { RedisCache, WeChatModule } from 'nest-wechat';

@Module({
imports: [
Expand All @@ -43,12 +43,13 @@ import { WeChatModule } from 'nest-wechat';
}),
WeChatModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
inject: [ConfigService, CACHE_MANAGER],
useFactory: (configService: ConfigService, cache: Cache) => ({
appId: configService.get('WX_APPID'),
secret: configService.get('WX_SECRET'),
token: configService.get('WX_TOKEN'),
encodingAESKey: configService.get('WX_AESKEY'),
cacheAdapter: new RedisCache(cache),
}),
}),
]
Expand Down Expand Up @@ -220,6 +221,12 @@ export interface ICache {

> [参考文档](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html)
### 获取手机号码

```javascript
mp.getPhoneNumber(code: string, accessToken: string): Promise<PhoneNumberResult>;
```

### Run Test

Create .env.test.local file, and save your test appid and secret in the file.
Expand Down
37 changes: 36 additions & 1 deletion lib/interfaces/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,41 @@ export interface AuthorizerListResult {
* 授权的时间
*/
auth_time: number;
}[]
}[];
}

/**
* 获取手机号码返回结果
*/
export interface PhoneNumberResult extends DefaultRequestResult {
/**
* 用户手机号信息
*/
phone_info: {
/**
* 用户绑定的手机号(国外手机号会有区号)
*/
phoneNumber: string;
/**
* 没有区号的手机号
*/
purePhoneNumber: string;
/**
* 区号
*/
countryCode: number;
/**
* 数据水印
*/
watermark: {
/**
* 用户获取手机号操作的时间戳
*/
timestamp: number;
/**
* 小程序appid
*/
appid: string;
};
};
}
26 changes: 26 additions & 0 deletions lib/miniprogram.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { MiniProgramService } from './miniprogram.service';

describe('mini program service test', () => {

let service: MiniProgramService;

beforeAll(() => {
service = new MiniProgramService({
appId: 'your/mini/app/id',
secret: 'your/mini/app/secret',
});
});

it('Should not got a phone number use incorrect token', async () => {
const accessToken = 'INCORRECT_TOKEN';
const code = 'INCORRECT_CODE';
try {
const ret = await service.getPhoneNumber(code, accessToken);
// { errcode: 40001, errmsg: 'invalid credential, access_token is invalid or not latest rid: 62c66213-76542f8c-06b14179'}
expect(ret.data.errcode).toStrictEqual(40001);
} catch (error) {
expect(error).toBeUndefined();
}
});

});
21 changes: 17 additions & 4 deletions lib/miniprogram.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Logger, Req, Res } from '@nestjs/common';
import axios from 'axios';

import { DefaultRequestResult, ParamCreateQRCode, SessionResult } from './interfaces';
import { DefaultRequestResult, ParamCreateQRCode, PhoneNumberResult, SessionResult } from './interfaces';
import { WeChatModuleOptions } from './types';

import type { Request, Response } from 'express';
Expand All @@ -22,8 +22,8 @@ export class MiniProgramService {
* @link https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
*/
public async code2Session (code: string, appId?: string, secret?: string): Promise<SessionResult> {
appId = appId || this.options.appId;
secret = secret || this.options.secret;
appId = appId || this.options?.appId;
secret = secret || this.options?.secret;
if (!appId || !secret) {
throw new Error(`${MiniProgramService.name}': No appId or secret.`);
} else {
Expand All @@ -42,6 +42,19 @@ export class MiniProgramService {
return axios.post<DefaultRequestResult>(url, params);
}

/**
* 获取手机号
* @param {string} accessToken 小程序调用token,第三方可通过使用authorizer_access_token代商家进行调用
* @param {string} code 手机号获取凭证,小程序端获取
* @returns
* @link https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
* @link https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
*/
public async getPhoneNumber (code: string, accessToken: string) {
const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
return axios.post<PhoneNumberResult>(url, { code });
}

/**
* 小程序消息推送配置时,推送处理方法
* @param req Express.Request
Expand All @@ -51,7 +64,7 @@ export class MiniProgramService {
* @link https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html
*/
public verifyMessagePush (@Req() req: Request, @Res() res: Response, token?: string) {
token = token || this.options.token;
token = token || this.options?.token;
this.logger.debug(`verifyMessagePush() token = ${token}`);
this.logger.debug(`verifyMessagePush() query = ${JSON.stringify(req.query)}`);
const signature = (req.query && req.query.signature) || '';
Expand Down

0 comments on commit f003582

Please sign in to comment.