微信小程序获取openid

2025年1月15日:

1、现在云服务器上安装nodejs,然后写个get接口:

复制代码
const express = require('express');
const app = express();

app.get('/getOpenid',(req,res)=>{
    res.send("success");
})

app.listen(3000,()=>{
    console.log('server is run!!');
})

2、这时在浏览器访问服务器的getOpenid接口,就会收到success

3、小程序里面获取一下(app.js):

复制代码
App({
  onLaunch(){
    console.log('in onLaunch');
    wx.request({
      url: 'http://223.4.251.25:3000/getOpenid',
      success(res){
        console.log('成功',res.data);
      },
      fail(err){
        console.log('失败:',err.errMsg);
      }
    })
  }
})

4、这时候提示出错:

5、打开微信小程序开发工具,设置一下:

6、这个时候再编译一下,就可以得到正确的回复啦:

7、到这里基本框架已经搭好了,接下来我们就根据微信小程序的文档上的流程来获取openid

8、首先先login获取code,然后将code和其他的一些参数都发送到后台:

注意:其中appid,secret,还有服务器网址都按自己实际的填写

复制代码
// app.js
App({
  onLaunch() {
    console.log('in onLaunch');
    wx.login({
      success: (res) => {
        console.log('成功登录:', res.code);
        var code = res.code;
        wx.request({
          url: 'http://223.4.251.25:3000/getOpenid',
          data: {
            appid: appid,
            secret: appsecret,
            js_code: code,
            grant_type: 'authorization_code'
          },
          success(res) {
            console.log('成功', res.data.openid);
          },
          fail(err) {
            console.log('失败:', err.errMsg);
          }
        })

      },
      fail(err) {
        console.log('失败:', err.errMsg);
      }
    })
  }
})

9、然后我们就去服务器端(后台)完善我们的nodejs代码:

注意:我这里用的axios组件,所以要先安装一下

复制代码
const express = require('express');
const axios = require('axios');
const app = express();

app.get('/getOpenid',(req,res)=>{
    const appid = req.query.appid;
    const appsecret = req.query.secret;
    const code = req.query.js_code;
    console.log('appid:',appid,'appsecret:',appsecret,'code:',code);
    const url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+appid+'&secret='+appsecret+'&js_code='+code+'&grant_type=authorization_code';
    axios.get(url)
    .then(respinse=>{
        res.send(respinse.data);        
    })
    .catch(err=>{
        console.error(' 请求发生错误:',err);
    })
})

app.listen(3000,()=>{
    console.log('server is run!!');
})

10、这时,我们回到小程序端,重新编译一下代码,就可以在日志里看见openid了。

相关推荐
mykj15517 小时前
消费积分抵扣物业费小程序商城开发
小程序·积分商城抵扣物业费·积分商城小程序开发
云迈科技-软件定制开发1 天前
2026年湖南长沙软件定制开发公司怎么选?本地企业做APP、小程序、管理系统的合作参考
小程序
admin and root1 天前
「移动安全」安卓APP 反编译&frida脱壳技巧分享
android·开发语言·python·web安全·微信小程序·移动安全·攻防演练
m0_462803882 天前
【无标题】
微信小程序
小码哥0682 天前
从三甲综合医院到连锁诊所:医院管理小程序的场景化突围逻辑(陪诊系统-陪诊APP-陪诊小程序)
小程序·医院管理系统·陪诊小程序·陪诊系统·陪诊app
2501_916007472 天前
iOS和macOS应用程序性能分析和优化工具使用综合指南
android·macos·ios·小程序·uni-app·iphone·webview
正在走向自律2 天前
用豆包Seed Evolving打造全功能【AI智能记账】小程序,开源可落地
人工智能·小程序·开源·智能记账
小羊Yveesss3 天前
模板建站哪个平台好?模板数量之外还要比较编辑与SEO能力
大数据·人工智能·小程序
2501_916007473 天前
深入理解HTTPS对称与非对称加密机制及Charles抓包实践
网络协议·http·ios·小程序·https·uni-app·iphone
郑州光合科技余经理3 天前
家政O2O平台解析:从0搭建上门预约小程序解决方案
android·java·开发语言·前端·小程序·架构·php