全栈开发微信公众号(下)

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 全栈开发微信公众号

全局票据

全局票据需要基于mongodb或者redires,我们用mongodb

新建个mongoose.js

const mongoose = require('mongoose')
const {
    Schema
} = mongoose
mongoose.connect('mongodb://localhost:27017/weixin', {
    useNewUrlParser: true
}, () => {
    console.log('Mongodb connected..')
})
exports.ServerToken = mongoose.model('ServerToken', {
    accessToken: String
});

index.js里改造上面用co-wechat-api的

const { ServerToken } = require('./mongoose')//全局票据来源
const WechatAPI = require('co-wechat-api')
const api = new WechatAPI(
    conf.appid,
    conf.appsecret,
    // 取Token
    async () => await ServerToken.findOne(),
    // 存Token
    async token => await ServerToken.updateOne({}, token, { upsert: true })
)
router.get('/getFollowers', async ctx => {
    let res = await api.getFollowers()
    res = await api.batchGetUsers(res.data.openid, 'zh_CN')
    ctx.body = res
})

消息推动

就类似于这个,前台发送1,1,2


后台会显示前台的推送,而且更新echart

Oauth2认证流程

首先三个端,浏览器,服务器,微信服务器


1.浏览器向服务器发送认证请求


2.服务器让浏览器重定向微信认证界面


3.浏览器向微信服务器请求第三方认证(微信认证)


4.微信服务器毁掉给服务器一个认证code


5.服务器用code向微信服务器申请认证令牌


6.微信服务器返给服务器一个令牌


最后当服务器得到令牌认证成功后,发给浏览器一个指令,刷新界面


刷新后就会有一个用户信息


使用微信开发者工具,选择公众号网页,用来预览


demo1 下载

相关文档:


01_公众号_服务器端 下载

01-公众号简介与开发者申请 下载

02-ngrok使用1 下载


实现一个微信认证登录

配置js接口安全域名,就是我们转发的公网域名(不用带协议):zhifeiji.free.idcfengye.com

再就是每个微信接口api那里也要授权,即下图的修改位置,修改的和上面一样


把前面的项目考过来再seed目录下继续写

index.js


const OAuth = require('co-wechat-oauth')//引入一个oauth库
const oauth = new OAuth(conf.appid,conf.appsecret)
/**
 * 生成用户URL
 */
router.get('/wxAuthorize', async (ctx, next) => {
    const state = ctx.query.id
    console.log('ctx...' + ctx.href)
    let redirectUrl = ctx.href
    redirectUrl = redirectUrl.replace('wxAuthorize', 'wxCallback')
    const scope = 'snsapi_userinfo'
    const url = oauth.getAuthorizeURL(redirectUrl, state, scope)
    console.log('url' + url)
    ctx.redirect(url)
})
/**
 * 用户回调方法
 */
router.get('/wxCallback', async ctx => {
    const code = ctx.query.code
    console.log('wxCallback code', code)
    const token = await oauth.getAccessToken(code)
    const accessToken = token.data.access_token
    const openid = token.data.openid
    console.log('accessToken', accessToken)
    console.log('openid', openid)
    ctx.redirect('/?openid=' + openid)
})
/**
 * 获取用户信息
 */
router.get('/getUser', async ctx => {
    const openid = ctx.query.openid
    const userInfo = await oauth.getUser(openid)
    console.log('userInfo:', userInfo)
    ctx.body = userInfo
})

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-input v-model="value"></cube-input>
        <cube-button @click='click'>Click</cube-button>
        <cube-button @click='getTokens'>getTokens</cube-button>
        <cube-button @click='getFollowers'>getFollowers</cube-button>
        <cube-button @click='auth'>微信登录</cube-button>
        <cube-button @click='getUser'>获取用户信息</cube-button>
    </div>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                value: 'input'
            },
            methods: {
                click: function () {
                    console.log('click')
                },
                async getTokens(){
                    const res = await axios.get('/getTokens')
                    console.log('res:',res)
                },
                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 openid= qs.openid
                    const res = await axios.get('/getUser',{
                        params:{
                            openid
                        }
                    })
                    console.log('res',res)
                }
            },
            mounted: function () {
            },
        });
    </script>
</body>
</html>

全局票据(一样用到mongoose,从上次的修改)

mongoose.js

const mongoose = require('mongoose')
const {
    Schema
} = mongoose
mongoose.connect('mongodb://localhost:27017/weixin', {
    useNewUrlParser: true
}, () => {
    console.log('Mongodb connected..')
})
exports.ServerToken = mongoose.model('ServerToken', {
    accessToken: String
});
schema = new Schema({
    access_token: String,
    expires_in: Number,
    refresh_token: String,
    openid: String,
    scope: String,
    create_at: String
});
// 自定义getToken方法
schema.statics.getToken = async function (openid) {
    return await this.findOne({
        openid: openid
    });
};
schema.statics.setToken = async function (openid, token) {
    // 有则更新,无则添加
    const query = {
        openid: openid
    };
    const options = {
        upsert: true
    };
    return await this.updateOne(query, token, options);
};
exports.ClientToken = mongoose.model('ClientToken', schema);

index.js

const { ServerToken,ClientToken } = require('./mongoose')//全局票据来源
const oauth = new OAuth(conf.appid, conf.appsecret,
    async function (openid) {
        return await ClientToken.getToken(openid)
    },
    async function (openid, token) {
        return await ClientToken.setToken(openid, token)
    }
)

微信jssdk

准备:

?1.获取jsconfig

index.html

<cube-button @click='getJSConfig'>获取jsconfig</cube-button>
async getJSConfig(){
                    console.log('wx',wx)
                    const res = await axios.get('/getJSConfig',{
                        params:{
                            url:window.location.href
                        }
                    })
                    console.log('config',res)
                    res.data.jsApiList = ['onMenuShareTimeline']
                    wx.config(res.data)
                    wx.ready(function () {
                        console.log('wx.ready......')
                    })
                }

index.js

/**
 * 获取JSConfig
 */
router.get('/getJsConfig',async ctx => {
    console.log('getJSSDK...',ctx.query)
    const res = await api.getJsConfig(ctx.query)
    ctx.body = res
})

如果能走到wx.ready(),说明这个时候可以使用别的功能那个api了


?2.获取网络状态

在wx.ready()后加,当然在ready()里加最为合理

//获取网络状态
                    wx.getNetworkType({
                        success:function(res){
                            // 返回网络类型2g,3g,4g,wifi
                            const networkType = res.networkType
                            console.log('getNetworkType...', networkType)
                        }
                    })

下图可见当前是wifi


好了,到这里基本上已经知道怎么去调用微信jssdk了,但是呢,开发过程中是前后端分离的,所以我们要有特定的写法


前后端分离的开发

cubeui(前端目录)

安装依赖

npm run watch

quiz(后端目录)

nodemon server.js

项目丢这里,可以自己看看

demo2下载

文档:

02_公众号_网页端下载


相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
1天前
|
小程序
微信小程序开发---购物商城系统。【详细业务需求描述+实现效果】
这篇文章详细介绍了作者开发的微信小程序购物商城系统,包括功能列表、项目结构、具体页面展示和部分源码,涵盖了从首页、商品分类、商品列表、商品详情、购物车、支付、订单查询、个人中心到商品收藏和意见反馈等多个页面的实现效果和业务需求描述。
微信小程序开发---购物商城系统。【详细业务需求描述+实现效果】
|
1天前
|
小程序
关于我花了一个星期学习微信小程序开发、并且成功开发出一个商城项目系统的心得体会
这篇文章是作者关于学习微信小程序开发并在一周内成功开发出一个商城项目系统的心得体会,分享了学习基础知识、实战项目开发的过程,以及小程序开发的易上手性和开发周期的简短。
关于我花了一个星期学习微信小程序开发、并且成功开发出一个商城项目系统的心得体会
|
2天前
|
小程序 前端开发 API
微信小程序全栈开发中的异常处理与日志记录是一个重要而复杂的问题。
微信小程序作为业务拓展的新渠道,其全栈开发涉及前端与后端的紧密配合。本文聚焦小程序开发中的异常处理与日志记录,从前端的网络、页面跳转等异常,到后端的数据库、API调用等问题,详述了如何利用try-catch及日志框架进行有效管理。同时强调了集中式日志管理的重要性,并提醒开发者注意安全性、性能及团队协作等方面,以构建稳定可靠的小程序应用。
10 1
|
2天前
|
小程序 前端开发 API
微信小程序全栈开发中的多端适配与响应式布局是一种高效的开发模式。
探讨小程序全栈开发中的多端适配与响应式布局,旨在实现统一的用户体验。多端适配包括平台和设备适配,确保小程序能在不同环境稳定运行。响应式布局利用媒体查询和弹性布局技术,使界面适应各种屏幕尺寸。实践中需考虑兼容性、性能优化及用户体验,借助跨平台框架如Taro或uni-app可简化开发流程,提升效率。
9 1
|
8天前
|
小程序 JavaScript 前端开发
微信小程序开发必备前置知识:基本代码构成与语法
【8月更文挑战第8天】微信小程序的基本代码构成与语法
15 0
微信小程序开发必备前置知识:基本代码构成与语法
|
17天前
|
人工智能 搜索推荐 安全
从零到一:微信机器人开发的实战心得
从零到一:微信机器人开发的实战心得
53 2
|
21天前
|
移动开发 开发框架 前端开发
微信门户开发框架-使用指导说明书(2)--基于框架的开发过程
微信门户开发框架-使用指导说明书(2)--基于框架的开发过程
|
21天前
|
存储 开发框架 小程序
微信门户开发框架-使用指导说明书
微信门户开发框架-使用指导说明书
|
2天前
|
小程序 前端开发 数据安全/隐私保护
微信小程序全栈开发中的身份认证与授权机制是一个重要而复杂的问题。
微信小程序作为业务拓展的新渠道,其全栈开发中的身份认证与授权机制至关重要。本文概览了身份认证方法,包括手机号码验证、微信及第三方登录;并介绍了授权机制,如角色权限控制、ACL和OAuth 2.0。通过微信登录获取用户信息,利用第三方登录集成其他平台,以及实施角色权限控制和ACL,开发者能有效保障小程序的安全性和提供良好用户体验。此外,还强调了在实现过程中需注重安全性、用户体验和合规性。
6 0
|
5天前
|
小程序 JavaScript

热门文章

最新文章