微信小程序获取openId和session_key

1.如何获取微信小程序/微信公众号的AppId和AppSecret?

进入微信公众平台点击此处:微信公众平台

 

2.获取openId和session_key

前端

// index.ts
// 获取应用实例
const app = getApp<IAppOption>()

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
  },
  // 事件处理函数
  bindViewTap() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  onLoad() {
    // @ts-ignore
    if (wx.getUserProfile) {
      console.log("getUserProfile执行了")
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  onReady() {
  },
  getUserProfile() {
    let that = this
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        wx.setStorage({
          "key": "user",
          "data": res.userInfo
        })
        //登录
        wx.login({
          success: res => {
            //根据code获取openid,session_key
            if (res.code) {
              console.log("code:"+res.code)
              //发起网络请求
              wx.request({
                url: "http://localhost:8080/user/getOpenId",
                method: "post",
                data: {
                  code: res.code
                },
                header: {
                  "Content-Type": "application/x-www-form-urlencoded"  
                },
                success: function (res) {
                  console.log("openid:" + res.data.openid);//openid
                  console.log("session_key:" + res.data.session_key);//session_key
                  that.globalData.openid = res.data.openid;
                  that.globalData.session_key = res.data.session_key;
                  wx.showToast({
                    title: '获取成功',
                    duration: 1500,
                    icon: 'success'
                  })
                },
                fail: function () {
                  wx.showToast({
                    title: '获取失败',
                    duration: 2000,
                    icon: 'error'
                  })
                }
              })
            } else {
              console.log('登录失败:' + res.errMsg)
            }
          }
        })
      }
    })
  },
  share() {
    wx.showActionSheet({
      itemList: ["微信", "oo", "朋友圈"],
      success(data) {
        console.log(data)
      }
    })
  },
  getUserInfo(e: any) {
    console.log("getUserInfo")
    // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    wx.setStorage({
      "key": "user",
      "data": e.detail.userInfo
    })
  },
})

 后端

    @PostMapping("getOpenId")
    @ResponseBody
    public ResultModel<OpenIdAndSessionKey> getOpenId(String code){
        try{
            OpenIdAndSessionKey openIdAndSessionKey = WxUtil.getOpenId(code);
            return ResultModel.success(openIdAndSessionKey);
        }catch (Throwable e){
            LOGGER.error("获取openId异常:", e);
        }
        return ResultModel.fail(null);
    }

WxUtil

package com.gl.utils.wx;

import cn.hutool.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author gl
 * @date 2022年10月14日
 */
public class WxUtil {
    private static  final Logger LOGGER = LoggerFactory.getLogger(WxUtil.class);
    private static final String appId = "";
    private static final String secret = "";
    private static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    public static OpenIdAndSessionKey getOpenId(String code) {
        OpenIdAndSessionKey openIdAndSessionKey =new OpenIdAndSessionKey();
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            String requestUrl = String.format(openIdUrl, appId, secret, code);
            HttpGet httpGet = new HttpGet(requestUrl);
            HttpEntity responseEntity = httpClient.execute(httpGet).getEntity();
            if (responseEntity != null) {
                String responseStr = EntityUtils.toString(responseEntity);
                if (responseStr.contains("openid")) {
                    JSONObject wxResponse = new JSONObject(responseStr);
                    openIdAndSessionKey.setOpenId((String) wxResponse.get("openId"));
                    openIdAndSessionKey.setSessionKey((String) wxResponse.get("session_key"));
                    return openIdAndSessionKey;
                }
            }
        }catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不穿铠甲的穿山甲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值