SpringCloud : 接入 微信公众号平台(四)、获取微信用户信息接口

代码参考:

import com.phpdragon.wechat.proxy.config.WeChatConfig;import com.phpdragon.wechat.proxy.dto.mp.user.GetOauthUserInfoDto;import com.phpdragon.wechat.proxy.dto.mp.user.GetOpenidDto;import com.phpdragon.wechat.proxy.dto.mp.user.GetUserInfoDto;import lombok.extern.slf4j.Slf4j;import me.chanjar.weixin.common.error.WxErrorException;import me.chanjar.weixin.mp.api.WxMpService;import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;import me.chanjar.weixin.mp.bean.result.WxMpUser;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;@Slf4j@RequestMapping("/user/")@RestControllerpublic class UserController { @Autowired private WeChatConfig weChatConfig; /** * 通过openid获得基本用户信息 * 详情请见: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#3 * * @param req * @return */ @ResponseBody @PostMapping("/getUserInfo") public WxMpUser getUserInfo(@RequestBody @Valid GetUserInfoDto req) throws WxErrorException { WxMpService wxMpService = weChatConfig.getWxMpService(req.getAppId()); return wxMpService.getUserService().userInfo(req.getOpenid(), req.getLang()); } /** * 通过code获得基本用户信息 * 详情请见: * https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1 * https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#3 * * @param req * @return */ @ResponseBody @RequestMapping("/getOAuth2UserInfo") public WxMpUser getOAuth2UserInfo(@RequestBody @Valid GetOauthUserInfoDto req) throws WxErrorException { WxMpService wxMpService = weChatConfig.getWxMpService(req.getAppId()); WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(req.getCode()); return wxMpService.getUserService().userInfo(accessToken.getOpenId(), req.getLang()); } /** * 用code换取oauth2的openid * 详情请见: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1 * * @param req */ @ResponseBody @PostMapping("/getOpenid") public String getOpenid(@RequestBody @Valid GetOpenidDto req) throws WxErrorException { WxMpService wxMpService = weChatConfig.getWxMpService(req.getAppId()); WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(req.getCode()); return accessToken.getOpenId(); }}

 

 

PS:

公众号开发文档wiki

SpringCloud : 接入 微信公众号平台(四)、获取微信用户信息接口

Java开发微信公众号之整合weixin-java-tools框架开发微信公众号

从零实现 Spring Boot 2.0 整合 weixin-java-mp(weixin-java-tools) 获取 openId,用于微信授权

 

Demo 列表

  1. 微信支付 Demo:GitHub、码云
  2. 企业号/企业微信 Demo:GitHub、码云
  3. 微信小程序 Demo:GitHub、码云
  4. 开放平台 Demo:GitHub、码云
  5. 公众号 Demo:
    • 使用 Spring MVC 实现的公众号 Demo:GitHub、码云
    • 使用 Spring Boot 实现的公众号 Demo(支持多公众号):GitHub、码云
    • 含公众号和部分微信支付代码的 Demo:GitHub、码云

 

相关文章