微信小程序-获取openid

发布时间 2023-11-02 21:42:28作者: 钟小嘿

当需要获取当前用户的微信openid时,需要调用微信提供的接口进行获取,这里以从后端获取为例进行说明。

1.小程序代码

ts(之前叫js):

Page({
  data: {
      info:'hello'
  },
  clickMe:function(){
    wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: "http://localhost:8080/user/getInfo?code="+res.code,
              method: "POST",
              success(res){
                  console.log(res.data)
               }
            })
          } else {
            wx.showToast({
              title: '出现错误',
              icon: 'error',
              duration: 5000
            })
            console.log('出现错误!' + res.errMsg)
          }
        }
      })

  },
  onLoad() {
    this.setData({
     
    })
  },
})

wxml:

<view class="container log-list">
    <button bindtap="clickMe">获取</button>
</view>

2.后台代码

后端代码以springboot为模板

controller:

@RestController
@RequestMapping("/user")
public class TestController {

    /**
     * 获取微信的openid
     *
     * @param code
     * @return
     */
    @PostMapping("/getInfo")
    public JSONObject getInfo(@RequestParam String code) {
        String wxspAppid = "appid,在微信公众平台获取";
        String wxspSecret = "appSecret,在获取公众平台获取";
        // 授权(必填)固定
        String grant_type = "authorization_code";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", wxspAppid);
        params.put("secret", wxspSecret);
        params.put("js_code", code);
        params.put("grant_type", grant_type);
        // 发送请求
        String res = HttpUtil.post("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject json = JSONObject.parseObject(res);
        log.info("解析code请求结果:" + json.toString());
        //获取openid
        String openid = json.getString("openid");
        log.info("openid=" + openid);
        return json;
    }
}

引入的依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.15</version>
        </dependency>

点击按钮后即可获取到用户信息