手把手教你如何获取微信用户openid
作者:崇尚学技术的科班人 发布时间:2023-11-04 01:01:21
1、前言
随着技术的发展,微信的一系列服务渗透进了我们的生活,但是我们应该怎样进行微信方面的开发呢。相信很多的小伙伴们都很渴望知道吧。这篇文章就是来解决大家的一些疑惑的。首先我们要进行相关的开发的话,那么我们需要先获取微信的openid
。那么我们英爱怎样获取呢?这里我会介绍两种方式。
2、手工方式
官方文档
2.1、设置域名
(1).注册对应的公众号找到下图位置
(2). 在natapp.cn上购买自己的用于微信开发的域名
注册地址
哈哈,这个网站上面的域名也不是特别的贵呀,我在这上面买的一个域名为期一个月的话也就才12
元,且改类型的属于二级域名,是已经备过案的,所以也就不需要备案。
(3). 下载对应的客户端进行启动
在windows
上启动的命令
natapp -authtoken 你的authtoken
启动后
可见我的域名指向了127.0.0.1:8080
。
(4).将我们的域名填到公众号中JS接口安全域名提交
提交之前我们需要将上图中的红色框框住的部分的文件下载下来放置项目的
static
目录下,测试访问通过之后,然后才能进行提交。
2.2、获取code
可谓是一波三折呀,我本来以为我这个项目就要gg
了。但也是我自己太小儿科了。微信怎么可能没有想到这么一个问题呢。就是微信公众号的 网页授权获取用户基本信息 功能服务。它这个功能服务必须只有 服务号 才拥有,但是其实每个用户可以免注册获得一个测试号,该测试号就含有这个特殊功能服务。
(1).登录自己的测试号
微信测试号是免注册的,我们直接扫码登录即可。
(2).编写对应的接口
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :小肖
* @date :Created in 2022/2/1 21:55
*/
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {
@GetMapping("/auth")
public void auth(@RequestParam("code") String code){
log.info("进入了auth方法...");
log.info("code = {}",code);
}
}
(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
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author :小肖
* @date :Created in 2022/2/1 21:55
*/
@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=appid&secret=appsecret&code=" + code + "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
}
}
(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).访问的结果
{
"access_token": "53_HK355v2MhOolNlGkaoUf4oDCkyX0WDollvsQNU5SvhsvmvF2S2VoqdPXuokfERI2oqFvQijVShq8aQzeQ9n01mGKSJn7q5rLAcYbTjm1H7k",
"expires_in": 7200,
"refresh_token": "53_C1us_G770mgzXjd-PuK329qB65lXiK483_qxUXjKudwWIdHkOz5ntwlByEgUQfMEy_-7tCCzcO4DoHaFbY0JurpZYD3Bys6DLs8ua8J_CjU",
"openid": "你的openid",
"scope": "snsapi_base"
}
3、使用第三方sdk
3.1、引入第三方依赖
<!--微信公众号开发需要引入的依赖-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.1.0</version>
</dependency>
3.2、将微信公众号配置写入yaml文件并引入类中
wechat:
mpAppId: 你的微信测试号appId
mpAppSecret: 你的微信测试号secret
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author :小肖
* @date :Created in 2022/2/2 10:31
*/
@Component
@Data
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {
/**
* 公众号id
*/
private String mpAppId;
/**
* 公众号密钥
*/
private String mpAppSecret;
}
3.3、编写配置类初始化设置wxMpService配置
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author :小肖
* @date :Created in 2022/2/2 10:24
*/
@Component
public class WechatMpConfig {
@Autowired
private WechatAccountConfig wechatAccountConfig;
@Autowired
private WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage;
@Bean
public WxMpService wxMpService(){
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
return wxMpService;
}
@Bean
public WxMpInMemoryConfigStorage wxMpConfigStorage(){
/**
* 这里需要注意的是 由于父类中没有定义对应的接口
* 所以所有的方法都在其实现类中,所以我们要构造实现类
*/
WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
return wxMpConfigStorage;
}
}
3.4、编写对应的controller
import com.xiao.enums.ResultEnum;
import com.xiao.exception.SellException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :小肖
* @date :Created in 2022/2/2 10:20
*/
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
@Autowired
private WxMpService wxMpService;
@GetMapping("/authorize")
public String authorize(@RequestParam("returnUrl") String returnUrl){
String url = "http://xiao-sell.natapp1.cc/sell/wechat/userInfo";
String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,returnUrl);
return "redirect:" + redirectUrl;
}
@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("【微信网页授权错误】 exception = {}",e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(),e.getError().getErrorMsg());
}
String openId = wxMpOAuth2AccessToken.getOpenId();
log.info("openid = {}",openId);
return "redirect:" + returnUrl + "?openid=" + openId;
}
}
3.5、进行debug测试
第一个断点
该重定向的url
很明显就是我们手工方式中获取code
的url
。
第二个断点
成功获取了code
和openid
。
来源:https://blog.csdn.net/weixin_56727438/article/details/122766235


猜你喜欢
- 引言 在c#中,可能大多数人针对于多线程之间的通讯,是熟能生巧,对于AsyncLocal 和Thre
- 安装 Tomcat 之前请一定先安装 Java ,然后才能安装 Tomcat 。安装 Java 、环境变量 path 的设置以及 cmd 小
- 全局配置无效依赖 <dependency> &n
- 由于MediaPlayer占用资源较多,且不支持同时播放多个音频,所以Android还提供了另一个播放音频的类-----SoundPool。
- 介绍Tuple是异类对象的有序序列。 我们经常可以写出返回多个值的方法,所以我们需要创建一个包含多个数据元素的简单结构。 为了支持这些情况,
- 用的Idea,在写MyBatis时,测试发现有以下的报错信息Error parsing SQL Mapper Configuration.
- 为了更好地组织类,Java 提供了包机制,用于区别类名的命名空间。包的作用1、把功能相似或相关的类或接口组织在同一个包中,方便类的查找和使用
- 最近项目中用到了文字图标的按钮,需要居中显示,如果用TextView实现的方式,必须同时设置padding和drawablePadding。
- 直接进入主题先来看一个栗子,假设现在有一个第三方dllnamespace TestLibrary1{ p
- 一、前言尽管Unity有一个像样的脚本编辑器(Mono),但很多人喜欢使用另一个编辑器。这篇短文解释了如何更改脚本编辑器,并介绍了Mono的
- strftime函数主要用于时间格式化,它的函数原型如下:size_t __cdecl strftime(char * __restrict
- ResultSet 动态获取列名和值仅供自己方便查阅,无其他用途ResultSet result = null; //前边SQL查询结果,这
- 短信是手机常见的功能,本文就以实例形式讲述了Android实现将已发送的短信写入短信数据库的方法。分享给大家供大家参考之用。具体如下:一般来
- 前言在一般能搜到的所有实现圆角窗体的示例中,都是通过绘制圆角的路径,并创建对应的窗体Region区域实现。目前所知,重新创建Region的所
- 题目一:通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。比
- 前言通过adb shell input可以模拟android各种输入事件,比如文字、按键、触摸等等。adb shell inputUsage
- 前言在单机应用时代,我们对一个共享的对象进行多线程访问的时候,使用java的synchronized关键字或者ReentrantLock类对
- 1 使用阿里的FastJson1.1 项目的pom.xml依赖<dependency> <groupId>com.a
- Springboot内部提供的事务管理器是根据autoconfigure来进行决定的。比如当使用jpa的时候,也就是pom中加入了sprin
- 在一般性开发中,笔者经常看到很多同学在对待java并发开发模型中只会使用一些基础的方法。比如Volatile,synchronized。像L