解决微信公众号网页授权域名2个的限制

问题

微信进行网页授权时,需要填写授权域名,授权域名只有两个, 但是实际上可能有多个。不利于开发调试,每次都要修改,并且要发布到那个域名底下,相当麻烦

思路

准备中间代理域名agent.example
微信公众号网页授权上填这个代理域名 agent.example
所有 需要微信网页授权的客户端页面都向 agent.example 请求
然后由 agent.example 统一向 微信服务器进行发起网页授权请求
微信服务器带着code 重定向 agent.example
agent.example 将code 拼接真实客户端需要授权页面的地址 为 url
agent.example 重定向 url 到客户端
客户端可以通过 url 拿到 微信授权过的 code

流程图

 

 

 

 

 

代码实现

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;

@RestController
@RequestMapping("/h5")
public class WechatAgentController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 微信网页授权地址, 需要人工点击确认的那种
     */
    private static final String AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize"
            + "?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

/** * 代理授权域名,换成你自己真实的公网域名!! */
private static final String DEFAULT_AUTH_HOST = "https://xxxx.com"; private static final String CODE_URL = "retail/h5/wx/code?returnUrl={0}";
/** * 授权 * * @param redirectUrl 目标地址--授权完成之后的回调地址 */ @NoToken @GetMapping("/wx/oauth2") public void openAuth(String appId, String redirectUrl, HttpServletResponse response) throws IOException { String middleUrl = DEFAULT_AUTH_HOST; middleUrl = middleUrl.concat("/"); middleUrl = middleUrl.concat(CODE_URL); String tmpUrl = MessageFormat.format(middleUrl, redirectUrl); logger.warn("tmpUrl"+tmpUrl); System.out.println(tmpUrl); String realRedirectUrl = MessageFormat.format(AUTH_URL, appId, tmpUrl); logger.warn("realRedirectUrl:"+realRedirectUrl); System.out.println(realRedirectUrl); //重定向到 /wx/code 请求 response.sendRedirect(realRedirectUrl); } /** * 获取 code */ @NoToken @GetMapping("/wx/code") public void code(String code, String returnUrl, HttpServletResponse response) throws IOException { String redirectUrl; if (returnUrl.contains("?")) { redirectUrl = returnUrl.concat("&code=").concat(code); } else { redirectUrl = returnUrl.concat("?code=").concat(code); } logger.warn("redirectUrl:"+redirectUrl); response.sendRedirect(redirectUrl); } /** * 在微信公众号后台配置域名可跳过文件验证 */ @GetMapping("/MP_verifxxxxxxxxxxxx.txt") public String txt() { return "xxxxxxxxxx"; } }

 

posted @ 2022-09-08 11:05  低调的小白  阅读(6199)  评论(0编辑  收藏  举报