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