手把手教你如何獲取微信用戶openid
1、前言
隨著技術(shù)的發(fā)展,微信的一系列服務(wù)滲透進(jìn)了我們的生活,但是我們應(yīng)該怎樣進(jìn)行微信方面的開發(fā)呢。相信很多的小伙伴們都很渴望知道吧。這篇文章就是來解決大家的一些疑惑的。首先我們要進(jìn)行相關(guān)的開發(fā)的話,那么我們需要先獲取微信的openid。那么我們英愛怎樣獲取呢?這里我會介紹兩種方式。
2、手工方式
2.1、設(shè)置域名
(1).注冊對應(yīng)的公眾號找到下圖位置

(2). 在natapp.cn上購買自己的用于微信開發(fā)的域名

哈哈,這個網(wǎng)站上面的域名也不是特別的貴呀,我在這上面買的一個域名為期一個月的話也就才12元,且改類型的屬于二級域名,是已經(jīng)備過案的,所以也就不需要備案。
(3). 下載對應(yīng)的客戶端進(jìn)行啟動

在windows上啟動的命令
natapp -authtoken 你的authtoken
啟動后

可見我的域名指向了127.0.0.1:8080。
(4).將我們的域名填到公眾號中JS接口安全域名提交

提交之前我們需要將上圖中的紅色框框住的部分的文件下載下來放置項目的
static目錄下,測試訪問通過之后,然后才能進(jìn)行提交。
2.2、獲取code
可謂是一波三折呀,我本來以為我這個項目就要gg了。但也是我自己太小兒科了。微信怎么可能沒有想到這么一個問題呢。就是微信公眾號的 網(wǎng)頁授權(quán)獲取用戶基本信息 功能服務(wù)。它這個功能服務(wù)必須只有 服務(wù)號 才擁有,但是其實每個用戶可以免注冊獲得一個測試號,該測試號就含有這個特殊功能服務(wù)。
(1).登錄自己的測試號

微信測試號是免注冊的,我們直接掃碼登錄即可。
(2).編寫對應(yīng)的接口
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("進(jìn)入了auth方法...");
log.info("code = {}",code);
}
}
(3).在登錄測試號之后進(jìn)行網(wǎng)頁授權(quán)


授權(quán)的域名就是我們在
natapp.cn上購買的域名,如果沒有進(jìn)行授權(quán)的話那么就會報出10003 redirect_uri域名與后臺配置不一致錯誤。
(4).進(jìn)行訪問url進(jìn)行測試
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
注意點

被測試的對象必須先關(guān)注對應(yīng)的測試號且必須在微信客戶端進(jìn)行訪問。
(5).測試結(jié)果

成功獲取了用戶的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("進(jìn)入了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
| 參數(shù) | 是否必須 | 說明 |
|---|---|---|
| appid | 是 | 公眾號的唯一標(biāo)識 |
| secret | 是 | 公眾號的appsecret |
| code | 是 | 填寫第一步獲取的code參數(shù) |
| grant_type | 是 | 填寫為authorization_code |
(3).訪問的結(jié)果
{
"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、引入第三方依賴
<!--微信公眾號開發(fā)需要引入的依賴-->
<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、編寫配置類初始化設(shè)置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(){
/**
* 這里需要注意的是 由于父類中沒有定義對應(yīng)的接口
* 所以所有的方法都在其實現(xiàn)類中,所以我們要構(gòu)造實現(xiàn)類
*/
WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
return wxMpConfigStorage;
}
}
3.4、編寫對應(yīng)的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("【微信網(wǎng)頁授權(quán)錯誤】 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、進(jìn)行debug測試
第一個斷點

該重定向的url很明顯就是我們手工方式中獲取code的url。
第二個斷點

成功獲取了code和openid。
總結(jié)
到此這篇關(guān)于手把手教你如何獲取微信用戶openid的文章就介紹到這了,更多相關(guān)獲取微信用戶openid內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談java中BigDecimal的equals與compareTo的區(qū)別
下面小編就為大家?guī)硪黄獪\談java中BigDecimal的equals與compareTo的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11
實例化JFileChooser對象報空指針異常問題的解決辦法
今天小編就為大家分享一篇關(guān)于實例化JFileChooser對象報空指針異常問題的解決辦法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02
SpringBoot3 Spring WebFlux簡介(推薦)
SpringWebFlux是Spring Framework 5中引入的響應(yīng)式Web框架,用于支持非阻塞異步通信和響應(yīng)式流處理,與傳統(tǒng)的SpringMVC相比,WebFlux提供了完全異步非阻塞的編程模型,適用高并發(fā)、微服務(wù)架構(gòu)和實時數(shù)據(jù)流,本文介紹SpringBoot3 Spring WebFlux簡介,感興趣的朋友一起看看吧2024-10-10
SpringSecurity的@EnableWebSecurity注解詳解
這篇文章主要介紹了SpringSecurity的@EnableWebSecurity注解詳解,@EnableWebSecurity是開啟SpringSecurity的默認(rèn)行為,它的上面有一個Import注解導(dǎo)入了WebSecurityConfiguration類,就是往IOC容器中注入了WebSecurityConfiguration這個類,需要的朋友可以參考下2023-11-11
spring?cloud之eureka高可用集群和服務(wù)分區(qū)解析
這篇文章主要介紹了spring?cloud之eureka高可用集群和服務(wù)分區(qū)解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

