微信公众号网页开发

328 阅读3分钟

目录

概述 公众号主要通过公众号消息会话和公众号内网页来为用户提供服务的

公众号内网页

许多复杂的业务场景,需要通过网页形式来提供服务,这时需要用到:

1)网页授权获取用户基本信息:通过该接口,可以获取用户的基本信息(获取用户的OpenID是无需用户同意的,获取用户的基本信息则需用户同意)

2)微信JS-SDK:是开发者在网页上通过JavaScript代码使用微信原生功能的工具包,开发者可以使用它在网页上录制和播放微信语音、监听微信分享、上传手机本地图片、拍照等许多能力

网页授权

微信网页授权是通过OAuth2.0机制实现的。

网络授权流程分为四步:

  1. 引导用户进入授权页面,用户同意授权,获取code
  2. 通过code换取网页授权access_token(与基础支持中的access_token不同)
  3. 刷新access_token,避免过期(如果需要)
  4. 通过网页授权access_token和openid获取用户基本信息(需scope为snsapi_userinfo)

官方资料

npm库co-wechat-oauth

index.html

<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <script src="https://unpkg.com/vue@2.1.10/dist/vue.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/cube-ui/lib/cube.min.js"></script>
    <script src="https://cdn.bootcss.com/qs/6.6.0/qs.js"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/cube-ui/lib/cube.min.css">
    <style>
        .cube-btn {
            margin: 10px 0;
        }
    </style>
</head>

<body>
    <div id="app">
        <cube-button @click='auth'>微信登录</cube-button>
        <cube-button @click='getUser'>获取用户信息</cube-button>
    </div>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                value: 'input'
            },

            methods: {
                async getFollowers() {
                    const res = await axios.get('/getFollowers')
                    console.log('res', res)
                },
                async auth() {
                    window.location.href = '/wxAuthorize'

                },
                async getUser() {
                    const qs = Qs.parse(window.location.search.substr(1))
                    const res = await axios.get('/getUser', {
                        params: {
                            openid: qs.openid
                        }
                    })
                    console.log('User', res.data)
                }
            },
            mounted: function () {

            },
        });
    </script>
</body>

</html>

index.js

/**
 * 网页授权
 * 
 */

const Koa = require('koa')
const Router = require('koa-router')
const static = require('koa-static')
const bodyParser = require('koa-bodyparser');
const app = new Koa()
const conf = require('./conf')
app.use(bodyParser())
const router = new Router()
app.use(static(__dirname + '/'))
const axios = require('axios')


const tokenCache = {
    access_token: '',
    updateTime: Date.now(),
    refresh_token: "REFRESH_TOKEN",
    expires_in: 7200
}

const OAuth = require('co-wechat-oauth')
const oauth = new OAuth(conf.appid, conf.appsecret,
    openid => tokenCache.access_token,
    (openid, token) => tokenCache.access_token = token
)

/**
 * 点击微信登录,生成并重定向到微信网页授权页面
 */
router.get('/wxAuthorize', async ctx => {
    const state = ctx.query.id
    //配置同意授权后的回调地址:
    const redirectUrl = ctx.href.replace('wxAuthorize', 'wxCallback')
    // 具体api参数信息:http://doxmate.cool/node-webot/co-wechat-oauth/api.html
    const oauthUrl = oauth.getAuthorizeURL(redirectUrl, state, 'snsapi_userinfo')
    console.log(oauthUrl)
    ctx.redirect(oauthUrl)
})

/**
 * 用于授权页面点击同意后,微信重定向请求
 * 请求URL中携带code信息,用于授权认证
 */
router.get('/wxCallback', async ctx => {
    const code = ctx.query.code
    const token = await oauth.getAccessToken(code)
    const openid = token.data.openid
    console.log('token', token.data)
    console.log('accessToken', token.data.access_token)
    ctx.redirect(`/?openid=${openid}`)
})

/**
 * 获取用户信息
 */
router.get('/getUser', async ctx => {
    const openid = ctx.query.openid
    const userInfo = await oauth.getUser(openid)
    ctx.body = userInfo
})

app.use(router.routes()); /*启动路由*/
app.use(router.allowedMethods());
app.listen(3000);

测试:

  1. 外网映射确保已经开启
  2. 启动node服务nodemon index
  3. 点击微信登录,同意后会重定向到index.html,并携带查询参数openid
  4. 点击获取用户信息(openid)
  5. 再次点击微信登录,观察变化

微信JS-SDK

官方资料

npm库co-wechat-api

index.html

//加入js文件,则页面中可用对象wx
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

<cube-button @click='getJSConfig'>获取JS-DKConfig</cube-button>
 
 // 编写接口调用
async getJSConfig() {
                    console.log('wx', wx)
                    const res = await axios.get('/getJSConfig', {
                        params: {
                            url: window.location.href
                        }
                    })
                    console.log('res....', res.data)
                    res.data.jsApiList = ['onMenuShareTimeline', 'onMenuShareAppMessage']
                    wx.config(res.data);
                    wx.ready(function () {
                        console.log('wx.ready......')
                    })
                    wx.getNetworkType({
                        success: function (res) {
                            // 返回网络类型2g,3g,4g,wifi
                            var networkType = res.networkType;
                            console.log('getNetworkType...', networkType)
                        }
                    })
                }

index.js

/**
 * 获取JSConfig
 */

const WechatAPI = require('co-wechat-api')
const api = new WechatAPI(
    conf.appid,
    conf.appsecret,
    // 取Token回调 这里可以扩展从数据库中取token
    () => tokenCache.access_token,
    // 存Token
    token => tokenCache.access_token = token
)
// api链接:http://doxmate.cool/node-webot/co-wechat-api/api.html#api_js_exports_getJsConfig
router.get('/getJsConfig',async ctx => {
    const res = await api.getJsConfig(ctx.query)
    ctx.body = res
})

查看 源代码

微信号:yuan_zi_xxx