微信小程序获取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了。

相关推荐
2501_9159184121 小时前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
知识分享小能手21 小时前
uni-app 入门学习教程,从入门到精通,uni-app基础扩展 —— 详细知识点与案例(3)
vue.js·学习·ui·微信小程序·小程序·uni-app·编程
2501_915909061 天前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
狂团商城小师妹1 天前
智尚房产中介小程序
微信小程序·小程序
狂团商城小师妹1 天前
预约洗车小程序
微信小程序·小程序
future_studio1 天前
聊聊 Unity(小白专享、C# 小程序 之 图片播放器)
unity·小程序·c#
Q_Q5110082851 天前
python+uniapp基于微信小程序的心理咨询信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
HuYi_code1 天前
WeChat 小程序下载文件实现
微信小程序·uni-app
00后程序员张1 天前
HTTPS 包 抓取与分析实战,从抓包到解密、故障定位与真机取证
网络协议·http·ios·小程序·https·uni-app·iphone
一匹电信狗1 天前
【C++】C++风格的类型转换
服务器·开发语言·c++·leetcode·小程序·stl·visual studio