Code Monkey home page Code Monkey logo

wechat-jssdk's Introduction

wechat-jssdk

npm node Coverage Status npm code style: prettier

微信JSSDK与NodeJS及Web端整合 WeChat JS-SDK integration with NodeJS and Web.

English | Release Notes

wechat-jssdk-demo

主要功能

使用方法

npm install wechat-jssdk --save
# 或者
yarn add wechat-jssdk
const {Wechat} = require('wechat-jssdk');
const wx = new Wechat(wechatConfig);

Wechat 配置项

wechatConfig 为以下格式:

{
  //第一个为设置网页授权回调地址
  wechatRedirectUrl: "http://yourdomain.com/wechat/oauth-callback", 
  wechatToken: "xxx", //第一次在微信控制台保存开发者配置信息时使用
  appId: "xxx",
  appSecret: "xxx",
  card: true, //开启卡券支持,默认关闭
  payment: true, //开启支付支持,默认关闭
  merchantId: '', //商户ID
  paymentSandBox: true, //沙箱模式,验收用例
  paymentKey: '', //必传,验签密钥,TIP:获取沙箱密钥也需要真实的密钥,所以即使在沙箱模式下,真实验签密钥也需要传入。
  //pfx 证书
  paymentCertificatePfx: fs.readFileSync(path.join(process.cwd(), 'cert/apiclient_cert.p12')),
  //默认微信支付通知地址
  paymentNotifyUrl: `http://your.domain.com/api/wechat/payment/`,
  //小程序配置
  "miniProgram": {
    "appId": "mp_appid",
    "appSecret": "mp_app_secret",
  }
}

其他支持的设置都有默认值,基本都是微信API的地址,且基本不会改变, 可以查看 ./lib/config.js.

设置微信环境

1.去微信公众平台

下载类似 MP_verify_XHZon7GAGRdcAFxx.txt 这样的文件放到网站根目录, 如http://yourdomain.com/MP_verify_XHZon7GAGRdcAFxx.txt,微信会验证这个链接.

2.然后在你的express/koa app中提供一个接口给浏览器获取验证信息, @see demo

//express app:
router.get('/get-signature', (req, res) => {
  wx.jssdk.getSignature(req.query.url).then(signatureData => {
    res.json(signatureData);
  });
});
//koa2/koa-router app:
router.get('/get-signature', async ctx => {
  ctx.body = await wx.jssdk.getSignature(ctx.request.query.url);
});

3.获取签名后,进入下一步浏览器端使用方法.

浏览器端

const WechatJSSDK = require('wechat-jssdk/dist/client.umd');
//ES6 import
import WechatJSSDK from 'wechat-jssdk/dist/client.umd';

//没有打包的话直接script扔到html,然后从`window`获取, e.g:
const wechatObj = new window.WechatJSSDK(config)

config应该为:

const config = {
  //前4个是微信验证签名必须的参数,第2-4个参数为类似上面 '/get-signature' 从node端获取的结果
  'appId': 'xxx',
  'nonceStr': 'xxx',
  'signature': 'xxx',
  'timestamp': 'xxx',
  //下面为可选参数
  'debug': true, //开启 debug 模式
  'jsApiList': [], //设置所有想要使用的微信jsapi列表, 默认值为 ['updateAppMessageShareData','updateTimelineShareData','onMenuShareTimeline', 'onMenuShareAppMessage'],分享到朋友圈及聊天记录
  'customUrl': '' //自定义微信js链接
}
const wechatObj = new WechatJSSDK(config);
wechatObj.initialize()
  .then(w => {
    //set up your share info, "w" is the same instance as "wechatObj"
  })
  .catch(err => {
    console.error(err);
  });

验证签名成功后, 就可以自定义你的分享内容了:

sdk默认只注册了updateAppMessageShareDataupdateTimelineShareDataonMenuShareTimeline(wx即将废弃)onMenuShareAppMessage(wx即将废弃)

//自定义分享到聊天窗口
//内部调用 `wechatObj.callWechatApi('updateAppMessageShareData', {...})`, 语法糖而已
wechatObj.updateAppMessageShareData({
  type: 'link',
  title: 'title',
  link: location.href,
  imgUrl: '/logo.png',
  desc: 'description',
  success: function (){},
  fail: function (){},
  complete: function (){},
  cancel: function (){}
});
//自定义分享到朋友圈
//语法糖
wechatObj.updateTimelineShareData({
  type: 'link',
  title: 'title',
  link: location.href,
  imgUrl: '/logo.png'
});

要获取原始的微信对象 wx,可以通过wechatObj.getOriginalWx()来获取。
如果第一次验证失败,可以在error回调里更新签名信息,并重新发验证请求:
wechatObj.signSignature(newSignatureConfig);, newSignatureConfig只需包含:

{
  'nonceStr': 'xxx',
  'signature': 'xxx',
  'timestamp': 'xxx',
}

调用其他微信接口:
wechatObj.callWechatApi(apiName, apiConfig)
apiNameapiConfig请参考微信官方接口文档

OAuth

默认生成微信授权URL为 wx.oauth.snsUserInfoUrlwx.oauth.snsUserBaseUrl,其中的默认回调URL为 wechatConfig 中配置的 wechatRedirectUrl. 你也可以通过调用 wx.oauth. generateOAuthUrl(customUrl, scope, state)来自定义回调地址

//callback url handler
//如"wechatRedirectUrl"配置为 "http://127.0.0.1/wechat/oauth-callback", 你的路由需要为:
router.get('/wechat/oauth-callback', function (req, res) {
  //得到code,获取用户信息
  wx.oauth.getUserInfo(req.query.code)
          .then(function(userProfile) {
            console.log(userProfile)
            res.render("demo", {
              wechatInfo: userProfile
            });
          });
});

TIP: 确保上面的重定向地址域名已经在微信里的授权回调地址设置里设置过。

微信卡券

在wechatConfig设置 card: true 来支持卡券功能的服务端支持, 参考demo.
要查看卡券 APIs, 参考 cards apis

微信支付

在wechatConfig设置 payment: true 来支持微信支付功能的服务端支持, 其他一些支付必须的配置也需要一同设置.
参考 demo.
要查看支付 APIs, 参考 payment apis

小程序

使用小程序的服务端支持(看接口), 在配置里设置小程序的appIdappSecret:

const { Wechat, MiniProgram } = require('wechat-jssdk');
const wechatConfig = {
  "appId": "appid",
  "appSecret": "app_secret",
  //...other configs
  //...
  //小程序配置
  "miniProgram": {
    "appId": "mp_appid",
    "appSecret": "mp_app_secret",
  }
};
const wx = new Wechat(wechatConfig);
//调用小程序接口
wx.miniProgram.getSession('code');

//手动实例化 MiniProgram
const miniProgram = new MiniProgram({
  miniProgram: {
    "appId": "mp_appid",
    "appSecret": "mp_app_secret",
  }
})

使用Stores

Store用来自定义存储token持久化(如文件,数据库等待),实现自己的Store, 请查看API
自带 Store: FileStore, MongoStore,默认为FileStore, 存储到wechat-info.json文件.

APIs

查看 API wiki

Demo

在v3.1.0后,demo页面增加卡券和支付的用例测试, Copy demo/wechat-config-sample.jsdemo/wechat-config.js,
然后在里面里面修改 appId, appSecret, 及其他的配置 如支付的其他配置如果需要使用支付功能的话.

./demo/index.js中设置你自己的appId, appSecret, 然后 npm startnpm run dev, 使用微信开发者工具测试。

Buy me a coffee

如果您觉得这个项目对您有用,可以请我喝杯咖啡 reward-me

LICENSE

MIT @ 2016-present jason

wechat-jssdk's People

Contributors

alichs avatar jasonboy avatar lk9100 avatar snyk-bot avatar yuezk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wechat-jssdk's Issues

卡券问题

现在getCardExt 只有outer_str参数,我需要outer_id,能加上吗

调用语法糖callWechatApi时报错,急急急

版本:"wechat-jssdk": "^3.0.11"

const weConfig = {
......
jsApiList:['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQZone'],
success:function(wechatObj ){ console.log('签名成功');},
......
}
const wechatObj = new WechatJSSDK(weConfig);

开启debug
签名成功的回调能执行到
当调用 wechatObj.callWechatApi('onMenuShareTimeline', apiConfig);
image

这是什么情况

vue无法使用fs

hi,配置中有paymentCertificatePfx: fs.readFileSync(path.join(process.cwd(), 'cert/apiclient_cert.p12')),而在vue-cli中无法引入fs,请问有什么解决方案?

小程序支付签名问题

Payment.js generateChooseWXPayInfo函数 appId: this.wechatConfig.appId
这个会appid是我的公众号appid,在miniProgram下还有一个appid这个是小程序的
那么,我在生成wx.requestPayment所需内容的时候签名就有问题了。

请问,现在支付是不是还没有完全适配小程序?

success回调不起作用?

const wxObj = new WechatJSSDK({
            ...wxConf,
            'success': () => {
              console.log(wxObj.wx, '????')
            },
          })
          console.error(wxObj.wx)
          setTimeout(() => console.error(wxObj.wx, '~!!!!!!!'), 1500)

sucess回调里面的没有被调用,
只有settimeout可以取到wxObj.wx

Cannot read property 'findOneAndUpdate' of undefined

系统:Ubuntu 18.04.3 x64
Node:v12.14.1
MongoDB: 4.0.3 (升级至4.2.2一样

只用了小程序的功能

const { Wechat, MongoStore } = require('wechat-jssdk')

// =========> TypeError: Cannot read property 'findOneAndUpdate' of undefined <==========
const mongoStore = new MongoStore({
  dbHost: process.env.DB_HOST,
  dbPort: process.env.DB_PORT,
  dbName: 'cat',
  dbOptions: {
    user: process.env.DB_USER,
    pass: process.env.DB_PASS,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true
  }, // extra options passed to mongoose
  limit: 10 // how many url signature and oauth token items should be initialized from db, default: 20
})

const wechatConfig = {
  appId: process.env.APP_ID,
  appSecret: process.env.APP_SECRET,
  // 小程序配置
  miniProgram: {
    appId: process.env.APP_ID,
    appSecret: process.env.APP_SECRET
  },
  store: mongoStore
}
const wx = new Wechat(wechatConfig)

module.exports = wx

报错文字

/home/nodejs-web/mpi-miniprogram/node_modules/wechat-jssdk/lib/store/MongoStore.js:350
      return this.GlobalToken.findOneAndUpdate({}, Object.assign({}, gt), {
                              ^

TypeError: Cannot read property 'findOneAndUpdate' of undefined
    at MongoStore.flushGlobalToken (/home/nodejs-web/mpi-miniprogram/node_modules/wechat-jssdk/lib/store/MongoStore.js:350:31)
    at MongoStore.flush (/home/nodejs-web/mpi-miniprogram/node_modules/wechat-jssdk/lib/store/MongoStore.js:473:12)
    at Timeout._onTimeout (/home/nodejs-web/mpi-miniprogram/node_modules/wechat-jssdk/lib/store/Store.js:100:47)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7)

TypeError: Wechat is not a constructor

Hi,
I found this repo from Medium post. Great job!

However, after I checkout master repo I got follow Error, could you please help?

PS C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend> npm start

[email protected] start C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend
node ./bin/www

C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend\app.js:30
const wx = new Wechat(wechatConfig);
^

TypeError: Wechat is not a constructor
at Object. (C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend\app.js:30:12)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object. (C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend\bin\www:7:11)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node ./bin/www
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xxxx\AppData\Roaming\npm-cache_logs\2020-07-19T08_03_03_260Z-debug.log
PS C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend> npm -v
6.14.5
PS C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend> node -v
v12.18.2
PS C:\Users\xxxx\Documents\GitHub\wechat_programs\WeChat-JSSDK-Backend> npm run
Lifecycle scripts included in wechat-demo:
start
node ./bin/www

available via npm run-script:
dev
nodemon ./bin/www

Is this coming from the version of nodejs and npm? I am using the latest version as below:
npm: 6.14.5
node: v12.18.2

Thanks

usage clarification

hi! I'm trying to check how to use the oAuth part

what we really want is to get the user's openID when they are accessing an H5 page linked from within an official account (from a menu item actually)

looking at the oAuth callback
https://github.com/JasonBoy/wechat-jssdk#oauth

//default callback url
router.get('/wechat/oauth-callback', function (req, res) {
  wx.oauth.getUserInfo(req.query.code)
          .then(function(userProfile) {
            console.log(userProfile)
            res.render("demo", {
              wechatInfo: userProfile
            });
          });
});

so this is server side code obviously. what is wx in this case?

const wx = new WeChat(wechatInfo);

Am i right to understand,
you've created an npm wechat JS-SDK, which is different from the official tencent js-sdk
and you're suggesting to initialize it with wx ?
this is a bit confusing, as the client side official tencent SDK is also referred to as wx in their examples.

浏览器端能不能有个ready方法等待核心库的加载?很苦恼~

刚new完WechatJSSDK,并不能马上获取到window.wx,那么自然而然使用里面的callWechatApi方法通通报错!!,看了源码才发现new的过程中还有一个loadScript方法在异步加载核心库,这下蛋疼了,没有对外提供一个ready方法让我们等待这个异步,那么何时使用wx的方法,很苦恼,计时器都不那么好用,希望能提供一个该接口(考虑做个事件触发器单独触发一个ready,或者构造器里面直接弄个回调也可以简单粗暴好用)。谢谢

Use stubs for quick unit tests

currently all tests are based on the wechat server apis, aka e2e tests, which really slow down the test process, also it's hard to test some error handling, so it could be great to also add stubs to boost UT testing.

invalid credential, access_token is invalid or not latest hint

现在有极小概率出现这个提示,可能是其他地方调用了access_token,导致我们自己的过期了,我目前就用了co-wechat-api和wechat-jssdk。
过期后我可能要等两个小时候业务才会恢复。能麻烦加入一个重新获取的机制吗,比如收到40001错误,就重新获取access_token,然后重新请求。

你好,希望可以自定义scope,这样的话, 非公众号appid也可以使用这个package了

你好,@JasonBoy,希望可以自定义scope,这样的话, 非公众号appid也可以使用这个package了

我看了package中的lib/oauth.js文件,里面有一些默认的配置,默认配置的scope是snsapi_userinfo,这个scope公众号(mp.weixin.qq.com)里面生成的appid可以使用,但是通过open.weixin.qq.com生成的开发者appid是无法使用的,open.weixin.qq.com里面生成的app只能使用snsapi_login scope,

但是在wechat-jssdk的package中并没有自定义scope的地方,希望可以配置一下,谢谢,这个sdk非常棒!

(也可能是我没有找到。如果是我没有找到,希望可以帮助下我,thx)

支付请求95%的几率出现Z_DATA_ERROR:unknown compression method

如题,之前都是好好的,不知道为何从7月6号开始出现这种错误,而且不是100%出现,是小几率正常
{ ReadError: unknown compression method
at EventEmitter.emitter.on (/var/www/XXXX/deploy/node_modules/_got@9.6.0@got/source/as-promise.js:28:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
name: 'ReadError',
code: 'Z_DATA_ERROR',
host: 'api.mch.weixin.qq.com',
hostname: 'api.mch.weixin.qq.com',
method: 'POST',
path: '/pay/unifiedorder',
....

不支持的压缩方法???没找到是哪里的原因,是微信支付请求处理改版了还是其他什么BUG?
我尝试把got换成了axios,就恢复正常了,希望关注下,目前在我们项目中got确实有问题

能支持proxy吗?

unifiedOrder之类的函数必须在服务器上调用,调试时非常麻烦,能够增加proxy设置可以轻松很多

请教OAuth如何使用

@JasonBoy 请教一下,现在部署OK后,点击OAuth和OAuth without new code都会显示
wechat Error: please get new code!
wechat at /home/gump/work/gump/github/wechat-jssdk/lib/OAuth.js:164:23
wechat at process._tickCallback (node.js:368:9) +0ms
查看key都是undefined,打印req.session后,信息如下
{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"}}
其中没有openid,请教是配置的问题吗?
同时请教demo下的oauth.html是点击OAuth后跳转吗?

Why the callback is not run

const wechatObj = new WechatJSSDK(config);
wechatObj.initialize()
.then(w => {
console.log('wechatObj w: ', w);// deos not run
//set up your share info, "w" is the same instance as "wechatObj"
})
.catch(err => {
console.error(err);
});

I only get this log 'Wechat script loaded successfully!'.

使用Oauth时出现的问题

你好!

我按照readme配置了微信公众平台,并修改了index.js后,点击Oauth一直有问题。步骤是:

配置:

  1. 将我的微信号在公众平台注册了一个测试账号,在接下来的页面中按说明做了配置。token服务器在公网上(配置成类似:http://1.2.3.4:12345),验证通过。

config_wechat_server

2. 使用这个页面的token,appid,appsecrect配置到index.js上去. 3. "wechatRedirectUrl"没有修改("http://127.0.0.1/oauth") 4. 启动后,使用微信web开发者工具访问127.0.0.1,各种验证的load是ok的:

22

5. 然后访问Oauth页面,却进入页面:

3

在进入这个页面前,网页console有GET 一个url失败(ERR_BLOCKED_BY_CLIENT)的错误。

请问以上配置步骤是否有问题?有哪里做得不对吗?

非常感谢!

can't use jssdk in react

用import时,提示define 错误,去掉后提示如下:
import WechatJSSDK from '../components/weichat-jssdk/client'
"export 'default' (imported as 'WechatJSSDK') was not found in 'weichat-jssdk/client'

采用//const WechatJSSDK = require( '/weichat-jssdk/client')用的时候浏览器出错

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.