收藏
回答

求助:本地调试小程序报错,未返回有效的openid。大佬帮帮忙?

https://developers.weixin.qq.com/s/DfX1SjmE74YA

上面链接是代码片段。

在本地使用phpstudy搭建的环境,后台使用wordpress,在函数中注册了几个端点。调试的过程中始终报错,未返回有效的openid,实际上在network中可以确定openid端口的状态码是200,也能看到返回的openid,我是新手,希望大佬给指教下,问题出现在哪里?

下面是调试窗口:

最后一次编辑于  03-01
回答关注问题邀请回答
收藏

5 个回答

  • Passerby
    Passerby
    03-03

    排查下这里 打印下

    03-03
    有用 1
    回复 1
    • 樂途
      樂途
      03-03
      已解决,感谢大佬指点。
      03-03
      回复
  • sun
    sun
    03-01

    你这是在前端获取openid?

    获取openid的接口需要在服务端调用,不支持在前端调用。

    03-01
    有用
    回复 1
    • 樂途
      樂途
      03-01
      是在后端端口获取的,我的预想是把获取到的openid在数据库中查询,如果存在则默认登陆,如果不存在那么就提示用户注册。
      03-01
      回复
  • Mr.Zhao
    Mr.Zhao
    03-01

    代码不是你写的?

    03-01
    有用
    回复 2
    • 樂途
      樂途
      03-01
      让大佬见笑了,我不懂开发,是在学习,用的ai帮写的。。
      03-01
      回复
    • Mr.Zhao
      Mr.Zhao
      03-01回复樂途
      说不清楚啊 给你说,你也不知道我在说啥
      03-01
      回复
  • 樂途
    樂途
    03-01

    不方便导入代码片段的大佬,可以看这里:

    const app = getApp();
    App({
      globalData: {
        userInfonull// 当前用户信息
        apiBase'http://localhost/new' // 统一API地址
      },
      onLaunch() {
        this.checkUserLogin();
        // 全局错误捕获
        wx.onError(function (error{
          console.error('全局捕获的错误:', error);
          wx.showToast({ title'程序异常,请重试'icon'none' });
        });
      },
    
    
      // 检查用户登录状态
      async checkUserLogin() {
        try {
          const loginRes = await wx.login();
          const code = loginRes.code;
    
    
          console.log('%c[DEBUG]wx.login返回的code:','color:orange', code);
          if (!code) {
            throw new Error('无法获取 code');
          }
          const openid = await this.getOpenid(code);
          if (!openid) {
            throw new Error('无法获取 openid');
          }
          const userRes = await wx.request({
            url`${this.globalData.apiBase}/wp-json/api/v1/user/check?openid=${openid}`,
            method'GET',
            header: { 'content-type''application/json' }
          });
          console.log('[DEBUG]/user/check响应:', userRes);
          if (userRes.statusCode === 200 && userRes.data) {
            if (userRes.data.isRegistered) {
              this.globalData.userInfo = { openid, name: userRes.data.name };
            } else {
              await this.showRegisterDialog(openid);
            }
          } else {
            throw new Error('用户检查失败');
          }
        } catch (error) {
          console.error('登录检查失败:', error);
          // 如果已获取 openid,则尝试注册
          if (this.globalData.openid) {
            try {
              await this.showRegisterDialog(this.globalData.openid);
            } catch (registerError) {
              console.error('注册过程中发生错误:', registerError);
              wx.showToast({ title'注册失败,请重试'icon'none' });
            }
          } else {
            wx.showToast({ title'登录失败,请重试'icon'none' });
          }
        }
      },
      // 获取 openid
      async getOpenid(code) {
        try {
          const res = await wx.request({
            url`${this.globalData.apiBase}/wp-json/api/v1/auth/openid`,
            method'POST',
            header: { 'content-type''application/json' },
            data: { code }
          });
          console.log('%c[DEBUG]auth/openid响应:','color:green', res);
          if (res.statusCode === 200 && res.data && res.data.openid) {
            const openid = res.data.openid;
            this.globalData.openid = openid; // 将 openid 存储到全局变量
            return openid;
          } else {
            throw new Error(res.data?.errmsg || '未返回有效 openid');
          }
        } catch (error) {
          console.error('获取 openid 失败:', error);
          wx.showToast({ title'获取 openid 失败'icon'none' });
          throw error;
        }
      },
      // 显示注册弹窗
      async showRegisterDialog(openid) {
        try {
          const name = await this.getUserName();
          if (!name) {
            throw new Error('未输入姓名');
          }
          await this.registerUser(openid, name);
          wx.showToast({ title'注册成功'icon'none' });
          this.globalData.userInfo = { openid, name };
        } catch (error) {
          console.error('注册失败:', error);
          wx.showToast({ title'注册失败,请重试'icon'none' });
          throw error; // 继续抛出错误
        }
      },
      // 获取用户姓名
      getUserName() {
        return new Promise((resolve) => {
          wx.showModal({
            title'输入姓名',
            editabletrue,
            placeholderText'请输入真实姓名',
            success(res) => {
              if (res.confirm) {
                resolve(res.content);
              } else {
                resolve(null);
              }
            }
          });
        });
      },
      // 注册用户
    async registerUser(openid, name) {
      const res = await wx.request({
        url`${this.globalData.apiBase}/wp-json/api/v1/user/register`,
        method'POST',
        data: { openid, name }
      });
      // 根据后端返回的状态码处理不同情况
      if (res.statusCode === 200) {
        this.globalData.userInfo = { openid, name };
        return;
      } else if (res.statusCode === 409) {  // 假设 409 表示用户已存在
        wx.showToast({ title'用户已存在,自动登录'icon'none' });
        this.globalData.userInfo = { openid, name: res.data.name }; // 假设后端返回用户信息
      } else {
        throw new Error(res.data?.message || '注册失败');
      }
    }
    });
    
    
    
    03-01
    有用
    回复
登录 后发表内容