### Spring Boot Full Configuration Example Source: https://github.com/binarywang/wxjava/blob/develop/docs/HTTPCLIENT_UPGRADE_GUIDE.md A comprehensive configuration example for Spring Boot, including WxMp settings, HTTP client type, optional proxy configuration, and timeout settings. ```properties # 公众号配置 wx.mp.app-id=your_app_id wx.mp.secret=your_secret wx.mp.token=your_token wx.mp.aes-key=your_aes_key # HTTP 客户端配置 wx.mp.config-storage.http-client-type=HttpComponents # HttpComponents, HttpClient, OkHttp, JoddHttp # HTTP 代理配置(可选) wx.mp.config-storage.http-proxy-host=proxy.example.com wx.mp.config-storage.http-proxy-port=8080 wx.mp.config-storage.http-proxy-username=proxy_user wx.mp.config-storage.http-proxy-password=proxy_pass # 超时配置(可选) wx.mp.config-storage.connection-timeout=5000 wx.mp.config-storage.so-timeout=5000 wx.mp.config-storage.connection-request-timeout=5000 ``` -------------------------------- ### WxJava Media Upload Example Source: https://github.com/binarywang/wxjava/wiki/CP_如何调用未支持的接口 An example of uploading media using the execute method with a custom MediaUploadRequestExecutor. This demonstrates how to handle file uploads with specific content types. ```java public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException { String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType; return execute(new MediaUploadRequestExecutor(), url, file); } ``` -------------------------------- ### Usage Example with WxOpenMultiServices Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-open-multi-spring-boot-starter/README.md Demonstrates how to inject and use WxOpenMultiServices to obtain WxOpenService instances for different tenant IDs. Includes a check for null service. ```java import com.binarywang.spring.starter.wxjava.open.service.WxOpenMultiServices; import me.chanjar.weixin.open.api.WxOpenService; import me.chanjar.weixin.open.api.WxOpenComponentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DemoService { @Autowired private WxOpenMultiServices wxOpenMultiServices; public void test() { // 应用 1 的 WxOpenService WxOpenService wxOpenService1 = wxOpenMultiServices.getWxOpenService("tenantId1"); WxOpenComponentService componentService1 = wxOpenService1.getWxOpenComponentService(); // todo ... // 应用 2 的 WxOpenService WxOpenService wxOpenService2 = wxOpenMultiServices.getWxOpenService("tenantId2"); WxOpenComponentService componentService2 = wxOpenService2.getWxOpenComponentService(); // todo ... // 应用 3 的 WxOpenService WxOpenService wxOpenService3 = wxOpenMultiServices.getWxOpenService("tenantId3"); // 判断是否为空 if (wxOpenService3 == null) { // todo wxOpenService3 为空,请先配置 tenantId3 微信开放平台应用参数 return; } WxOpenComponentService componentService3 = wxOpenService3.getWxOpenComponentService(); // todo ... } } ``` -------------------------------- ### Send Video Mass Message Source: https://github.com/binarywang/wxjava/wiki/MP_群发消息 This example demonstrates sending a video message. It involves uploading the video to get a media ID, then creating a WxMpMassVideo object, uploading it, and finally sending the mass message with the obtained media ID. ```java WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MEDIA_VIDEO, "mp4", inputStream); // 把视频变成可被群发的媒体 WxMpMassVideo video = new WxMpMassVideo(); video.setTitle("测试标题"); video.setDescription("测试描述"); video.setMediaId(uploadMediaRes.getMediaId()); WxMpMassUploadResult uploadResult = wxMpService.getMassMessageService().massVideoUpload(video); WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage(); massMessage.setMsgType(WxConsts.MASS_MSG_VIDEO); massMessage.setMediaId(uploadResult.getMediaId()); massMessage.getToUsers().add(openid); WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage); ``` -------------------------------- ### Configure Mixed V2 and V3 Settings Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-pay-multi-spring-boot-starter/README.md Example of how to define multiple configurations in YAML, allowing for mixed usage of V2 and V3 API settings. ```yml wx: pay: configs: app1: # V2配置 appId: wx111 mchId: 111 mchKey: xxx app2: # V3配置 appId: wx222 mchId: 222 apiV3Key: yyy privateKeyPath: xxx ``` -------------------------------- ### Initiate Transfer (New API) Source: https://github.com/binarywang/wxjava/blob/develop/docs/NEW_TRANSFER_API_SUPPORT.md Example code for initiating a transfer using the new `TransferService` in WxJava, including request parameters and handling the response. ```APIDOC ## Initiate Transfer (New API) ### Description This section provides a code example for initiating a transfer using the `transferBills` method of the `TransferService`. It covers building the `TransferBillsRequest` with necessary details and processing the `TransferBillsResult`. ### Method Java Code ### Endpoint `/v3/fund-app/mch-transfer/transfer-bills` ### Parameters #### Request Body (`TransferBillsRequest`) - **appid** (string) - Required - Application ID - **outBillNo** (string) - Required - Merchant transfer bill number - **transferSceneId** (string) - Required - Transfer scene ID (e.g., '1005' for commission payout) - **openid** (string) - Required - User's OpenID - **userName** (string) - Optional - Payee's name (automatically encrypted) - **transferAmount** (integer) - Required - Transfer amount in cents - **transferRemark** (string) - Required - Transfer remark - **receiptAuthorizationMode** (string) - Optional - Receipt authorization mode (e.g., `WxPayConstants.ReceiptAuthorizationMode.NO_CONFIRM_RECEIPT_AUTHORIZATION` for no-confirmation mode) ### Request Example ```java // Build transfer request TransferBillsRequest request = TransferBillsRequest.newBuilder() .appid("your_appid") // Application ID .outBillNo("T" + System.currentTimeMillis()) // Merchant transfer bill number .transferSceneId("1005") // Transfer scene ID (commission payout) .openid("user_openid") // User openid .userName("张三") // Payee's name (optional, auto-encrypted) .transferAmount(100) // Transfer amount (cents) .transferRemark("佣金报酬") // Transfer remark .build(); // Initiate transfer TransferBillsResult result = transferService.transferBills(request); System.out.println("Transfer successful, WeChat transfer bill number: " + result.getTransferBillNo()); ``` ### Response #### Success Response (200) - **transferBillNo** (string) - WeChat's unique transfer bill number ``` -------------------------------- ### Usage Example Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-channel-spring-boot-starter/README.md Inject WxChannelService into your service class to interact with the WeChat Channel API. ```java import me.chanjar.weixin.channel.api.WxChannelService; import me.chanjar.weixin.channel.bean.shop.ShopInfoResponse; import me.chanjar.weixin.channel.util.JsonUtils; import me.chanjar.weixin.common.error.WxErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DemoService { @Autowired private WxChannelService wxChannelService; public String getShopInfo() throws WxErrorException { // 获取店铺基本信息 ShopInfoResponse response = wxChannelService.getBasicService().getShopInfo(); // 此处为演示,如果要返回response的结果,建议自己封装一个VO,避免直接返回response return JsonUtils.encode(response); } } ``` -------------------------------- ### Java Example: Accessing Multiple WxMpServices Source: https://github.com/binarywang/wxjava/blob/develop/solon-plugins/wx-java-mp-multi-solon-plugin/README.md Demonstrates how to inject and use WxMpMultiServices to obtain WxMpService instances for different WeChat Official Accounts using their tenant IDs. Includes checks for null services. ```java import com.binarywang.solon.wxjava.mp_multi.service.WxMpMultiServices; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpUserService; import org.noear.solon.annotation.Component; import org.noear.solon.annotation.Inject; @Component public class DemoService { @Inject private WxMpMultiServices wxMpMultiServices; public void test() { // 应用 1 的 WxMpService WxMpService wxMpService1 = wxMpMultiServices.getWxMpService("tenantId1"); WxMpUserService userService1 = wxMpService1.getUserService(); userService1.userInfo("xxx"); // todo ... // 应用 2 的 WxMpService WxMpService wxMpService2 = wxMpMultiServices.getWxMpService("tenantId2"); WxMpUserService userService2 = wxMpService2.getUserService(); userService2.userInfo("xxx"); // todo ... // 应用 3 的 WxMpService WxMpService wxMpService3 = wxMpMultiServices.getWxMpService("tenantId3"); // 判断是否为空 if (wxMpService3 == null) { // todo wxMpService3 为空,请先配置 tenantId3 微信公众号应用参数 return; } WxMpUserService userService3 = wxMpService3.getUserService(); userService3.userInfo("xxx"); // todo ... } } ``` -------------------------------- ### WxMpXmlOutVideoMessage Construction Source: https://github.com/binarywang/wxjava/wiki/MP_同步回复消息 Example of how to construct a synchronous video message reply using WxMpXmlOutVideoMessage. ```APIDOC ## Constructing a Video Message Reply Use `WxMpXmlOutMessage.VIDEO()` to build a video message response. ### Request Example ```java WxMpXmlOutMessage.VIDEO() .mediaId("your_media_id") .fromUser("to_user_id") .toUser("from_user_id") .title("Video Title") .description("Video Description") .build(); ``` ### Parameters - **mediaId** (string) - Required - The media ID of the video. - **fromUser** (string) - Required - The recipient's user ID. - **toUser** (string) - Required - The sender's user ID. - **title** (string) - Optional - The title of the video. - **description** (string) - Optional - The description of the video. ``` -------------------------------- ### WxMpXmlOutMusicMessage Construction Source: https://github.com/binarywang/wxjava/wiki/MP_同步回复消息 Example of how to construct a synchronous music message reply using WxMpXmlOutMusicMessage. ```APIDOC ## Constructing a Music Message Reply Use `WxMpXmlOutMessage.MUSIC()` to build a music message response. ### Request Example ```java WxMpXmlOutMessage.MUSIC() .fromUser("to_user_id") .toUser("from_user_id") .title("Music Title") .description("Music Description") .hqMusicUrl("high_quality_music_url") .musicUrl("music_url") .thumbMediaId("your_thumb_media_id") .build(); ``` ### Parameters - **fromUser** (string) - Required - The recipient's user ID. - **toUser** (string) - Required - The sender's user ID. - **title** (string) - Required - The title of the music. - **description** (string) - Required - The description of the music. - **hqMusicUrl** (string) - Optional - The URL for the high-quality music. - **musicUrl** (string) - Required - The URL for the music. - **thumbMediaId** (string) - Required - The media ID of the music's thumbnail. ``` -------------------------------- ### Customizing HttpClient via DefaultApacheHttpClientBuilder Source: https://github.com/binarywang/wxjava/wiki/HttpClient相关参数的设置方法 Example of configuring proxy settings and custom HttpClient parameters before setting them on the config storage. ```java Wx**InMemoryConfigStorage config = new Wx**InMemoryConfigStorage(); config.setHttpProxyHost(..);//设置代理地址,没有可以无需设置 config.setHttpProxyPort(..);//设置代理端口,没有可以无需设置 config.setHttpProxyUsername(..);//设置代理用户名,没有可以无需设置 config.setHttpProxyPassword(..);//设置代理密码,没有可以无需设置 DefaultApacheHttpClientBuilder clientBuilder = DefaultApacheHttpClientBuilder.get(); clientBuilder.setConnectionRequestTimeout(..)//从连接池获取链接的超时时间(单位ms) clientBuilder.setConnectionTimeout(..)//建立链接的超时时间(单位ms) clientBuilder.setSoTimeout(..)//连接池socket超时时间(单位ms) clientBuilder.setIdleConnTimeout(..)//空闲链接的超时时间(单位ms) clientBuilder.setCheckWaitTime(..)//空闲链接的检测周期(单位ms) clientBuilder.setMaxConnPerHost(..)//每路最大连接数 clientBuilder.setMaxTotalConn(..)//连接池最大连接数 clientBuilder.setUserAgent(..)//HttpClient请求时使用的User Agent config.setApacheHttpClientBuilder(clientBuilder); //设置自定义的ApacheHttpClientBuilder ``` -------------------------------- ### WxSessionManager Usage Example Source: https://github.com/binarywang/wxjava/wiki/WxSession Example of using WxSessionManager to get a session, typically using the sender's username as the sessionId to associate all messages from that user. ```java public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, WxCpService wxCpService, WxSessionManager sessionManager) { sessionManager.getSession(wxMessage.getFromUserName()); // ... return null; } ``` -------------------------------- ### Official Account (MP) Example: Get AccessToken Source: https://github.com/binarywang/wxjava/blob/develop/README.md This example demonstrates how to obtain an AccessToken for a WeChat Official Account. Ensure you have configured your AppId and Secret. ```java WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl(); config.setAppId("your-app-id"); config.setSecret("your-secret"); WxMpService wxMpService = new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(config); String accessToken = wxMpService.getAccessToken(); System.out.println(accessToken); ``` -------------------------------- ### 配置 Spring Boot Starter 依赖 Source: https://context7.com/binarywang/wxjava/llms.txt 在 pom.xml 中添加 WxJava 各模块的 Spring Boot Starter 依赖。 ```xml com.github.binarywang wx-java-mp-spring-boot-starter 4.8.0 com.github.binarywang wx-java-miniapp-spring-boot-starter 4.8.0 com.github.binarywang wx-java-pay-spring-boot-starter 4.8.0 com.github.binarywang wx-java-cp-spring-boot-starter 4.8.0 ``` -------------------------------- ### Mini Program (MiniApp) Example: code2Session Source: https://github.com/binarywang/wxjava/blob/develop/README.md This example shows how to use the code2Session method for a WeChat Mini Program to get session information. You need to provide your AppId, Secret, and the JS code. ```java WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); config.setAppid("your-app-id"); config.setSecret("your-secret"); WxMaService wxMaService = new WxMaServiceImpl(); wxMaService.setWxMaConfig(config); WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo("js-code"); System.out.println(result.getOpenid()); ``` -------------------------------- ### Configure WxPayConfig and WxPayService Source: https://github.com/binarywang/wxjava/wiki/微信支付 Instantiate and configure WxPayConfig, then create a WxPayService instance and set the configuration. ```java WxPayConfig payConfig = new WxPayConfig(); .... WxPayService wxPayService = new WxPayServiceImpl(); wxPayService.setConfig(payConfig); ``` -------------------------------- ### GET materialNewsInfo Source: https://github.com/binarywang/wxjava/wiki/MP_永久素材管理 Retrieves a permanent news material by its media_id. ```APIDOC ## GET materialNewsInfo ### Description Fetches the details of a permanent news material. ### Parameters #### Query Parameters - **media_id** (String) - Required - The unique identifier of the news material. ``` -------------------------------- ### Instantiate Service with HttpClient 5.x in Pure Java Source: https://github.com/binarywang/wxjava/blob/develop/docs/HTTPCLIENT_UPGRADE_GUIDE.md For pure Java projects, instantiate the WxMpService using `WxMpServiceHttpComponentsImpl` to utilize HttpClient 5.x. Alternatively, use `WxMpServiceHttpClientImpl` to continue using HttpClient 4.x. ```java // 使用 HttpClient 5.x(推荐) WxMpService wxMpService = new WxMpServiceHttpComponentsImpl(); // 或者继续使用 HttpClient 4.x WxMpService wxMpService = new WxMpServiceHttpClientImpl(); ``` -------------------------------- ### Include Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-cp-spring-boot-starter/README.md Add the starter dependency to your project's pom.xml file. Replace ${version} with the desired library version. ```xml com.github.binarywang wx-java-cp-spring-boot-starter ${version} ``` -------------------------------- ### GET materialCount Source: https://github.com/binarywang/wxjava/wiki/MP_永久素材管理 Retrieves the total count of various permanent materials. ```APIDOC ## GET materialCount ### Description Returns the total count of voice, video, image, and news materials. ### Response #### Success Response (200) - **voice_count** (int) - **video_count** (int) - **image_count** (int) - **news_count** (int) ``` -------------------------------- ### 创建企业微信部门 Source: https://github.com/binarywang/wxjava/wiki/CP_部门管理 实例化 WxCpDepart 对象并设置必要属性,通过 create 方法提交至企业微信。 ```java WxCpDepart depart = new WxCpDepart(); depart.setName("子部门" + System.currentTimeMillis()); depart.setParentId(1L); depart.setOrder(1L); Integer departId = wxCpService.getDepartmentService().create(depart); ``` -------------------------------- ### Get User Tag List Source: https://github.com/binarywang/wxjava/wiki/MP_标签管理 Retrieves the list of all existing user tags. ```java List res = this.wxService.getUserTagService().tagGet(); ``` -------------------------------- ### Get Custom Menu Source: https://github.com/binarywang/wxjava/wiki/CP_自定义菜单管理 This endpoint retrieves the current custom menu configuration. ```APIDOC ## GET /menu/get ### Description Retrieves the custom menu. ### Method GET ### Endpoint /menu/get ### Response #### Success Response (200) - **wxMenu** (WxMenu) - The WxMenu object representing the current custom menu configuration. ### Response Example ```java WxMenu wxMenu = wxCpService.menuGet(); ``` ``` -------------------------------- ### Get users under a tag Source: https://github.com/binarywang/wxjava/wiki/CP_标签管理 Retrieves all users associated with a specific tag ID. ```java List users = wxService.tagGetUsers(tagId); ``` -------------------------------- ### Implement Multi-Service WeChat Pay Operations Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-pay-multi-spring-boot-starter/README.md Demonstrates how to use WxPayMultiServices to retrieve specific configurations and perform V3 order creation, service provider operations, and order queries. ```java import com.binarywang.spring.starter.wxjava.pay.service.WxPayMultiServices; import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request; import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryV3Result; import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result; import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum; import com.github.binarywang.wxpay.service.WxPayService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PayService { @Autowired private WxPayMultiServices wxPayMultiServices; /** * 为不同的公众号创建支付订单 * * @param configKey 配置标识(即 wx.pay.configs. 中的 key,可以是 appId 或自定义标识) */ public void createOrder(String configKey, String openId, Integer totalFee, String body) throws Exception { // 根据配置标识获取对应的WxPayService WxPayService wxPayService = wxPayMultiServices.getWxPayService(configKey); if (wxPayService == null) { throw new IllegalArgumentException("未找到配置标识对应的微信支付配置: " + configKey); } // 使用WxPayService进行支付操作 WxPayUnifiedOrderV3Request request = new WxPayUnifiedOrderV3Request(); request.setOutTradeNo(generateOutTradeNo()); request.setDescription(body); request.setAmount(new WxPayUnifiedOrderV3Request.Amount().setTotal(totalFee)); request.setPayer(new WxPayUnifiedOrderV3Request.Payer().setOpenid(openId)); request.setNotifyUrl(wxPayService.getConfig().getNotifyUrl()); // V3统一下单 WxPayUnifiedOrderV3Result.JsapiResult result = wxPayService.createOrderV3(TradeTypeEnum.JSAPI, request); // 返回给前端用于调起支付 // ... } /** * 服务商模式示例 */ public void serviceProviderExample(String configKey) throws Exception { // 使用配置标识获取WxPayService WxPayService wxPayService = wxPayMultiServices.getWxPayService(configKey); if (wxPayService == null) { throw new IllegalArgumentException("未找到配置: " + configKey); } // 获取子商户的配置信息 String subAppId = wxPayService.getConfig().getSubAppId(); String subMchId = wxPayService.getConfig().getSubMchId(); // 进行支付操作 // ... } /** * 查询订单示例 * * @param configKey 配置标识(即 wx.pay.configs. 中的 key) */ public void queryOrder(String configKey, String outTradeNo) throws Exception { WxPayService wxPayService = wxPayMultiServices.getWxPayService(configKey); if (wxPayService == null) { throw new IllegalArgumentException("未找到配置标识对应的微信支付配置: " + configKey); } // 查询订单 WxPayOrderQueryV3Result result = wxPayService.queryOrderV3(null, outTradeNo); // 处理查询结果 // ... } private String generateOutTradeNo() { // 生成商户订单号 return "ORDER_" + System.currentTimeMillis(); } } ``` -------------------------------- ### Retrieve User List Source: https://github.com/binarywang/wxjava/wiki/MP_用户管理 Retrieves a list of users starting from the specified next_openid. ```java WxMpUserList wxUserList = wxMpService.getUserService().userList(next_openid); ``` -------------------------------- ### Initialize WeChat Pay Service Source: https://context7.com/binarywang/wxjava/llms.txt Sets up the WxPayService with merchant credentials and API V3 security configurations. ```java import com.github.binarywang.wxpay.config.WxPayConfig; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl; // 初始化支付配置 WxPayConfig payConfig = new WxPayConfig(); payConfig.setAppId("公众号或小程序的appid"); payConfig.setMchId("商户号"); payConfig.setMchKey("API密钥"); payConfig.setKeyPath("/path/to/apiclient_cert.p12"); // 证书路径 // API V3 配置(推荐) payConfig.setApiV3Key("APIv3密钥"); payConfig.setPrivateKeyPath("/path/to/apiclient_key.pem"); payConfig.setPrivateCertPath("/path/to/apiclient_cert.pem"); // 创建支付服务 WxPayService wxPayService = new WxPayServiceImpl(); wxPayService.setConfig(payConfig); ``` -------------------------------- ### WxMpXmlOutNewsMessage Construction Source: https://github.com/binarywang/wxjava/wiki/MP_同步回复消息 Example of how to construct a synchronous news message reply using WxMpXmlOutNewsMessage. ```APIDOC ## Constructing a News Message Reply Use `WxMpXmlOutNewsMessage.Item` to define articles and `WxMpXmlOutMessage.NEWS()` to build a news message response. ### Request Example ```java // Define a news item WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item(); item.setDescription("Article Description"); item.setPicUrl("image_url"); item.setTitle("Article Title"); item.setUrl("article_url"); // Build the news message WxMpXmlOutNewsMessage m = WxMpXmlOutMessage.NEWS() .fromUser("to_user_id") .toUser("from_user_id") .addArticle(item) // Add one or more articles .build(); ``` ### Parameters for Item - **description** (string) - Optional - The description of the article. - **picUrl** (string) - Optional - The URL of the article's image. - **title** (string) - Required - The title of the article. - **url** (string) - Required - The URL of the article. ### Parameters for NEWS message - **fromUser** (string) - Required - The recipient's user ID. - **toUser** (string) - Required - The sender's user ID. - **articles** (list of Item) - Required - A list of news items to include in the message. ``` -------------------------------- ### 获取WxPayService实例和RealNameService Source: https://github.com/binarywang/wxjava/blob/develop/weixin-java-pay/REAL_NAME_USAGE.md 初始化WxPayService并获取RealNameService实例以进行后续操作。请根据你的具体配置来初始化WxPayService。 ```java WxPayService wxPayService = ... // 根据你的配置初始化 RealNameService realNameService = wxPayService.getRealNameService(); ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-mp-multi-spring-boot-starter/README.md Include the starter dependency in your project's pom.xml file. ```xml com.github.binarywang wx-java-mp-multi-spring-boot-starter ${version} ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-miniapp-multi-spring-boot-starter/README.md Include the starter dependency in your project's pom.xml file. ```xml com.github.binarywang wx-java-miniapp-multi-spring-boot-starter ${version} ``` -------------------------------- ### WxMpXmlOutVoiceMessage Construction Source: https://github.com/binarywang/wxjava/wiki/MP_同步回复消息 Example of how to construct a synchronous voice message reply using WxMpXmlOutVoiceMessage. ```APIDOC ## Constructing a Voice Message Reply Use `WxMpXmlOutMessage.VOICE()` to build a voice message response. ### Request Example ```java WxMpXmlOutMessage.VOICE() .mediaId("your_media_id") .fromUser("to_user_id") .toUser("from_user_id") .build(); ``` ### Parameters - **mediaId** (string) - Required - The media ID of the voice. - **fromUser** (string) - Required - The recipient's user ID. - **toUser** (string) - Required - The sender's user ID. ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-cp-multi-spring-boot-starter/README.md Include the starter dependency in your project's pom.xml file. ```xml com.github.binarywang wx-java-cp-multi-spring-boot-starter ${version} ``` -------------------------------- ### WxMpXmlOutImageMessage Construction Source: https://github.com/binarywang/wxjava/wiki/MP_同步回复消息 Example of how to construct a synchronous image message reply using WxMpXmlOutImageMessage. ```APIDOC ## Constructing an Image Message Reply Use `WxMpXmlOutMessage.IMAGE()` to build an image message response. ### Request Example ```java WxMpXmlOutMessage.IMAGE() .mediaId("your_media_id") .fromUser("to_user_id") .toUser("from_user_id") .build(); ``` ### Parameters - **mediaId** (string) - Required - The media ID of the image. - **fromUser** (string) - Required - The recipient's user ID. - **toUser** (string) - Required - The sender's user ID. ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-open-spring-boot-starter/README.md Include the starter dependency in your project's pom.xml file. ```xml com.github.binarywang wx-java-open-spring-boot-starter ${version} ``` -------------------------------- ### WxMpXmlOutTextMessage Construction Source: https://github.com/binarywang/wxjava/wiki/MP_同步回复消息 Example of how to construct a synchronous text message reply using WxMpXmlOutTextMessage. ```APIDOC ## Constructing a Text Message Reply Use `WxMpXmlOutMessage.TEXT()` to build a text message response. ### Request Example ```java WxMpXmlOutMessage.TEXT() .content("Your text content here") .fromUser("to_user_id") // The user who sent the message .toUser("from_user_id") // The official account ID .build(); ``` ### Parameters - **content** (string) - Required - The text content of the message. - **fromUser** (string) - Required - The recipient's user ID (usually the `FromUserName` from the incoming message). - **toUser** (string) - Required - The sender's user ID (usually the `ToUserName` from the incoming message, which is the official account ID). ``` -------------------------------- ### 构造视频消息 Source: https://github.com/binarywang/wxjava/wiki/CP_主动发送消息 使用 WxCpMessage.VIDEO() 构造视频消息,包含标题、描述及媒体 ID。 ```java WxCpMessage.VIDEO() .agentId(...) // 企业号应用ID .toUser("非必填,UserID列表(消息接收者,多个接收者用‘|’分隔)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送") .toParty("非必填,PartyID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数") .toTag("非必填,TagID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数") .title("TITLE") .mediaId("MEDIA_ID") .thumbMediaId("MEDIA_ID") .description("DESCRIPTION") .build(); ``` -------------------------------- ### Configure Application Properties Source: https://github.com/binarywang/wxjava/blob/develop/solon-plugins/wx-java-miniapp-multi-solon-plugin/README.md Define multiple MiniApp tenant configurations and storage settings in app.properties. ```properties # 公众号配置 ## 应用 1 配置(必填) wx.ma.apps.tenantId1.app-id=appId wx.ma.apps.tenantId1.app-secret=@secret ## 选填 wx.ma.apps.tenantId1.token=@token wx.ma.apps.tenantId1.aes-key=@aesKey wx.ma.apps.tenantId1.use-stable-access-token=@useStableAccessToken ## 应用 2 配置(必填) wx.ma.apps.tenantId2.app-id=@appId wx.ma.apps.tenantId2.app-secret =@secret ## 选填 wx.ma.apps.tenantId2.token=@token wx.ma.apps.tenantId2.aes-key=@aesKey wx.ma.apps.tenantId2.use-stable-access-token=@useStableAccessToken # ConfigStorage 配置(选填) ## 配置类型: memory(默认), jedis, redisson wx.ma.config-storage.type=memory ## 相关redis前缀配置: wx:ma:multi(默认) wx.ma.config-storage.key-prefix=wx:ma:multi wx.ma.config-storage.redis.host=127.0.0.1 wx.ma.config-storage.redis.port=6379 ## 单机和 sentinel 同时存在时,优先使用sentinel配置 # wx.ma.config-storage.redis.sentinel-ips=127.0.0.1:16379,127.0.0.1:26379 # wx.ma.config-storage.redis.sentinel-name=mymaster # http 客户端配置(选填) ## # http客户端类型: http_client(默认), ok_http, jodd_http wx.ma.config-storage.http-client-type=http_client wx.ma.config-storage.http-proxy-host= wx.ma.config-storage.http-proxy-port= wx.ma.config-storage.http-proxy-username= wx.ma.config-storage.http-proxy-password= ## 最大重试次数,默认:5 次,如果小于 0,则为 0 wx.ma.config-storage.max-retry-times=5 ## 重试时间间隔步进,默认:1000 毫秒,如果小于 0,则为 1000 wx.ma.config-storage.retry-sleep-millis=1000 ``` -------------------------------- ### Get WxCpUser by ID Source: https://github.com/binarywang/wxjava/wiki/CP_用户管理 Retrieve a user's details using their unique user ID. ```java WxCpUser user = wxCpService.getUserService().getById("demo.user"); ``` -------------------------------- ### Send Hello World Message with WxJava Source: https://github.com/binarywang/wxjava/wiki/CP_Quick-Start Initializes the service configuration and sends a text message to a specific user. ```java WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl(); config.setCorpId("..."); // 设置微信企业号的appid config.setCorpSecret("..."); // 设置微信企业号的app corpSecret config.setAgentId("..."); // 设置微信企业号应用ID config.setToken("..."); // 设置微信企业号应用的token config.setAesKey("..."); // 设置微信企业号应用的EncodingAESKey WxCpServiceImpl wxCpService = new WxCpServiceImpl(); wxCpService.setWxCpConfigStorage(config); String userId = "..."; WxCpMessage message = WxCpMessage.TEXT().agentId("...").toUser(userId).content("Hello World").build(); wxCpService.messageSend(message); ``` -------------------------------- ### Custom WxSessionManager Implementation Source: https://github.com/binarywang/wxjava/wiki/WxSession Developers can provide their own WxSessionManager implementations, for example, based on file systems or clusters. ```APIDOC ## Custom WxSessionManager The default `WxSessionManager` implementation in this project is memory-based. Developers can implement their own `WxSessionManager` based on requirements, such as file system or cluster-based storage. To use a custom implementation, set it using `setSessionManager` before routing messages: ```java // Assuming 'myCustomSessionManager' is an instance of your custom WxSessionManager implementation wxMessageRouter.setSessionManager(myCustomSessionManager); wxMessageRouter.route(msg, context, wxCpService, null); ``` ``` -------------------------------- ### Batch Get Approval Information Source: https://github.com/binarywang/wxjava/blob/develop/weixin-java-cp/APPROVAL_WORKFLOW_GUIDE.md Fetches a list of approval numbers within a specified time range. ```java // Get approval info with filters Date startTime = new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000); Date endTime = new Date(); WxCpApprovalInfo approvalInfo = wxCpService.getOaService() .getApprovalInfo(startTime, endTime, "0", 100, null); List spNumbers = approvalInfo.getSpNoList(); ``` -------------------------------- ### 配置隔离模式多租户 Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-miniapp-multi-spring-boot-starter/MULTI_TENANT_MODE.md 在 application.yml 中配置隔离模式,这是默认的多租户实现方式。 ```yaml wx: ma: # 多租户配置 apps: tenant1: app-id: wxd898fcb01713c555 app-secret: 47a2422a5d04a27e2b3ed1f1f0b0dbad token: aBcDeFg123456 aes-key: abcdefgh123456abcdefgh123456abc tenant2: app-id: wx1234567890abcdef app-secret: 1234567890abcdef1234567890abcdef token: token123 aes-key: aeskey123aeskey123aeskey123aes # 配置存储(可选) config-storage: type: memory # memory, jedis, redisson, redis_template http-client-type: http_client # http_client, ok_http, jodd_http # multi-tenant-mode: isolated # 默认值,可以不配置 ``` -------------------------------- ### Get Approval Details Source: https://github.com/binarywang/wxjava/blob/develop/weixin-java-cp/APPROVAL_WORKFLOW_GUIDE.md Retrieves detailed information for a specific approval request using its approval number. ```java // Get approval details by approval number WxCpApprovalDetailResult result = wxCpService.getOaService() .getApprovalDetail("approval_number"); WxCpApprovalDetailResult.WxCpApprovalDetail detail = result.getInfo(); System.out.println("Approval Status: " + detail.getSpStatus()); System.out.println("Approval Name: " + detail.getSpName()); ``` -------------------------------- ### WxJava Transfer Service Initialization Source: https://github.com/binarywang/wxjava/blob/develop/docs/NEW_TRANSFER_API_SUPPORT.md Demonstrates how to obtain an instance of the TransferService, which is required for using the new merchant transfer API. ```APIDOC ## WxJava Transfer Service Initialization ### Description This snippet shows how to get the `TransferService` instance from `WxPayService`. This service is essential for interacting with the new WeChat Pay merchant transfer API. ### Method Java Code ### Endpoint N/A ### Parameters N/A ### Request Example ```java // Get WxPayService instance WxPayService wxPayService = new WxPayServiceImpl(); wxPayService.setConfig(config); // Get the new transfer service - this is the service new merchants must use! TransferService transferService = wxPayService.getTransferService(); ``` ### Response N/A ``` -------------------------------- ### Get User Basic Information Source: https://github.com/binarywang/wxjava/wiki/MP_OAuth2网页授权 Retrieve basic user information using the obtained access token. ```java WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null); ``` -------------------------------- ### Configure wx-java-miniapp-solon-plugin Source: https://github.com/binarywang/wxjava/blob/develop/solon-plugins/wx-java-miniapp-solon-plugin/README.md Configure your WeChat Mini Program settings in app.properties. This includes essential public account details and optional storage and HTTP client configurations. ```properties # 公众号配置(必填) wx.miniapp.appid = appId wx.miniapp.secret = @secret wx.miniapp.token = @token wx.miniapp.aesKey = @aesKey wx.miniapp.msgDataFormat = @msgDataFormat # 消息格式,XML或者JSON. # 存储配置redis(可选) # 注意: 指定redis.host值后不会使用容器注入的redis连接(JedisPool) wx.miniapp.config-storage.type = Jedis # 配置类型: Memory(默认), Jedis, RedisTemplate wx.miniapp.config-storage.key-prefix = wa # 相关redis前缀配置: wa(默认) wx.miniapp.config-storage.redis.host = 127.0.0.1 wx.miniapp.config-storage.redis.port = 6379 # http客户端配置 wx.miniapp.config-storage.http-client-type=HttpClient # http客户端类型: HttpClient(默认), OkHttp, JoddHttp wx.miniapp.config-storage.http-proxy-host= wx.miniapp.config-storage.http-proxy-port= wx.miniapp.config-storage.http-proxy-username= wx.miniapp.config-storage.http-proxy-password= ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-miniapp-spring-boot-starter/README.md Include this dependency in your project's pom.xml to use the wx-java-miniapp-spring-boot-starter. ```xml com.github.binarywang wx-java-miniapp-spring-boot-starter ${version} ``` -------------------------------- ### Get Custom Menu Source: https://github.com/binarywang/wxjava/wiki/CP_自定义菜单管理 Use this to retrieve the current custom menu configuration. Returns a WxMenu object. ```java WxMenu wxMenu = wxCpService.menuGet() ``` -------------------------------- ### 获取新版转账服务实例 Source: https://github.com/binarywang/wxjava/blob/develop/docs/NEW_TRANSFER_API_USAGE.md 演示如何通过WxPayService实例获取新版转账服务TransferService。需要先配置WxPayService。 ```java // 获取WxPayService实例 WxPayService wxPayService = new WxPayServiceImpl(); wxPayService.setConfig(config); // 获取新版转账服务 TransferService transferService = wxPayService.getTransferService(); ``` -------------------------------- ### Get Material Count Source: https://github.com/binarywang/wxjava/wiki/MP_永久素材管理 Fetches the total count of each type of permanent material (voice, video, image, news). ```json { "voice_count":1, "video_count":1, "image_count":1, "news_count":1 } ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/binarywang/wxjava/blob/develop/spring-boot-starters/wx-java-mp-spring-boot-starter/README.md Include the starter dependency in your pom.xml file. ```xml com.github.binarywang wx-java-mp-spring-boot-starter ${version} ``` -------------------------------- ### Get Custom Menu Configuration with WxJava Source: https://github.com/binarywang/wxjava/wiki/MP_自定义菜单管理 Retrieve the current custom menu configuration using the `menuGet` method. ```java WxMenu wxMenu = wxMpService.getMenuService().menuGet(); ``` -------------------------------- ### Configure wx-java-open-solon-plugin Properties Source: https://github.com/binarywang/wxjava/blob/develop/solon-plugins/wx-java-open-solon-plugin/README.md Configure the plugin by adding these properties to your app.properties file. This includes essential details like appId, secret, token, and aesKey, as well as optional settings for storage and HTTP client configurations. ```properties # 公众号配置(必填) wx.open.appId = appId wx.open.secret = @secret wx.open.token = @token wx.open.aesKey = @aesKey # 存储配置redis(可选) # 优先注入容器的(JedisPool, RedissonClient), 当配置了wx.open.config-storage.redis.host, 不会使用容器注入redis连接配置 wx.open.config-storage.type = redis # 配置类型: memory(默认), redis(jedis), jedis, redisson, redistemplate wx.open.config-storage.key-prefix = wx # 相关redis前缀配置: wx(默认) wx.open.config-storage.redis.host = 127.0.0.1 wx.open.config-storage.redis.port = 6379 # http客户端配置 wx.open.config-storage.http-client-type=httpclient # http客户端类型: httpclient(默认) wx.open.config-storage.http-proxy-host= wx.open.config-storage.http-proxy-port= wx.open.config-storage.http-proxy-username= wx.open.config-storage.http-proxy-password= # 最大重试次数,默认:5 次,如果小于 0,则为 0 wx.open.config-storage.max-retry-times=5 # 重试时间间隔步进,默认:1000 毫秒,如果小于 0,则为 1000 wx.open.config-storage.retry-sleep-millis=1000 ``` -------------------------------- ### Create WxCpUser Source: https://github.com/binarywang/wxjava/wiki/CP_用户管理 Use this to create a new user in the enterprise. Ensure all required fields are populated. ```java WxCpUser user = new WxCpUser(); user.setUserId("demo.user"); user.setName("demo.user"); user.setDepartIds(new Integer[] { 9, 8 }); user.setEmail("demo.user@ddd.com"); user.setGender("女"); user.setMobile("87350908979"); user.setPosition("demo.user"); user.setTel("3300393"); user.addExtAttr("爱好", "旅游"); wxCpService.getUserService().create(user); ```