npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

weixin-nodejs

v2.0.0

Published

快速开发微信公众号的框架

Downloads

30

Readme

使用

npm i weixin-nodejs -S

参考文档

API 文档 Gitee 课程作业 npm

创建项目

"dependencies": {
    "dotenv": "^10.0.0",
    "weixin-nodejs": "^1.2.0"
  }

dotenv 不是必须的

const { WX } = require('weixin-nodejs')

const path = require('path')

// 如果你没有使用 dotenv 则删除下面一行代码
require('dotenv').config()


// 如果你没有使用dotenv,则不应该使用process.env
new WX({
    token: process.env.token,
    port: process.env.port,
    appid: process.env.appid,
    secret: process.env.secret,
    plugin_path: path.resolve(__dirname, 'plugins'),
})

快速入门

const { WX, Plugin } = require('weixin-nodejs')
const wx = new WX({
    token: 'token',
    port: 30081,
})
wx.use(class extends Plugin {
    process() {
        return 'Hello'
    }
})

如果你成功执行,你发送任何内容给微信公众号,都将收到 Hello 这条文本消息 你的插件必须继承Plugin
你的插件必须被use方法调用才生效,比如wx.use(Hello)


可使用的模块

  /** 临时素材 */
  public media: Media
  /** 自定义菜单 */
  public menu: Menu
  /** 客服 */
  public custom: Custom
  /** 用户管理 */
  public user: User
  /** 标签管理 */
  public tag: Tag
  /** 二维码工具 */
  public qrcode: Qrcode
  /** 群发 */
  public mass: Mass
  /** 模板消息 */
  public template: Template

如何开发插件

1. 使用ES6语法创建一个类,且这个类继承Plugin基类

// 这是一个最简单的插件了,但是它不具备处理能力
class Text extends Plugin {}

2. 想让插件只处理某一种类型的消息

class Text extends Plugin {
    test() {
        return this.push.is('text')
    }
}

3. 想让插件被动回复文本

class Text extends Plugin {
    test() {
        return this.push.is('text')
    },
    process() {
        return this.reply.text('Hello')
    }
}

4. 使用插件管理菜单

wx.use(class extends Plugin {
    test() {
        return this.push.is('text') && this.params.Content == '创建'
    }
    async process() {
        const res = await this.menu.create([
            {
                type: 'click',
                name: '今日歌曲',
                key: '今日歌曲',
            },
            {
                type: 'click',
                name: '歌手简介',
                key: '歌手简介',
            },
            {
                name: '菜单',
                sub_button: [
                    {
                        type: 'view',
                        name: '搜索',
                        url: 'http://www.baidu.com'
                    },
                    {
                        type: 'view',
                        name: '视频',
                        url: 'http://v.qq.com'
                    },
                    {
                        type: 'click',
                        name: '赞',
                        key: '赞'
                    },
                ]
            }
        ])

        return this.reply.text(JSON.stringify(res))
    }

})

同时也支持处理菜单事件,更多内容请查看 API 文档

后台管理

你可通过直接访问主机监听的端口来确定是否启动成功 正常情况下,将显示后台管理页面,可以辅助你维护这个公众号

自动加载插件

提供了一个自动加载插件的功能,如果你想使用它,你需要在参数中填写plugin_path字段。 它的值是一个目录的路径,这样就会加载这个目录下面所有的插件了。

如果你填写正确的 appidsecret 那么在插件里 sccess_token 是可用的,可以放心调用

访问令牌的时效性

由于 access_token 是通过异步的方式获取的,所以它在new WX()后不能立马使用需要 access_token 才能调用的接口,因为它还未就绪 如果你想立刻使用它,应该这样使用

await wx.accessToken?.wait();
// 一个小小的例子
const wx = new WX({
    plugin_path: path.join(__dirname, 'plugins'),
})

建议使用 path 库处理路径

当然,你想使用手动加载或者自己写一个自动加载的方法也是可以的。

二次开发

wx 是基于 koa2 开发的,我们公开了这个属性(koa2的实例),你可以像开发 koa2 那样在 wx.koa 上编写你的代码。

// 使用这个实例你需要安装 koa-router
const router = new Router();
router.get('/test', (ctx) => {
    ctx.body = 'test'
})
wx.koa.use(router.routes())

仓库

对于微信公众号来说,虽然它也是响应 http请求,但是它一般只能收到来自微信服务器的的请求,这样我们的session技术不能再满足我们的日常使用

我们在session概念上设计了store,它和session的功能类似,但是它是基于 openId 的存储的。

每个用户都有一个自己仓库来存储自己的信息

它支持数据持久化,你需要在配置里传入sotre_path字段,这样就可以开启它。

数据持久化就是将数据永久的保存在硬盘上。不会因为程序/项目的重启而丢失数据。

const wx = new WX({
    // 它有个默认值,就是 ./sotre
    sotre_path: path.join(__dirname, 'stores'), // 请使用 path 处理路径,内部未对路径做任何处理。
})

下面,你可以在插件里调用this.store的方法来管理你的仓库了,请记住,如果你想数据持久化,那么需要调用save方法。

具体的使用方法建议参考 API 文档

目前,数据持久化是以 json 文件 的形式存储在本地计算机上的,你可以覆盖原本的存储方式,那样就可以将 stroe 存储到数据库或者其他任何合适的地方。

可能遇到的问题

1. 我的80端口被占用了

你可使用反向代理技术解决这个问题 如果你使用的是apache,你可能需要以下配置

在 httpd.conf 中开启这两项配置(将#号去掉)

# 大约在 149 行
LoadModule proxy_module modules/mod_proxy.so
# 大约在 157 行
LoadModule proxy_http_module modules/mod_proxy_http.so

在对应的网站***.cong文件里使用如下配置

<VirtualHost *:80>
    # 监听的域名
	ServerName weixin.***.***
    # 开启反向代理
	ProxyRequests off 
    # 将 / 转发到 http://localhost:30080/
	ProxyPass / http://localhost:30080/ 
</VirtualHost>

这时你只需要监听30080即可
而微信公众平台上则填写 weixin.***.***(你的域名)

2. 我需要在本地电脑上开发

可以使用内网穿透解决这个问题
如果你拥有自己服务器,可以搭建,比如 nps-gitee nps-github
你也可以从其他提供内网穿透服务的提供商那里解决这个问题,比如花生壳