微信授權網頁獲取用戶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