纯属分享
var config = require('./admin/wx/config/config'); var API = require('wechat-api'); var api = new API(config.appid, config.appsecret); api.getAccessToken(function (err, token) { console.log(err); console.log(token); //accessToken }); var menu = JSON.stringify(require('./admin/wx/config/wx_menu.json')); api.createMenu(menu, function (err, result) { console.log(result); // { errcode: 0, errmsg: 'ok' } });
config.js
module.exports = { appid : "wx6238bb5b691334fc", appsecret : "da41b732f36f9d390eb9835605a38423" }
wx_menu.json
{ "button":[ { "type":"click", "name":"今日歌曲", "key":"V1001_TODAY_MUSIC" }, { "type":"click", "name":"歌手简介", "key":"V1001_TODAY_SINGER" }, { "name":"菜单", "sub_button":[ { "type":"view", "name":"搜索", "url":"http://www.soso.com/" }, { "type":"view", "name":"视频", "url":"http://v.qq.com/" }, { "type":"click", "name":"赞一下我们", "key":"V1001_GOOD" } ] } ] }
result 返回结果为:
{ errcode: 0, errmsg: 'ok' } 者表示成功!
为下面这个就是表示没有权限使用自定义菜单:
{ errcode: 48001,errmsg: 'api unauthorized hint: [iHQZfa0607vr46!]' }
http://mp.weixin.qq.com/debug 这个地址可以测试
还有一种方法:
var u = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=m9UgecuDsgZurHHk17MBYPJEtCtZ-2-whaYodfDkXhvRpyy-NL06nJz5IA9EYplajmz8DNYad8yxP2NC1T5jHZw6k25eNVjYQwohX7PSO6xMaNo6z6wTOHceuF6KCz0qBSLhAFAOFY'; var content = JSON.stringify(require('./config/wx_menu.json'));//这是需要提交的数据 var options = { url: u, form: content, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; request.post(options, function (err, res, body) { if (err) { console.log(err) }else { console.log(body); } })
这种方式得先拿到 access_token 值,这个值是2个小时更新一次
代码:
var qs = require('querystring');
var queryParams = { 'grant_type': 'client_credential', 'appid': config.appId, 'secret': config.appSecret }; var wxGetAccessTokenBaseUrl = 'https://api.weixin.qq.com/cgi-bin/token?'+qs.stringify(queryParams); var options = { method: 'GET', url: wxGetAccessTokenBaseUrl }; request(options, function (err, res, body) { if (err) { console.log(err); } else { console.log(body); } });