# Orcrist-Wechat 微信 SDK 服务组件

## 背景

## 安装

> npm install --save-dev orcrist-wechat

## 使用说明

ES 模块引入：

> import WeChat from 'orcrist-wechat'

> import { authorize, register, msg } from 'orcrist-wechat'

> WeChat.msg() || msg()

## 开放 API：

### 公众号相关：

| API 功能名称 | 功能说明                   |          入参          |           返回值           |        Demo        | 备注                                                         |
| :----------: | :------------------------- | :--------------------: | :------------------------: | :----------------: | :----------------------------------------------------------- |
|  authorize   | 微信用户授权               | redirectURL, isVisible | Promise {code, data, type} | [DEMO](#authorize) | code: 20000（成功）/ -1（失败）, type: 'userINFO' / 'openID' |
| explicitAuth | 微信显式授权               |      redirectURL       | Promise {code, data, type} |         -          | -                                                            |
|     msg      | 微信获取公众号后管配置信息 |           -            |          Promise           |    [DEMO](#msg)    |                                                              |

### JS-SDK：

| API 功能名称 |      功能说明       | 备注                                                                                      |
| :----------: | :-----------------: | :---------------------------------------------------------------------------------------- |
|   register   | 注册微信 jssdk 服务 | 同时在 ready 中可设置分享信息（参数一 shareOpt），与是否隐藏菜单栏信息（参数二 hideMenu） |
|    share     |    单独调用分享     | 通常为重置分享用                                                                          |
|     pay      |      调用支付       |                                                                                           |
|   getUser    |  获取微信用户信息   | 前提条件需调用 authorize 显式授权                                                         |

## DEMO

### authorize 微信用户授权

```javascript
/**
 * 参数 Object { redirectURL: '', isVisible: '' }
 * return Promise resolve(openID)
 */

// 1.在无依赖的场景下纯授权，并获取openID记录至sessionStorage
WeChat.authorize() // 默认参数 redirectURL = location.href当前页，isVisible为false - 直接重定向拿code换openID的“隐式授权”

// 2.对微信openID要做额外的处理，如拿openID去走用户登录 或 单独其它处理
/**
 * then 回调返回 data为 { code: 20000, data: openID, type }, 首次跳转及获取openID失败时， data为 { code: -1, data: "" }
 */
WeChat.authorize().then({code: 20000, data: openID, type = 'openID'} => {

  // go login fn
  // ---------------------
  // some other logic code...
})

// 3.控制render 不加载两次 componentDidMount ->
componentDidMount() {
  WeChat.authorize({
      redirectURL: location.href,
      isVisible: true, // 是否显式授权
    }).then(code: 20000, data: openID, type = 'userINFO' => {

      self.setState(
        {
          userINFO: data,
        },
        () => {
          Utils.preventTouch(this.myRefTabs.current, false);
        },
      );
    });
}

// ......
render() {
  if (!this.state.flag) {
    return (<div>empty<div>)
  }
  return (<div>....</div>)
}
```

### msg 获取公众号信息

```javascript
/** 

返回值： 
{"APPID":"wx0d74e6b4fe6aba0b","SOURCE":"1000000000","LOGO_IMG":{"name":"1587869394.jpg","url":"https://9719956.jpg"},"ACCOUNT_NAME":"XX健康 测试环境","original":{"id":"42ac27f3466b4215a4fc568066c398e0","accountName":"派健康 测试环境","appId":"wx0d74e6b4fe6aba0b","appSecret":null,"logoImg":{"name":"1587869394.jpg","url":"https://719956.jpg"},"sources":"1000000000"}}
*/

// 异步查询后，查询成功后存入sessionStorage KEY: ORCRIST_WECHAT_APPMSG
WeChat.msg().then((wxRes) => {
  console.log(wxRes);
});

// or
const fn = async () => {
  const wxRes = await WeChat.msg();
};
```

### register 注册微信 jssdk 服务

```javascript
// 入口统一注册 app.ts
WeChat.register({
  shareOpt: {
    title: "四十九元惠民保 惠家惠民福利好的很",
    desc: "百万保额、不限年龄、特药覆盖、无等待期，参保仅本月，错过等一年",
    link: location.href, // 分享链接
    imgUrl: "https://m.ytbxjj.com/spcare-public/static-files/hz/share.png", // 分享图标
  },
  hideMenu: true, // 是否关闭菜单栏，默认是false，可以不传
});

// 单页注册 page/index.ts
WeChat.register({
  shareOpt: {
    title: "四十九元惠民保 惠家惠民福利好的很",
    desc: "百万保额、不限年龄、特药覆盖、无等待期，参保仅本月，错过等一年",
    link: location.href, // 分享链接
    imgUrl: "https://m.ytbxjj.com/spcare-public/static-files/hz/share.png", // 分享图标
  },
  hideMenu: true, // 是否关闭菜单栏，默认是false，可以不传
});
```

##### share 需调用 register 注册接口，再可单独调用分享，通常为重置分享用

```javascript
class ReactComponent extends React.Component {
  componentDidMount() {
    // 再次重置分享
    WeChat.share({
      title: "四十九元惠民保 惠家惠民福利好的很",
      desc: "百万保额、不限年龄、特药覆盖、无等待期，参保仅本月，错过等一年",
      link: location.href, // 分享链接
      imgUrl: "https://m.ytbxjj.com/spcare-public/static-files/hz/share.png", // 分享图标
    });
  }
}
```

##### getUser 获取微信信息

app.ts 首先在入口处调用显式授权

```
import WeChat from 'orcrist-wechat'

WeChat.authorize({
  redirectURL: location.href,
  isVisible: true, // 显式授权
})
```

xxxPage.ts

```
import WeChat from 'orcrist-wechat'

const userInfo = WeChat.getUser() // {} || null
```

## API 额外说明

### msg

#### 关于页面的 sources 管理规范的说明

- 在后续的微信场景下，若当前 URL 中不包含`sources`参数，则微信组件 **Orcrist-WeChat** 会抛出 `Error` 并做 Toast 用户提示。
- 为统一规则，测试环境**不再保留**无 `sources` 可默认指向 `π 健康`场景，接入后统一使用 `1000000000`（10 位字符串，1 后面有 9 个 0）

#### sources 关联映射公众号列表

|  sources   | 公众号 |
| :--------: | :----: |
| 1100110101 |  广州  |
| 1100210101 |  惠州  |
| 1100310101 |  惠蓉  |
| 1000000000 | π 健康 |

```
## 内容列表模板

- [背景](#背景)
- [安装](#安装)
- [使用说明](#使用说明)
- [徽章](#徽章)
- [示例](#示例)
- [相关仓库](#相关仓库)
- [维护者](#维护者)
- [如何贡献](#如何贡献)
- [使用许可](#使用许可)

```
