关于javascript:❤️十分钟快速学会使用Nodejs全栈开发微信公众号建议收藏

10次阅读

共计 11029 个字符,预计需要花费 28 分钟才能阅读完成。

原文地址:https://blog.csdn.net/qq_32442973/article/details/120475806

一、筹备

  1. 注册微信订阅号
  2. 注册小程序测试号
  3. sunny-ngrok 工具装置及注册账号

留神:sunny-ngrok 的原型是 ngrok,不过 ngrok 是国外的,sunny-ngrok 是国内的一个私服,速度更快了,次要作用是域名转发,模仿公网 ip 和端口,甚至能够配置给客户在公网上展现我的项目。地址:http://www.ngrok.cc/
, 进去后注册开明隧道,有收费的。
记住:一个微信号只能注册一种微信产品,然而能够治理多个。

这是我的隧道:(收费的如果启动不了就间接用这个吧)

应用 sunny-ngrok 尝试一次转发:
下载工具,启动工具,输出隧道 id,回车

阐明 127.0.0.1:3000 曾经被转发到 zhifieji.vipgz4.idcfengye.com 的公网 ip 上了。

建个 weixin 目录,npm 初始化:

npm init -y

把上面的内容复制到 package.json 里:

{
  "name": "weixin-lesson",
  "version": "1.0.0",
  "description": "微信开发",
  "main": "index.js",
  "directories": {"doc": "doc"},
  "scripts": {
    "sunny": "./bin/sunny clientid 62d16df91a118fd3",
    "ngrok": "./bin/ngrok http 3000",
    "test": "echo \"Error: no test specified\"&& exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git@gitlab.kaikeba.com:web_dev/weixin-lesson.git"
  },
  "author": "","license":"ISC","dependencies": {"axios":"^0.18.0","co-wechat":"^2.3.0","co-wechat-oauth":"^2.0.1","crypto":"^1.0.1","express":"^4.16.4","jsonwebtoken":"^8.4.0","koa":"^2.6.2","koa-bodyparser":"^4.2.1","koa-compress":"^3.0.0","koa-jwt":"^3.5.1","koa-route":"^3.2.0","koa-router":"^7.4.0","koa-socket":"^4.4.0","koa-static":"^5.0.0","koa-views":"^6.1.5","koa-websocket":"^5.0.1","koa-xml-body":"^2.1.0","moment":"^2.23.0","mongoose":"^5.4.4","promise-redis":"0.0.5","pug":"^2.0.3","redis":"^2.8.0","request":"^2.88.0","request-promise":"^4.2.2","socket.io":"^2.2.0","watch":"^1.0.2","wechat":"^2.1.0","wechat-oauth":"^1.5.0","xml2js":"^0.4.19"}
}

而后装置依赖

npm install
# 或
yarn

再在 weixin 目录下建设 seed 目录,seed 目录下建设 index.js 和 index.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()
app.use(bodyParser())
const router = new Router()
app.use(static(__dirname + '/'))

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

index.html:

<!DOCTYPE html>
<html>

<head>
    <title> 全栈开发微信公众号 </title>
    <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>
    </div>
    <script>
        var app = new Vue({
            el: '#app',
            data: {value: 'input'},

            methods: {click: function () {console.log('click')
                }
            },
            mounted: function () {},
        });
    </script>
</body>

</html>

在 seed 目录关上终端,执行 nodemon(须要装置), 3000 端口关上 127.0.0.1

npm install -g nodemon
nodemon



后面说通过 ngrok 把 3000 端口转发到了 zhifieji.vipgz4.idcfengye.com 上,咱们关上这个网址试下:

二、应用音讯接口

微信自带音讯主动回复性能,能够在公众平台设置,然而很死板,无奈动静回复音讯

进入微信开发者工具,申请公众平台测试账号

有一些配置,填写转发的域名,token 随便,要和服务器的用的一样

接口配置的 URL 就是转发的网址加了 /wechat,再去提交接口配置信息(要多试试,能力提交胜利)。

再就是在我的项目 seed 目录里配置,新建一个 conf.js,把后面的 appid、appsecret、token 带上:

module.exports={
    appid: 'wx77f481fc8a9113a4',
    appsecret: '2b84470b9fb0f8166a8518c5b40edaf9',
    token: 'qweqwe'
}

在 index.js 里引入,应用一个库 co-wechat,所以 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')// 引入 conf
app.use(bodyParser())
const router = new Router()
app.use(static(__dirname + '/'))

const wechat = require('co-wechat')// 应用 co-wechat 库
router.all('/wechat', wechat(conf).middleware(
    async message => {console.log('wechat:', message)
        return 'Hello World' + message.Content
    }
))

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

知识点:co- 结尾的库是代表着满足异步要求的库

胜利后,这个时候呢,能够关注上面的测试号二维码

发送 1,会回复 Hello World 1(如果是设置的没有这中获取用户发送的信息的办法,所以有时候也须要 api),如下图:

三、微信一些 api 的调用

相干文档:https://developers.weixin.qq….

获取 token:

const axios = require('axios')
const tokenCache = {
    access_token:'',
    updateTime:Date.now(),
    expires_in:7200
}

router.get('/getTokens',async ctx => {// 获取 token
    const wxDomain =  `https://api.weixin.qq.com`
    const path = `/cgi-bin/token`
    const param = `?grant_type=client_credential&appid={conf.appid}&secret={conf.appsecret}`
    const url = wxDomain + path + param
    const res = await axios.get(url)
    Object.assign(tokenCache,res.data,{updateTime:Date.now()
    })
    ctx.body = res.data
})

获取用户信息

router.get('/getFollowers',async ctx => {// 获取用户信息
    const url = `https://api.weixin.qq.com/cgi-bin/user/get?access_token=${tokenCache.access_token}`
    const res = await axios.get(url)
    console.log('getFollowers:',res)
    ctx.body = res.data
})

以上为原生的写法,实际上咱们十有库能够用的。

应用 co-wechat-api

yarn add co-wechat-api 
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
})

四、全局票据

全局票据须要基于 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
})


再在 index.html 中加上一个按钮和一个按钮点击办法:

<cube-button @click='getFollowers'>getFollowers</cube-button>
 async getFollowers(){const res = await axios.get('/getFollowers')
      console.log('res',res)
},


动动小手点击一下:(这个 getFollwers 拿到了数据)

五、音讯推动

就相似于这个,手机微信扫码微信公众平台前台发送 1 或者 2,饼图主动统计 1 和 2 发送的次数。

后盾(模拟器)会显示前台(手机微信在测试订阅号)的推送,而且更新 echart。
代码为上面的 vote 局部,前面会放出代码。

六、Oauth2 认证流程

首先要晓得有三个端,浏览器,服务器,微信服务器。

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

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

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

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

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

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

最初当服务器失去令牌认证胜利后,发给浏览器一个指令,刷新界面

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

应用微信开发者工具,抉择公众号网页,用来预览。

PS:以上代码中

  1. 音讯推动我放在 vote 目录了
  2. 残余的 api 调用办法放在了 seed 目录

七、实现一个微信认证登录

配置 js 接口平安域名,就是咱们转发的公网域名(不必带协定):zhifieji.vipgz4.idcfengye.com

再就是每个微信接口 api 那里也要受权域名,即下图的批改地位,批改的和下面一样:(zhifieji.vipgz4.idcfengye.com)


把后面的我的项目中 seed 目录拷贝一份叫做 seed_up,咱们给予后面的在 seed_up 中持续干!
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:

<!DOCTYPE html>
<html>

<head>
    <title> 全栈开发微信公众号 </title>
    <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});

// 以下为 seed_up 新增

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)
    }
)

写进去成果如下:完满

https://www.qq.com/video/e327…

八、调用微信 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 调用办法也是如此!

还有一点,通常咱们十前后端拆散的开发我的项目,所以我把我的项目改成了前后端拆散。

九、前后端拆散的开发

1、新建了个 weixin_pro 的我的项目
2、将 weixin 我的项目的 package.json 复制到 weixin_pro
3、分一个 cube-ui 目录为前端代码
4、分一个 quiz 目录为后端代码

5、weixin_pro 下装置依赖,为后端依赖
6、cube-ui 下装置依赖为前端依赖
7、别离启动前端代码后后端代码

运行成果如下:

https://www.qq.com/video/l327…

十、代码地址

前后端拆散前的代码:https://gitee.com/huqinggui/w…
前后端拆散后的代码:https://gitee.com/huqinggui/w…

🔥热门举荐🔥
表弟说看了这本书后,他的 TypeScript 技术曾经登峰造极了
手把手教你在 Vue 中应用 JSX,不怕学不会!【倡议珍藏】
2021 年的几次面试让我死磕了 17 道 JS 手写题!
大前端根本知识点及面试重灾区学习目录
一个聊天室案例带你理解 Node.js+ws 模块是如何实现 websocket 通信的!
npm 常用命令以及 npm publish 常见问题解决办法

正文完
 0