微信公众号 - 开发配置
公众号开发需要配置服务器地址,验证消息来源,并获取access_token来调用各种API。
开发流程
| 步骤 | 操作 | 说明 |
|---|---|---|
| 1. 注册账号 | 访问 mp.weixin.qq.com | 注册并完成认证(个人/企业) |
| 2. 服务器配置 | 填写URL、Token、EncodingAESKey | 微信会向URL发送GET请求验证 |
| 3. 验证签名 | 校验signature参数 | 将token、timestamp、nonce排序后SHA1加密比对 |
| 4. 获取Token | 调用 /cgi-bin/token 接口 | 使用AppID和AppSecret换取access_token |
| 5. 接口调用 | 携带access_token请求API | 发送消息、管理菜单、获取用户信息等 |
服务器验证 - Node.js 示例
const express = require('express')
const crypto = require('crypto')
const app = express()
const TOKEN = 'your_token'
app.get('/wechat', (req, res) => {
const { signature, timestamp, nonce, echostr } = req.query
const arr = [TOKEN, timestamp, nonce].sort().join('')
const hash = crypto.createHash('sha1').update(arr).digest('hex')
if (hash === signature) {
res.send(echostr)
} else {
res.status(403).send('验证失败')
}
})
获取 access_token
const axios = require('axios')
let tokenCache = { token: '', expireAt: 0 }
async function getAccessToken() {
if (Date.now() < tokenCache.expireAt) {
return tokenCache.token
}
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=APP_SECRET`
const { data } = await axios.get(url)
tokenCache = {
token: data.access_token,
expireAt: Date.now() + (data.expires_in - 300) * 1000
}
return tokenCache.token
}