java 微信小程序登录接口获取openid

根据官方文档,wx.login()的回调函数中,需要我们传递生成的用户登录凭证到code2accessToken的接口中

小程序登录方法


code2accessToken的方法中要求传入如下参数

获取Appid与appSecret,登录微信公众平台,知道你申请的小程序,开发者设置中有appid,然后生成secret即可



开发者设置

官方文档:

    https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

微信公众平台:

    https://mp.weixin.qq.com/

首先,要在微信开发者工具中,修改utils下app.js中的wx.login()方法

// 登录
wx.login({
  success: function (res) {
    if (res.code) {
      // 发起网络请求
      wx.request({
        // 这里是接口地址,建议部署配置域名为https,否则可能会出问题,nginx加密证书配置见文章尾
        url: 'http://127.0.0.1:8099/api/v1/minipro/login',
        data: {
          code: res.code
        }
      })
    } else {
      console.log('登录失败!' + res.errMsg)
    }
  }
})

微信小程序登录 JAVA接口

@Controller
@RequestMapping("/api/v1/minipro")
public class MainController implements Serializable {
 
    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(MainController.class);
 
    /**
     * 登录
     * @param
     */
    @ResponseBody
    @GetMapping(value="/login")
    public Result login(String code) {
        
        // 微信小程序ID
        String appid = "";
        // 微信小程序秘钥
        String secret = "";
        
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        // 发送请求,返回Json字符串
        String str = WeChatUtil.httpRequest(url, "GET", null);
        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(str);
        
        // 我们需要的openid,在一个小程序中,openid是唯一的
        String openid = jsonObject.get("openid").toString();
        
        
        // 然后书写自己的处理逻辑即可
        
    }
 

微信小程序 JAVA工具类

/**
 * 微信工具类
 */
public class WeChatUtil {
 
    public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
}

因为审核上线的小程序接口都必须要https开头,也就是说必须开启加密证书才可以使用。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java编写微信小程序登录接口的一般步骤如下: 1. 获取微信小程序登录凭证(code),该凭证由微信小程序提供。 2. 将code发送给微信服务器,换取用户的唯一标识openid和会话密钥session_key。 3. 对session_key进行解密,获取用户的唯一标识和用户信息。 4. 将用户信息存储到数据库中,返回用户相关信息给微信小程序。 下面是一个简单的Java代码示例: ```java @RestController @RequestMapping("/wx") public class WxLoginController { @Autowired private UserService userService; @PostMapping("/login") public ResponseData login(@RequestBody WxLoginDTO wxLoginDTO) { String code = wxLoginDTO.getCode(); String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=" + code + "&grant_type=authorization_code"; RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject(url, String.class); JSONObject jsonObject = JSON.parseObject(response); String openId = jsonObject.getString("openid"); String sessionKey = jsonObject.getString("session_key"); String userInfo = wxLoginDTO.getUserInfo(); // 解密用户信息 WxEncryptedData wxEncryptedData = JSON.parseObject(userInfo, WxEncryptedData.class); String decryptedData = WxMiniProgramUtils.decrypt(wxEncryptedData.getEncryptedData(), sessionKey, wxEncryptedData.getIv()); // 存储用户信息 userService.saveUser(openId, decryptedData); // 返回用户信息 User user = userService.getUser(openId); return ResponseData.success(user); } } ``` 其中,WxLoginDTO是一个封装了code和用户信息的DTO类,WxEncryptedData是一个封装了加密数据的DTO类,WxMiniProgramUtils是一个解密工具类,User是一个封装了用户信息的实体类。此外,需要在配置文件中配置微信小程序的appid和secret。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值