Java服务端获取微信小程序openid(简单实现,搞懂原理)

🧩在微信小程序login时通过Java后台获取openid

在这里插入图片描述

闲话少说,直接上代码和视频教程

📺 视频教程:Java服务器端获取用户的openid

🧰 官方文档:微信小程序登陆流程

👩‍🏫图解流程原理:

在这里插入图片描述

小程序端代码

<button bindtap="getUserProfile">点击获取用户信息</button>
// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },

  getUserProfile(e){
    console.log("getUserProfile方法");
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    });

    wx.login({
      success (res) {
        console.log("code:"+res.code);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'http://localhost:8080/login',
            method:"POST",
            data: {
              code: res.code
            }
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })
  }

Java后台代码

在这里插入图片描述

import lombok.Data;
@Data
public class Back {
    private Integer code;
    private String msg;
    private Object object;
}
import lombok.Data;

@Data
public class LoginBO {
    private String code;
}

/**
 * @author Hooker
 * @program: wechat
 * @description: 登陆
 * @date 2021-04-22 23:38:14
 */
@RestController
@RequestMapping("login")
public class LoginController {
    @PostMapping
    public Back login(@RequestBody LoginBO loginBO) throws IOException {
        System.out.println(loginBO);
        //AppID
        String appId = "wx59ce6e94fdcc6730";
        //密钥
        String secret= "67b61e7fff09cf46a8a75a73cbf91e1f";
        //code
        String code = loginBO.getCode();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId
                +"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";

        //客户端
        OkHttpClient client = new OkHttpClient();
        //用url发起请求
        Request request = new Request.Builder().url(url).build();
        //拿到响应
        Response response = client.newCall(request).execute();
        //如果响应成功,打印返回值
        if (response.isSuccessful()){
            String body = response.body().string();
            System.out.println(body);
            //实际开发应该有的步骤:
            //1.入库:把openId存起来
            //2.返回一个token
        }
        //因为是简易版,所以返回值没用到
        return new Back();
    }
}

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.it</groupId>
    <artifactId>wechat</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>wechat</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.7.2</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

运行结果
在这里插入图片描述

代码很简陋,但是大体功能都实现了,主要是为了理清思路,了解原理,希望对你有帮助,若内容有误欢迎留言指正~

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值