Skip to content

Instantly share code, notes, and snippets.

@aisk
Created October 11, 2016 09:56
Show Gist options
  • Save aisk/ada0357757121f83e795c195028c6eb5 to your computer and use it in GitHub Desktop.
Save aisk/ada0357757121f83e795c195028c6eb5 to your computer and use it in GitHub Desktop.
LeanCloud WeApp Integration
AV.Cloud.define('loginWeApp', function(request, response) {
var WX_APP_ID = 'WX_APP_ID'
var WX_SECRET = 'WX_SECRET';
var code = request.params.code;
var signature = request.params.signture;
var rawData = request.params.rawData;
var userInfo = JSON.parse(rawData);
var openid, user;
AV.Cloud.httpRequest({
url: 'https://api.weixin.qq.com/sns/jscode2session',
params: {
appid: WX_APP_ID,
secret: WX_SECRET,
js_code: code,
grant_type: 'authorization_code',
}
}).then(function(result) {
// TODO: mock api result
openid = "1";
return;
var data = JSON.parse(result.text);
if ('errmsg' in data) {
throw new Error(data.errmsg);
}
openid = data.openid;
var sessionKey = data.session_key;
var hash = require('crypto').createHash('sha1');
hash.update(rawData);
hash.update(sessionKey);
var signature2 = hash.digist('hex');
if (signature2 !== signature) {
throw new Error("invalid raw data signature");
}
}).then(function() {
return AV.User.signUpOrlogInWithAuthData({
uid: openid,
access_token: "",
}, 'weapp');
}).then(function(_user) {
user = _user;
user.set('username', userInfo.nickName);
user.set('gender', userInfo.gender);
user.set('province', userInfo.province);
user.set('country', userInfo.country);
user.set('avatarUrl', userInfo.avatarUrl);
return user.save();
}).then(function() {
response.success(user);
}).catch(function(err) {
response.error(err);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment