Created
February 29, 2016 07:55
-
-
Save morlay/82981c7ace14759275b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment