微信用户公众授权登录获取openid
1.查看微信官方文档了解大致流程:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1
2.获取openid流程:
第一步:用户同意授权,获取code,通过访问:
第二步:通过code换取网页授权access_token,获得access_token,openid可通过access_token获取
3.通过sdk获取openid :https://github.com/wechat-group/WxJava/wiki
4.通过查看sdk的文档来编写相应的代码:
package com.yzy.sell.Controller; import com.yzy.sell.Enums.ResultEnum; import com.yzy.sell.exception.SellException; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.net.URLEncoder; @Controller @Slf4j @RequestMapping("/wechat") public class WecharController { @Autowired private WxMpService wxMpService; @GetMapping("/authorize") //获取code public String authorize(@RequestParam("returnUrl") String returnUrl){ String redirectUrl="http://shouyaya.natapp1.cc/sell/wechat/userInfo"; String resultRedirectUrl = wxMpService.oauth2buildAuthorizationUrl(redirectUrl, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode(returnUrl));//该属性对应微信接口里的state属性, // 通过此属性可以传递自定义参数,这里定义了从前端获取ip地址 log.info("[回调的地址为:{}]",resultRedirectUrl); return "redirect:"+resultRedirectUrl; } @GetMapping("/userInfo") //通过前面获取的code,以oauth2getAccessToken获取wxMpOAuth2AccessToken //openid即可通过wxMpOAuth2AccessToken获取 public String userInfo(@RequestParam("code") String code,@RequestParam("state") String returnUrl){ WxMpOAuth2AccessToken wxMpOAuth2AccessToken= new WxMpOAuth2AccessToken(); try { wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code); } catch (WxErrorException e) { log.error("【微信网页授权】,{}", e); throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(),e.getError().getErrorMsg()); } String openId = wxMpOAuth2AccessToken.getOpenId(); log.info("openId={}",openId); return "redirect:"+returnUrl+"?openid="+openId; } }
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect