经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信开发 » 查看文章
手把手教你如何获取微信用户openid
来源:jb51  时间:2023/2/15 9:19:33  对本文有异议

1、前言

随着技术的发展,微信的一系列服务渗透进了我们的生活,但是我们应该怎样进行微信方面的开发呢。相信很多的小伙伴们都很渴望知道吧。这篇文章就是来解决大家的一些疑惑的。首先我们要进行相关的开发的话,那么我们需要先获取微信的openid。那么我们英爱怎样获取呢?这里我会介绍两种方式。

2、手工方式

官方文档

2.1、设置域名

(1).注册对应的公众号找到下图位置

(2). 在natapp.cn上购买自己的用于微信开发的域名

注册地址

哈哈,这个网站上面的域名也不是特别的贵呀,我在这上面买的一个域名为期一个月的话也就才12元,且改类型的属于二级域名,是已经备过案的,所以也就不需要备案。

(3). 下载对应的客户端进行启动

windows上启动的命令

  1. natapp -authtoken 你的authtoken

启动后

可见我的域名指向了127.0.0.1:8080

(4).将我们的域名填到公众号中JS接口安全域名提交

提交之前我们需要将上图中的红色框框住的部分的文件下载下来放置项目的static目录下,测试访问通过之后,然后才能进行提交。

2.2、获取code

可谓是一波三折呀,我本来以为我这个项目就要gg了。但也是我自己太小儿科了。微信怎么可能没有想到这么一个问题呢。就是微信公众号的 网页授权获取用户基本信息 功能服务。它这个功能服务必须只有 服务号 才拥有,但是其实每个用户可以免注册获得一个测试号,该测试号就含有这个特殊功能服务。

(1).登录自己的测试号

微信测试号是免注册的,我们直接扫码登录即可。

(2).编写对应的接口

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. import org.springframework.web.bind.annotation.RestController;
  6.  
  7. /**
  8. * @author :小肖
  9. * @date :Created in 2022/2/1 21:55
  10. */
  11. @RestController
  12. @RequestMapping("/weixin")
  13. @Slf4j
  14. public class WeixinController {
  15.  
  16. @GetMapping("/auth")
  17. public void auth(@RequestParam("code") String code){
  18. log.info("进入了auth方法...");
  19. log.info("code = {}",code);
  20. }
  21. }
  22.  

(3).在登录测试号之后进行网页授权

授权的域名就是我们在natapp.cn上购买的域名,如果没有进行授权的话那么就会报出 10003 redirect_uri域名与后台配置不一致 错误。

(4).进行访问url进行测试

https://open.weixin.qq.com/connect/oauth2/authorize?appid=测试号的appid&redirect_uri=http://你的域名/sell/weixin/auth&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect

注意点

被测试的对象必须先关注对应的测试号且必须在微信客户端进行访问。

(5).测试结果

成功获取了用户的code信息。

2.3、换取access_token

(1).编写的controller

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import org.springframework.web.client.RestTemplate;
  7.  
  8. /**
  9. * @author :小肖
  10. * @date :Created in 2022/2/1 21:55
  11. */
  12. @RestController
  13. @RequestMapping("/weixin")
  14. @Slf4j
  15. public class WeixinController {
  16.  
  17. @GetMapping("/auth")
  18. public void auth(@RequestParam("code") String code){
  19. log.info("进入了auth方法...");
  20. log.info("code = {}",code);
  21. String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=appsecret&code=" + code + "&grant_type=authorization_code";
  22. RestTemplate restTemplate = new RestTemplate();
  23. String response = restTemplate.getForObject(url, String.class);
  24. }
  25. }

(2).访问的url组成

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

参数是否必须说明
appid公众号的唯一标识
secret公众号的appsecret
code填写第一步获取的code参数
grant_type填写为authorization_code

(3).访问的结果

  1. {
  2. "access_token": "53_HK355v2MhOolNlGkaoUf4oDCkyX0WDollvsQNU5SvhsvmvF2S2VoqdPXuokfERI2oqFvQijVShq8aQzeQ9n01mGKSJn7q5rLAcYbTjm1H7k",
  3. "expires_in": 7200,
  4. "refresh_token": "53_C1us_G770mgzXjd-PuK329qB65lXiK483_qxUXjKudwWIdHkOz5ntwlByEgUQfMEy_-7tCCzcO4DoHaFbY0JurpZYD3Bys6DLs8ua8J_CjU",
  5. "openid": "你的openid",
  6. "scope": "snsapi_base"
  7. }

3、使用第三方sdk

3.1、引入第三方依赖

  1. <!--微信公众号开发需要引入的依赖-->
  2. <dependency>
  3. <groupId>com.github.binarywang</groupId>
  4. <artifactId>weixin-java-mp</artifactId>
  5. <version>3.1.0</version>
  6. </dependency>

3.2、将微信公众号配置写入yaml文件并引入类中

  1. wechat:
  2. mpAppId: 你的微信测试号appId
  3. mpAppSecret: 你的微信测试号secret
  1. import lombok.Data;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4.  
  5. /**
  6. * @author :小肖
  7. * @date :Created in 2022/2/2 10:31
  8. */
  9. @Component
  10. @Data
  11. @ConfigurationProperties(prefix = "wechat")
  12. public class WechatAccountConfig {
  13.  
  14. /**
  15. * 公众号id
  16. */
  17. private String mpAppId;
  18.  
  19. /**
  20. * 公众号密钥
  21. */
  22. private String mpAppSecret;
  23.  
  24. }

3.3、编写配置类初始化设置wxMpService配置

  1. import me.chanjar.weixin.mp.api.WxMpConfigStorage;
  2. import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
  3. import me.chanjar.weixin.mp.api.WxMpService;
  4. import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. * @author :小肖
  11. * @date :Created in 2022/2/2 10:24
  12. */
  13. @Component
  14. public class WechatMpConfig {
  15.  
  16.  
  17. @Autowired
  18. private WechatAccountConfig wechatAccountConfig;
  19.  
  20. @Autowired
  21. private WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage;
  22.  
  23. @Bean
  24. public WxMpService wxMpService(){
  25. WxMpService wxMpService = new WxMpServiceImpl();
  26. wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
  27. return wxMpService;
  28. }
  29.  
  30. @Bean
  31. public WxMpInMemoryConfigStorage wxMpConfigStorage(){
  32. /**
  33. * 这里需要注意的是 由于父类中没有定义对应的接口
  34. * 所以所有的方法都在其实现类中,所以我们要构造实现类
  35. */
  36. WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
  37. wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
  38. wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
  39. return wxMpConfigStorage;
  40. }
  41. }
  42.  

3.4、编写对应的controller

  1. import com.xiao.enums.ResultEnum;
  2. import com.xiao.exception.SellException;
  3. import lombok.extern.slf4j.Slf4j;
  4. import me.chanjar.weixin.common.api.WxConsts;
  5. import me.chanjar.weixin.common.error.WxErrorException;
  6. import me.chanjar.weixin.mp.api.WxMpService;
  7. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.GetMapping;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import org.springframework.web.bind.annotation.RestController;
  14.  
  15. /**
  16. * @author :小肖
  17. * @date :Created in 2022/2/2 10:20
  18. */
  19. @Controller
  20. @RequestMapping("/wechat")
  21. @Slf4j
  22. public class WechatController {
  23.  
  24. @Autowired
  25. private WxMpService wxMpService;
  26.  
  27. @GetMapping("/authorize")
  28. public String authorize(@RequestParam("returnUrl") String returnUrl){
  29. String url = "http://xiao-sell.natapp1.cc/sell/wechat/userInfo";
  30. String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,returnUrl);
  31. return "redirect:" + redirectUrl;
  32. }
  33.  
  34. @GetMapping("/userInfo")
  35. public String userInfo(@RequestParam("code") String code,
  36. @RequestParam("state") String returnUrl) {
  37. WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
  38. try{
  39. wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
  40. }catch (WxErrorException e){
  41. log.error("【微信网页授权错误】 exception = {}",e);
  42. throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(),e.getError().getErrorMsg());
  43. }
  44. String openId = wxMpOAuth2AccessToken.getOpenId();
  45. log.info("openid = {}",openId);
  46. return "redirect:" + returnUrl + "?openid=" + openId;
  47. }
  48. }

3.5、进行debug测试

第一个断点

该重定向的url很明显就是我们手工方式中获取codeurl

第二个断点

成功获取了codeopenid

总结

到此这篇关于手把手教你如何获取微信用户openid的文章就介绍到这了,更多相关获取微信用户openid内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号