首页 > 编程语言 >微信小程序登录授权获取基础信息

微信小程序登录授权获取基础信息

时间:2024-10-11 15:50:25浏览次数:3  
标签:openid code String 登录 微信 res 授权 wx

        最近在写小程序项目时遇到一些问题,小程序登录授权API接口调用会区分新旧版本库,旧版本在调取wx.getUserProfile接口时会直接从底部弹窗,从而允许或取消授权;而新版本库则需要自行设置弹窗,提醒用户授权使用。

        测试新版本和旧版本究竟是哪个可以自动底部弹窗,使用多个版本后发现2.25.4是相较于高版本并且可以升起底部授权弹窗,2.26.2发发生报错,建议使用2.25.4

        本文介绍老版本库从底部弹窗授权登录,调用wx.getUserProfile接口获取用户基本信息(微信昵称、头像、openid、session_key)使用微信开发者工具+idea编写后端是Java的springboot

1、微信小程序端:button点击授权按钮

 wxml:

        <view>

            <button class="confirm-btn"  bindtap="getUserProfile">点击授权</button>

        </view>

js :

  data: {
    session: null,
    code: null,
    userInfo: null,
    hasUserInfo: false,
    avatarUrl: null,
    nickName: null,
    jwt:null,
  },
  getUserProfile(e){
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
        }),
        console.log('登录成功:', res);
        app.globalData.UserInfo = this.data.userInfo;
        this.onGetUserInfo(res);
      }
    })
  },

  onGetUserInfo: function(e) {
    if (e) {
      // 用户同意了授权
      wx.login({
        success: async (res) => {
          if (res.code) {
            // 获取用户登录凭证(code)
            var code = res.code;
            console.log(code);
            // 发起网络请求,将code发送给服务器
            wx.request({
              url: 'http://localhost:8080/wx/user/login',
              data: {
                code : code,
                avatarUrl : this.data.userInfo.avatarUrl,
                nickName : this.data.userInfo.nickName
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded' // POST请求默认为 application/x-www-form-urlencoded
              },
              success: function(res) {
                console.log('登录成功:', res);
                app.globalData.jwt = res.data.content.jwt
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/main/homePage/homePage',
                  });
                }, 1000);
              },
              fail: function(err) {
                console.error('登录失败:', err);
              }
            });
          } else {
            console.log('获取用户登录态失败!' + res.errMsg);
          }
        }
      });
    } else {
      // 用户按了拒绝按钮
      wx.showToast({
        title: '您已拒绝授权',
        icon: 'none'
      });
    }
  },

 2、后端springboot:直接在controller调用

        

@RestController
@RequestMapping("/wx")
public class WxLoginController {

    @Autowired
    private WxUserDataService wxUserDataService;

    /**
     * 登录分为用户小程序登录和后台员工登录
     **/


    /**
     * 小程序端微信用户登录
     */

    private static final String APPID = "****"; // 你的小程序AppID

    private static final String SECRET = "****"; // 你的小程序AppSecret


    @PostMapping("/user/login")
    public Result login(String code, String nickName, String avatarUrl) throws IOException {
        // 构造请求微信服务器的URL

        Map<String, String> params = new LinkedHashMap<>();
        params.put("appid", APPID);
        params.put("secret", SECRET);
        params.put("js_code", code);

        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        requestUrl = String.format(requestUrl, APPID, SECRET, code);

        // 使用RestTemplate发起请求
        RestTemplate restTemplate = new RestTemplate();

        // 发起GET请求
        ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class, params);

        if (response.getStatusCode().is2xxSuccessful()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(response.getBody());

                // 获取session_key和openid
                String sessionKey = jsonNode.get("session_key").asText();
                String openid = jsonNode.get("openid").asText();
                WxUserData wxUserData = new WxUserData();
                wxUserData.setUserOpenId(openid);
                wxUserData.setUserSession(sessionKey);
                wxUserData.setUserNickName(nickName);
                wxUserData.setUserAvatarUrl(avatarUrl);
                wxUserDataService.wxUserLogin(wxUserData);

                //生成JWT
                JwtDto jwtDto = new JwtDto();
                if (wxUserData != null){
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("openid", openid);
                    claims.put("session_key", sessionKey);
                    claims.put("nickName", nickName);
                    claims.put("avatarUrl", avatarUrl);
                    String jwt = JwtUtils.generateJwt(claims);
                    jwtDto.setJwt(jwt);
                }
                // 返回session_key和openid
                return Result.success(jwtDto);
            } catch (IOException e) {
                return Result.fail("微信登录获取信息异常!");
            }
        } else {
            ResponseEntity<String> body = ResponseEntity.status(response.getStatusCode()).body(response.getBody());
            return Result.fail(500,"登陆失败",body);
        }
    }
}

呈现状态:

        小程序端点击授权后

 允许后查看小程序端控制台输出

成功调用wx.getUserProfile接口获取用户基本信息。

标签:openid,code,String,登录,微信,res,授权,wx
From: https://blog.csdn.net/bao_cai/article/details/142854872

相关文章

  • 微信小程序的北京旅游古建筑文化景点打卡平台Thinkphp/Laravel
    目录技术栈和环境说明项目介绍具体实现截图文件解析微信开发者工具HBuilderX+uniapp开发技术简介性能/安全/负载方面数据访问方式PHP核心代码部分展示代码目录结构解析系统测试详细视频演示源码获取技术栈和环境说明Laravel以其优雅的语法和快速开发能力著称,简化了......
  • 2025选题推荐|基于微信小程序的公考学习平台的设计与实现
    作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待与各位高校教师、企业......
  • 微信转账被骗怎么追回?一招教你处理?
    一旦发现自己被骗,打开百度"搜索官方网站"进行网上报案,[报案官网wwa12450.cn]如实描述当时被骗的过程,进行报案挽回您的损失。 如果微信转账被骗,可以尝试以下方法追回: 1. 及时联系微信客服:向微信客服举报该笔转账交易存在诈骗行为,提供详细的交易信息和被骗情况说明,微......
  • python+django+uniapp高校社团管理系统 微信小程序 a4z3n
    目录项目介绍具体实现截图开发者工具介绍技术路线解决的思路性能/安全/负载方面开发语言以及框架介绍数据库设计python-flask核心代码部分展示python-django核心代码部分展示详细视频演示源码获取项目介绍主要是对于申请入社工作调研,以及对申请入社信息采集、存储、......
  • 微信支付接口接入
    微信支付接口接入微信支付接入文档参考(https://pay.weixin.qq.com/docs/merchant/products/jsapi-payment/preparation.html)1.接入前准备具体步骤如下所示:1、选择接入模式:普通商户或普通服务商,官网说明地址:https://pay.weixin.qq.com/docs/merchant/development/glossary/......
  • php网站后台登录密码怎样修改
    在PHP开发的网站后台系统中,修改用户的登录密码通常涉及以下几个步骤:用户身份验证:用户需要先登录到系统中。确认当前用户的权限允许其更改密码。旧密码验证:提供一个输入框让用户输入当前的密码。验证用户输入的旧密码是否正确。新密码设置:用户输入新的密码以及......
  • 登录模板【vue】
    <template><divclass="login-box"><divclass="content-main"><h1style="text-align:center">用户登录</h1><el-formlabel-width="auto"label-position="top">......
  • 微信公众号小说漫画系统 fileupload.php 任意文件上传复现
    0x01漏洞描述:        在微信公众号小说漫画系统的fileupload.php接口中,存在任意文件上传漏洞,该漏洞允许未经身份验证的攻击者上传恶意文件,从而实现代码执行。这种安全隐患使得攻击者能够在服务器上写入后门程序,获取服务器权限,并最终控制整个Web服务器。攻击者可......
  • SpringBoot整合MD5加密完成注册和登录
    目录md5是什么?MD5的主要特点包括:MD5的应用场景市面上比较流行的加密方式引入相关依赖在src/main/resources/application.yml中添加配置加密工具类创建User实体类创建UserRepository接口创建UserService类创建UserController类测试APImd5是什么? ......
  • .Net微信服务商平台ApiV3接口
    转载:https://www.cnblogs.com/xilen/p/15380183.html开始在开始之前建议仔细读微信官方文档,接口规则及api文档https://pay.weixin.qq.com/wiki/doc/apiv3_partner/wechatpay/wechatpay-1.shtmlhttps://pay.weixin.qq.com/wiki/doc/apiv3_partner/index.shtml目录整个流程开......