微信授权网页获取用户openiid


微信网页授权:
官方文档: https://mp.weixin.qq.com/wiki
 支付文档:https://pay.weixin.qq.com/wiki/doc/api/index.html

调试:https://natapp.cn
第三方SDK:https://github.com/Wechat-Group/weixin-java-tools

 

 

 

手工获取openid
1.设置域名
2.用户同意授权,获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=(自己的appid)&redirect\_uri=自己的域名&response\_type=code&scope=SCOPE&state=STATE#wechat\_redirect

-----------换取access_token--------
3.创建方法测试是否能跳转

public class WeixinController {
   @GetMapping("/auth")
    public void auth(@RequestParam("code") String code){
       log.info("进入auth方法");

   }
}

  


4.用户同意授权后得到CODE,页面跳转至 redirect_uri/?code=CODE&state=STATE
5.通过CODE换取网页授权

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

    @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=wxd898fcb01713c658&secret=29d8a650db31472aa87800e3b0d739f2&code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}", response);
    }
}

  


6.拉去用户信息

 

二   sdk获取openid
https://github.com

1).引入依赖

<dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>2.7.0</version>
        </dependency>

2.构造授权url

所需配置文件

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.getMpAppId());
        wxMpConfigStorage.setSecret(accountConfig.getMpAppSecret());
        return wxMpConfigStorage;
    }
}

  项目配置文件中配置

wechat:
  mpAppId:自己的appid
  mpAppSecret: 自己的 mpAppSecret

  微信账号相关的写个配置

package com.imooc.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

/
@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {

    /**
     * 公众平台id
     */
    private String mpAppId;

    /**
     * 公众平台密钥
     */
    private String mpAppSecret;

    /**
     * 开放平台id
     */
    private String openAppId;

    /**
     * 开放平台密钥
     */
    private String openAppSecret;

    /**
     * 商户号
     */
    private String mchId;

    /**
     * 商户密钥
     */
    private String mchKey;

    /**
     * 商户证书路径
     */
    private String keyPath;

    /**
     * 微信支付异步通知地址
     */
    private String notifyUrl;

    /**
     * 微信模版id
     */
    private Map<String, String> templateId;
}

  获取用户code,重定向获取openid

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

    @Autowired
    private WxMpService wxMpService;

       @Autowired
    private ProjectUrlConfig projectUrlConfig;
//获取code重定向到info
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        //1. 配置
        //2. 调用方法
        String url = projectUrlConfig.getWechatMpAuthorize() + "/sell/wechat/userInfo";//重定向到info里面
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(returnUrl));
        return "redirect:" + redirectUrl;
    }
//获取openid和url并重定向
  @GetMapping("/userInfo")
  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();

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

}

  

 

  前端调试

用手机访问到项目,域名不同,手机不能直接访问,需使用抓包工具fiddler,将所有请求先转发到电脑

用电脑IP设置手机http代理,端口设为8888,fiddler默认端口为8888

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM