微信小程序获取用户微信openID

一、需要三个参数:

1、获取code

2、小程序AppID

3、小程序密钥AppSecret 

二、代码


Page({
 
    /**
     * 页面的初始数据
     */
    data: {
        wxCode: "", // 获取到的code
        wxOpenId: "初始值" // 获取到的OpenId
    },
 
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // ====== 【获取Code】
        wx.login({
            success: (res) => {
                console.log(res);
                this.setData({
                    wxCode: res.code,
                })
                // ====== 【获取OpenId】
                let m_code = this.data.wxCode; // 获取code
                let m_AppId = "wx1111"; // appid
                let m_mi = "111111"; // 小程序密钥
                console.log("m_code:" + m_code);
                let url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + m_AppId + "&secret=" + m_mi + "&js_code=" + m_code + "&grant_type=authorization_code";
                console.log(url);
                wx.request({
                    url: url,
                    success: (res) => {
                        console.log(res);
                        this.setData({
                            wxOpenId: res.data.openid
                        })
                        //获取到你的openid
                        console.log("====openID=======");
                        console.log(this.data.wxOpenId);
                    }
                })
            }
        })
    },
 
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
 
    },
 
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
 
    },
 
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
 
    },
 
})

猜你喜欢

转载自blog.csdn.net/L_yupeng/article/details/129272771