morlay
2/29/2016 - 7:55 AM

WechatJSSDKWrapper.js

import _ from 'lodash';

const wechatScript = '//res.wx.qq.com/open/js/jweixin-1.1.0.js';

export const loadSdk = () =>
  new Promise((resolve) => {
    require('scriptjs')(wechatScript, () => {
      resolve(global.wx);
    });
  });

const setConfig = _.curry(({ appId, timestamp, nonceStr, signature }, wx) =>
  new Promise((resolve, reject) => {
    let isError = false;
    wx.config({
      appId,
      timestamp,
      nonceStr,
      signature,
      jsApiList: Object.keys(wx)
    });
    wx.error((err) => {
      isError = true;
      reject(err);
    });
    wx.ready(() => {
      // When has error the ready callback will be called too,
      // Tiny timeout to ignore error callback;
      setTimeout(() => {
        if (!isError) {
          resolve(wx);
          console.log('wechat config is ready');
        }
      }, 0.02);
    });
  })
);

const shareRegister = _.curry(({ title, desc, imgUrl, link, onShareSuccess, onShareCancel }, wx) => {
  [
    'onMenuShareTimeline',
    'onMenuShareAppMessage',
    'onMenuShareQQ',
    'onMenuShareWeibo',
    'onMenuShareQZone'
  ].map((eventName) => wx[eventName]({
    title: eventName === 'onMenuShareTimeline' ? desc : title,
    desc,
    imgUrl,
    link,
    success: onShareSuccess,
    cancel: onShareCancel
  }));
  return Promise.resolve();
});

const createWechatRegister = _.curry(({ appId, timestamp, nonceStr, signature }, curryFn, curryFnOptions) =>
  loadSdk()
    .then(setConfig({ appId, timestamp, nonceStr, signature }))
    .then(curryFn(curryFnOptions))
);

export default ({ appId, timestamp, nonceStr, signature }) => {
  const wechatRegister = createWechatRegister({ appId, timestamp, nonceStr, signature });
  return {
    shareRegister: wechatRegister(shareRegister)
  };
};