我有一个预订网络应用程序,我们正考虑在预订后通过微信向用户发送消息。
我查看了微信文档,看到我们需要用户的openid,但我不知道如何获得这个。
我是否必须编制“通过微信登录”按钮?
答案 0 :(得分:0)
您需要获取微信官方帐号才能获得用户开放ID,请抛出https://open.weixin.qq.com/
答案 1 :(得分:0)
这是我们可以用来在登录时获取 openId 的一种方法。
步骤:
wx.login
登录用户。https://api.weixin.qq.com/sns/jscode2session?
。 // Client-side
/**
* @description Handle the login to wechat
* https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
* @returns {Promise} Return the user's wechat information.
* {"openId", "nickName","gender", "city", "province", "country", "avatarUrl" }
*/
export function handleWxLogin() {
return new Promise((resolve, reject) => {
wx.login({
success : async function (res) {
const js_code = res.code;
const userInfo = getUserInfo()
const openID = getOpenID(js_code)
const payload = {
...await userInfo,
...{openID:await openID}
}
console.info('handleWxLogin payload:', payload);
resolve(payload)
},
fail: function(err){
console.log('wx.login error:',err);
reject(err)
}
})
})
}
/**
* @description GET request to get the OpenID from the server.
* @param {String} js_code
* @returns {Promise} Return openID
*/
async function getOpenID(js_code){
// A GET request to our back-end.
return http.get(`wxUnionID?js_code=${js_code}`).then(res => {
if(res){
return res.data.openid;
}
}).catch(err => {
console.warn('getOpenID error:',err,);
})
}
/**
* @description Get the userInfo with wx.getUserInfo
* https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
* @returns {Promise} returns an object
*/
function getUserInfo(){
return new Promise((resolve, reject) => {
wx.getUserInfo({
success: async function(res) {
const userInfo = res.userInfo;
resolve(userInfo)
},
fail: function(err){
console.warn('getUserInfo error:',err,);
reject('getUserInfo error:',err)
}
})
})
}
在服务器端:
js_code
: 登录时提供的代码apiid
和 secret
:可以在 developer dashboard
const bent = require("bent");
/**
* @description We get the openid from weixin.
* https://developers.weixin.qq.com/miniprogram/en/dev/api-backend/open-api/login/auth.code2Session.html
* @param {String} js_code (the code provided during the login)
* APP_ID and APP_SECRET can be found on the developper dashboard.
* @returns {Promise} {session_key, openid}
*/
module.exports = {
wxUnionID: async ctx => {
const query = ctx.request.query;
const js_code = query.js_code;
const getJSON = bent("json");
const user = await getJSON(
`https://api.weixin.qq.com/sns/jscode2session?appid=${process.env.APP_ID}&secret=${process.env.APP_SECRET}&js_code=${js_code}`
);
console.info('user:', user)
if(user.openid){
ctx.send({
statusCode: 200,
error: null,
data:user,
});
}else{
ctx.send({
statusCode: 400,
error: user,
data:null,
});
}
}
};