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

(2). 在natapp.cn上購(gòu)買(mǎi)自己的用于微信開(kāi)發(fā)的域名

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

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

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

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

微信測(cè)試號(hào)是免注冊(cè)的,我們直接掃碼登錄即可。
(2).編寫(xiě)對(duì)應(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).在登錄測(cè)試號(hào)之后進(jìn)行網(wǎng)頁(yè)授權(quán)


授權(quán)的域名就是我們?cè)?code>natapp.cn上購(gòu)買(mǎi)的域名,如果沒(méi)有進(jìn)行授權(quán)的話那么就會(huì)報(bào)出
10003 redirect_uri域名與后臺(tái)配置不一致錯(cuò)誤。
(4).進(jìn)行訪問(wèn)url進(jìn)行測(cè)試
https://open.weixin.qq.com/connect/oauth2/authorize?appid=測(cè)試號(hào)的appid&redirect_uri=http://你的域名/sell/weixin/auth&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
注意點(diǎn)

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

成功獲取了用戶(hù)的code信息。
2.3、換取access_token
(1).編寫(xiě)的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).訪問(wèn)的url組成
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
| 參數(shù) | 是否必須 | 說(shuō)明 |
|---|---|---|
| appid | 是 | 公眾號(hào)的唯一標(biāo)識(shí) |
| secret | 是 | 公眾號(hào)的appsecret |
| code | 是 | 填寫(xiě)第一步獲取的code參數(shù) |
| grant_type | 是 | 填寫(xiě)為authorization_code |
(3).訪問(wèn)的結(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、引入第三方依賴(lài)
<!--微信公眾號(hào)開(kāi)發(fā)需要引入的依賴(lài)-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.1.0</version>
</dependency>
3.2、將微信公眾號(hào)配置寫(xiě)入yaml文件并引入類(lèi)中
wechat: mpAppId: 你的微信測(cè)試號(hào)appId mpAppSecret: 你的微信測(cè)試號(hào)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 {
/**
* 公眾號(hào)id
*/
private String mpAppId;
/**
* 公眾號(hào)密鑰
*/
private String mpAppSecret;
}
3.3、編寫(xiě)配置類(lèi)初始化設(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(){
/**
* 這里需要注意的是 由于父類(lèi)中沒(méi)有定義對(duì)應(yīng)的接口
* 所以所有的方法都在其實(shí)現(xiàn)類(lèi)中,所以我們要構(gòu)造實(shí)現(xiàn)類(lèi)
*/
WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
return wxMpConfigStorage;
}
}
3.4、編寫(xiě)對(duì)應(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)頁(yè)授權(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測(cè)試
第一個(gè)斷點(diǎn)

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

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

