项目作者: jindasong

项目描述 :
基于vue开发的微信单页应用授权插件
高级语言: JavaScript
项目地址: git://github.com/jindasong/vue-wechat-auth.git
创建时间: 2017-03-26T15:49:36Z
项目社区:https://github.com/jindasong/vue-wechat-auth

开源协议:

下载


vue-wechat-auth

基于vue开发的微信单页应用授权插件

依赖

  1. 基于vue2.0+, vue-router2.0+

使用步骤

1.npm安装

  1. npm i vue-wechat-auth vue-router axios -S
  2. # axios为选装,可以使用您喜欢的任意ajax库

2.引入vue-wechat-auth

  1. import Vue from 'vue'
  2. import VueRouter from 'vue-router'
  3. import WechatAuth from 'vue-wechat-auth'
  4. import axios from 'axios'
  5. // 路由配置
  6. let router = new Router({
  7. routes: [
  8. {
  9. path: '/',
  10. name: 'Hello',
  11. meta: {
  12. auth: true // 如果此路由需要微信授权请设置为true,默认为false
  13. }
  14. }
  15. ]
  16. })
  17. Vue.use(VueRouter)
  18. // 微信授权插件初始化
  19. Vue.use(WechatAuth , {
  20. router, // 路由实例对象
  21. appid: '', // 您的微信appid
  22. responseType: 'code', // 返回类型,请填写code
  23. scope: 'snsapi_userinfo', // 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
  24. getCodeCallback (code, next) {
  25. // 用户同意授权后回调方法
  26. // code:用户同意授权后,获得code值
  27. // code说明: code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
  28. // next: 无论access_token是否获取成功,一定要调用该方法
  29. // next说明:next方法接收两个参数
  30. // 参数1为通过code值请求后端获取到的access_token值,如果获取失败请填入空字符串''
  31. // 参数2(非必填,默认获取access_token切换到当前路由对象),指定切换对象 next('/') 或者 next({ path: '/' })
  32. axios.get('通过code值换取access_token接口地址', {
  33. params: {
  34. code,
  35. state: ''
  36. }
  37. }).then(response => {
  38. let data = response.data
  39. let accessToken = data.data['access_token']
  40. if (accessToken) {
  41. next(accessToken) // 获取access_toeken成功
  42. } else {
  43. next() // 获取access_token失败
  44. }
  45. }).catch(() => {
  46. next() // ajax出现错误
  47. })
  48. }
  49. })
  50. new Vue({
  51. el: '#app',
  52. router,
  53. render: h => h(App)
  54. })