1.0.0 • Published 6 years ago

v-wechat-auth v1.0.0

Weekly downloads
5
License
MIT
Repository
github
Last release
6 years ago

v-wechat-auth

npm vue2

vue 2.0 微信网页授权插件

安装

npm

npm install --save v-wechat-auth
import Vue from 'vue'
import VWechatAuth from 'v-wechat-auth'

通过 script 标签

<!-- 在 Vue 之后 -->
<!-- 从本地文件 -->
<script src="v-wechat-auth/dist/v-wechat-auth.min.js"></script>

<!-- 从 CDN -->
<script src="https://unpkg.com/v-wechat-auth"></script>

使用

初始化

Vue.use(VWechatAuth)

// 必须在 root 实例上注入 wechatAuth
new Vue({
  el: '#app',
  ...,
  wechatAuth: new VWechatAuth({
    appId: 'your wechat appid',
    scope: 'snsapi_base or snsapi_userinfo'
    authorize () {
      return axios.get('your backend api here', { params: { code: code } })
        .then(function (res) {
          var data = (res && res.data) || {} // response data should at least contain openid
          return data
        })
    }
  })
})

调用

this.$wechatAuth.authorize()

运行例子

  1. examples 文件夹中的 config.example.js 重命名为 config.js

  2. 修改 config.js, 填入微信 appid 和 scope, 并在 authorize 方法中调用后端接口获取用户信息,并将用户信息返回

  3. 修改 host 文件,将微信授权域名映射为 localhost

  4. 运行 npm run example

  5. 在微信开发者工具中访问 授权域名/examples/index.html(因为修改了host,这时访问的实际上是本地)

  6. 能显示当前用户的 openid

openid

options

属性类型必输默认说明
autoRedirectbooleantrue当 url 中不包含 code 参数或返回结果中不包含openid时,是否自动重定向到微信授权url
appIdstring微信 appid
scopestring微信 scope, snsapi_basesnsapi_userinfo
statestring''微信 state
authorizefunctionajax 请求调用后端接口获取微信用户信息
ssrboolean是否使用服务端渲染,尚未实现

VWechatAuth 实例

属性说明
user当获取用户信息成功后,存储了用户的信息,否则为一个空对象
方法参数返回说明
authorizeonSuccess,执行成功的回调函数 onFail,执行失败的回调函数Promise授权获取用户信息,支持回调函数 和 Promise

License

MIT