微信开发网页授权的两种方式(基于SpringBoot)

一、方式一:手动实现微信授权

1、若没有微信公众号,可以用测试号来进行测试号

     (1)官方链接:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

微信开发网页授权的两种方式(基于SpringBoot)_第1张图片

其中Token可以随便写,可能一开始配置的URL无法配置成功,别着急,按照我下面的步骤操作

(2)在“网页授权获取用户基本信息”那一栏,点击修改

 

在此处设置自己的域名,可以是通过花生壳或者natapp[链接:https://natapp.cn/ ]获取来的,均可!!

[不要包含http://或https://]

微信开发网页授权的两种方式(基于SpringBoot)_第2张图片

2、SpringBoot后台

例如我配置的上述URL就是doWxLogin这个方法的地址:http://域名/sell/weixin/wx/wxLogin

访问上述地址,调用doWxLogin方法请求微信,微信登陆后重定向到http://域名/sell/weixin/auth 这个方法,获取到返回的信息

(1)Controller层

@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info("进入auth方法。。。");
        log.info("code={}", code);

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=XXXXXXXXXXX&secret=XXXXXXXXXXXXXXXXXX&code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}", response);
    }

    @GetMapping("/wx/wxLogin")
    public void doWxLogin (HttpServletRequest request, HttpServletResponse response) {

        try {
            loginService.doWxLogin(request, response);
            System.out.println("==================================>");
        } catch (Exception e) {
            e.printStackTrace();
            //相应的处理
        }

    }
}

(2)Service层

@Service
public class LoginServiceImpl implements LoginService {
    @Override
    public void doWxLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String authUrl = WxConstants.AUTH_BASE_URL + "appid=" + WxConstants.APPID
                + "&redirect_uri=" + URLEncoder.encode(WxConstants.REDIRECT_URL)
                + "&response_type=code"
                + "&scope=" + WxConstants.SCOPE
                + "&state=STATE#wechat_redirect";


        String signature = request.getParameter("signature");/// 微信加密签名
        String timestamp = request.getParameter("timestamp");/// 时间戳
        String nonce = request.getParameter("nonce"); /// 随机数
        String echostr = request.getParameter("echostr"); // 随机字符串

        PrintWriter out = response.getWriter();

        if (signature != null && timestamp != null && nonce != null && echostr != null) {
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
            out.close();
        } else {
            response.sendRedirect(authUrl);
        }

    }
}

(3)WxConstants类

public final class WxConstants {

    public static final String APPID = "XXXXXXXXXXXXXXXXX";
    public static final String APPSECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

    //授权
    public static final String AUTH_BASE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?";
    //获取token
    public static final String ACCESS_TOKEN_BASE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    //获取用户信息
    public static final String INFO_BASE_URL = "https://api.weixin.qq.com/sns/userinfo?";
    //回调
    public static final String REDIRECT_URL = "http://域名/sell/weixin/auth";
    //允许的范围
    public static final String SCOPE = "snsapi_userinfo";
    //token
    public static final String TOKEN = "与上面设置的token一致";

    private WxConstants(){}

}

3、结果

微信访问即可获得授权:http://域名/sell/weixin/wx/wxLogin

二、方式二:利用第三方SDK实现微信授权

1、参考链接:https://github.com/Wechat-Group/WxJava

    在pom.xml中加入:


  com.github.binarywang
   weixin-java-mp 
  3.3.0

2、SpringBoot后台

参考文档:https://github.com/wechat-group/WxJava/wiki

(1)Controller层

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        //访问:http://t238997p11.qicp.vip/sell/wechat/authorize?returnUrl=http://www.imooc.com

        //访问:http://127.0.0.1:8080/sell/wechat/authorize?returnUrl=http://www.imooc.com
        //若用注解@RestController(会自动解析成json)
        //返回:redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx085c556cb1d22b1f&redirect_uri=http%3A%2F%2Ft238997p11.qicp.vip%2Fsell%2Fwechat%2FuserInfo&response_type=code&scope=snsapi_userinfo&state=http%3A%2F%2Fwww.imooc.com&connect_redirect=1#wechat_redirect
        //若用注解@Controller
        //返回:直接重定向,请在微信打开,访问http://t238997p11.qicp.vip/sell/wechat/authorize?returnUrl=http://www.imooc.com,在微信打开后会跳转到returnUrl,即http://www.imooc.com

        //配置(配置已经完成)

        //回调方法
        String url = "http://t238997p11.qicp.vip/sell/wechat/userInfo";
        //构造网页授权url
        //可使用WxConsts.OAuth2Scope.SNSAPI_USERINFO模式,也可使用WxConsts.OAuth2Scope.SNSAPI_BASE模式,SNSAPI_BASE模式用户是无感知的
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("微信网页授权获取code,redirectUrl={}",redirectUrl);
        return "redirect:" + redirectUrl;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,@RequestParam("state") String returnUrl){
        //获得access token
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("[微信网页授权] {}",e);
            throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(),e.getError().getErrorMsg());
        }
        //获取openid
        String openId = wxMpOAuth2AccessToken.getOpenId();

        return "redirect:" + returnUrl+"?openid=" + openId;
    }

}

(2)相关配置

A: application.yml

wechat:
  myAppId: XXXXXXXXXXXXXXXXXX
  myAppSecret: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
B: WechatAccountConfig.class
@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {

    private String myAppId;

    private String myAppSecret;
}

C:  WechatMpConfig.class

@Component
public class WechatMpConfig {
    @Autowired
    private WechatAccountConfig accountConfig;

    @Bean
    public WxMpService wxMpService(){
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage(){
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(accountConfig.getMyAppId());
        wxMpConfigStorage.setSecret(accountConfig.getMyAppSecret());
        return wxMpConfigStorage;
    }
}

3、结果

微信访问即可获得授权: http://域名/sell/wechat/authorize?returnUrl=http://www.imooc.com

页面会跳转到http://www.imooc.com,并且地址栏路径中会返回openid

你可能感兴趣的:(微信)