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

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

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

在windows上啟動(dòng)的命令
natapp -authtoken 你的authtoken
啟動(dòng)后

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

提交之前我們需要將上圖中的紅色框框住的部分的文件下載下來放置項(xiàng)目的
static目錄下,測試訪問通過之后,然后才能進(jìn)行提交。
2.2、獲取code
可謂是一波三折呀,我本來以為我這個(gè)項(xiàng)目就要gg了。但也是我自己太小兒科了。微信怎么可能沒有想到這么一個(gè)問題呢。就是微信公眾號的 網(wǎng)頁授權(quán)獲取用戶基本信息 功能服務(wù)。它這個(gè)功能服務(wù)必須只有 服務(wù)號 才擁有,但是其實(shí)每個(gè)用戶可以免注冊獲得一個(gè)測試號,該測試號就含有這個(gè)特殊功能服務(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)的話那么就會(huì)報(bào)出10003 redirect_uri域名與后臺配置不一致錯(cuò)誤。
(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
注意點(diǎn)

被測試的對象必須先關(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)的接口
* 所以所有的方法都在其實(shí)現(xiàn)類中,所以我們要構(gòu)造實(shí)現(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)錯(cuò)誤】 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測試
第一個(gè)斷點(diǎn)

該重定向的url很明顯就是我們手工方式中獲取code的url。
第二個(gè)斷點(diǎn)

成功獲取了code和openid。
總結(jié)
到此這篇關(guān)于手把手教你如何獲取微信用戶openid的文章就介紹到這了,更多相關(guān)獲取微信用戶openid內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
@RefreshScope在Quartz 觸發(fā)器類導(dǎo)致異常問題解決分析
這篇文章主要為大家介紹了@RefreshScope在Quartz 觸發(fā)器類導(dǎo)致異常問題解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Java編程中隨機(jī)數(shù)的生成方式總結(jié)
在Java中利用自帶的類庫可以有三種途徑可以產(chǎn)生隨機(jī)數(shù),這里我們舉了一些簡單的例子來進(jìn)行Java編程中隨機(jī)數(shù)的生成方式總結(jié),需要的朋友可以參考下2016-05-05
springmvc使用REST出現(xiàn):Request?method?'PUT'?not?sup
這篇文章主要介紹了springmvc使用REST出現(xiàn):Request?method?'PUT'?not?supported問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Java8中Optional操作的實(shí)際應(yīng)用
Optional類是一個(gè)可以為null的容器對象,如果值存在則isPresent()方法會(huì)返回true,調(diào)用get()方法會(huì)返回該對象,下面這篇文章主要給大家介紹了關(guān)于Java8中Optional操作實(shí)際應(yīng)用的相關(guān)資料,需要的朋友可以參考下2022-02-02
java中利用反射調(diào)用另一類的private方法的簡單實(shí)例
下面小編就為大家?guī)硪黄猨ava中利用反射調(diào)用另一類的private方法的簡單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
Spring MVC Interceptor 實(shí)現(xiàn)性能監(jiān)控的功能代碼
本篇文章主要介紹了Spring MVC Interceptor 實(shí)現(xiàn)性能監(jiān)控的功能代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09
Mybatis查詢返回Map<String,Object>類型的實(shí)現(xiàn)
本文主要介紹了Mybatis查詢返回Map<String,Object>類型的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

