在實際業務場景中,需要一個后臺同時支持多個微信小程序的登錄。例如,企業有多個不同業務的小程序,但希望統一在同一個后臺系統里進行用戶認證和數據處理。這時候,我們就需要一個靈活的方式來管理多個小程序的 appid
和 secret
,并根據前端傳遞的 appid
與 code
獲取對應的 openid
實現登錄。
本文將基于 weixin-java-miniapp SDK 實現一個通用的多小程序登錄模塊。
一、依賴引入
在 pom.xml
中加入微信小程序 SDK 依賴:
<dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-miniapp</artifactId><version>4.7.7-20250808.182223</version>
</dependency>
二、配置文件
通過 application.yml
配置多個小程序的 appid
與 secret
,提供給后續動態獲取。
wx:miniapp:configs:- appid: wxxxxxxxxxxxxxxxxxxsecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx- appid: wyyyyyyyyyyyyyyyyyysecret: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
三、屬性類
定義配置屬性類,讀取配置文件中多個小程序的信息:
@Data
@Component
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMiniAppProperties {private List<Config> configs;@Datapublic static class Config {private String appid;private String secret;}
}
這樣就能自動綁定 application.yml
中的配置到 WxMiniAppProperties
。
四、服務工廠類
編寫一個工廠類 WxMiniAppServiceFactory
,用來存儲和獲取 WxMaService
實例。
每個小程序對應一個 WxMaService
,通過 appid
來區分。
后臺可以根據傳入的 appid
動態選擇對應的 WxMaService
。
@Component
public class WxMiniAppServiceFactory {private final Map<String, WxMaService> services = new HashMap<>();public WxMiniAppServiceFactory(WxMiniAppProperties properties) {for (WxMiniAppProperties.Config config : properties.getConfigs()) {WxMaDefaultConfigImpl wxConfig = new WxMaDefaultConfigImpl();wxConfig.setAppid(config.getAppid());wxConfig.setSecret(config.getSecret());WxMaService wxService = new WxMaServiceImpl();wxService.setWxMaConfig(wxConfig);services.put(config.getAppid(), wxService);}}public WxMaService getWxMaService(String appid) {WxMaService service = services.get(appid);if (service == null) {throw new IllegalArgumentException("未找到對應appid的配置: " + appid);}return service;}
}
五、登錄邏輯
定義登錄服務,根據前端傳遞的 appid
與 code
獲取用戶 openid
:
@Service
public class WxMiniAppLoginService {private final WxMiniAppServiceFactory serviceFactory;public WxMiniAppLoginService(WxMiniAppServiceFactory serviceFactory) {this.serviceFactory = serviceFactory;}public String getOpenId(String appid, String code) throws Exception {WxMaService wxService = serviceFactory.getWxMaService(appid);WxMaJscode2SessionResult session = wxService.jsCode2SessionInfo(code);return session.getOpenid();}
}
調用時,只需要傳入 appid
和前端 wx.login
獲取的 code
,就能拿到用戶的唯一標識 openid
。