首页 > uniapp
微信通过code获取unionid
来源:TP课堂 时间:2024-01-02 点击:643
<template>
  <view class="container">
    <!-- 显示一个按钮 -->
    <button @click="loginWithWechat" type="primary">微信授权登录</button>
  </view>
</template>
 
<script>
export default {
  methods: {
    loginWithWechat() {
      // 调用微信 API 获取 code
      wx.login({
        success(res) {
          if (res.code) {
            const code = res.code;
            
            // 将 code 发送到服务器端进行校验
            uni.request({
              url: 'https://gen.cn/index/get_weixin_unionid', 
              method: 'POST',
              data: {
                code: code
              },
              success(response) {
                // 校验成功,获取 openid 等必要参数
                const userInfo = response.data;
                
                // 将用户信息存储到本地缓存中
                uni.setStorageSync('userInfo', JSON.stringify(userInfo));
                
                // TODO: 进行用户注册、登录等操作
              }
            });
          } else {
            console.log('登录失败!' + res.errMsg);
          }
        }
      })
    }
  }
}
</script>


上一篇: uniapp插件收藏