CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-github-binarywang--weixin-java-miniapp

Comprehensive Java SDK for WeChat MiniApp development with complete platform integration

Pending
Overview
Eval results
Files

cloud-development.mddocs/

Cloud Development

WeChat Cloud Development integration including cloud functions, database operations, cloud storage management, and serverless backend services for WeChat MiniApp applications.

Capabilities

Cloud Service Interface

Core cloud development operations for serverless backend functionality.

public interface WxMaCloudService {
    // Cloud Function Operations
    WxCloudInvokeResult invokeCloudFunction(String env, String functionName, String data) throws WxErrorException;
    WxCloudInvokeResult invokeCloudFunction(WxCloudInvokeRequest request) throws WxErrorException;
    
    // Database Operations
    WxCloudDatabaseResult databaseQuery(String env, String query) throws WxErrorException;
    WxCloudDatabaseResult databaseAdd(String env, String collection, String data) throws WxErrorException;
    WxCloudDatabaseResult databaseUpdate(String env, String collection, String query, String data) throws WxErrorException;
    WxCloudDatabaseResult databaseDelete(String env, String collection, String query) throws WxErrorException;
    WxCloudDatabaseResult databaseAggregate(String env, String collection, String pipeline) throws WxErrorException;
    WxCloudDatabaseResult databaseCount(String env, String collection, String query) throws WxErrorException;
    
    // File Operations
    WxCloudUploadFileResult uploadFile(String env, String path, InputStream inputStream) throws WxErrorException;
    WxCloudUploadFileResult uploadFile(WxCloudUploadFileRequest request) throws WxErrorException;
    WxCloudDownloadFileResult downloadFile(String env, String fileList) throws WxErrorException;
    WxCloudDeleteFileResult deleteFile(String env, List<String> fileIds) throws WxErrorException;
    
    // Storage Operations
    WxCloudGetTempFileUrlResult getTempFileUrl(String env, List<String> fileList) throws WxErrorException;
    WxCloudBatchDownloadFileResult batchDownloadFile(String env, List<String> fileList, Long zipName) throws WxErrorException;
}

Cloud Function Models

Data models for cloud function invocation and management.

public class WxCloudInvokeRequest implements Serializable {
    private String env;                 // Cloud environment ID
    private String functionName;        // Function name
    private String requestData;         // Function input data (JSON string)
    
    public WxCloudInvokeRequest();
    public WxCloudInvokeRequest(String env, String functionName, String requestData);
    
    // Getters and setters
    public String getEnv();
    public void setEnv(String env);
    public String getFunctionName();
    public void setFunctionName(String functionName);
    public String getRequestData();
    public void setRequestData(String requestData);
    
    // Convenience methods
    public WxCloudInvokeRequest withData(Object data);
    public String toJson();
}

public class WxCloudInvokeResult implements Serializable {
    private Integer errCode;            // Error code (0: success)
    private String errMsg;              // Error message
    private String requestId;           // Request ID for tracking
    private String respData;            // Function response data
    
    // Getters and setters
    public Integer getErrCode();
    public void setErrCode(Integer errCode);
    public String getErrMsg();
    public void setErrMsg(String errMsg);
    public String getRequestId();
    public void setRequestId(String requestId);
    public String getRespData();
    public void setRespData(String respData);
    
    // Convenience methods
    public boolean isSuccess();
    public <T> T getResponseData(Class<T> clazz);
    public JsonObject getResponseAsJson();
}

Cloud Database Models

Data models for database operations and queries.

public class WxCloudDatabaseRequest implements Serializable {
    private String env;                 // Cloud environment ID
    private String collection;          // Collection name
    private String query;               // Query conditions (JSON string)
    private String data;                // Data to insert/update (JSON string)
    private String pipeline;            // Aggregation pipeline (JSON string)
    private Integer limit;              // Query limit
    private Integer offset;             // Query offset
    
    // Getters and setters
    public String getEnv();
    public void setEnv(String env);
    public String getCollection();
    public void setCollection(String collection);
    public String getQuery();
    public void setQuery(String query);
    public String getData();
    public void setData(String data);
    
    // Builder methods
    public WxCloudDatabaseRequest withQuery(Object queryObj);
    public WxCloudDatabaseRequest withData(Object dataObj);
    public WxCloudDatabaseRequest withLimit(int limit);
    public WxCloudDatabaseRequest withOffset(int offset);
}

public class WxCloudDatabaseResult implements Serializable {
    private Integer errCode;            // Error code
    private String errMsg;              // Error message
    private List<JsonObject> data;      // Query results
    private Integer pager;              // Pagination info
    private Integer matched;            // Matched documents count
    private Integer modified;           // Modified documents count
    private Integer deleted;            // Deleted documents count
    private String id;                  // Inserted document ID
    
    // Getters and setters
    public Integer getErrCode();
    public void setErrCode(Integer errCode);
    public List<JsonObject> getData();
    public void setData(List<JsonObject> data);
    public Integer getMatched();
    public void setMatched(Integer matched);
    
    // Convenience methods
    public boolean isSuccess();
    public <T> List<T> getDataAs(Class<T> clazz);
    public <T> T getFirstData(Class<T> clazz);
}

Cloud Storage Models

Data models for file upload, download, and storage operations.

public class WxCloudUploadFileRequest implements Serializable {
    private String env;                 // Cloud environment ID
    private String path;                // File path in cloud storage
    private InputStream inputStream;    // File input stream
    private String fileName;            // Original file name
    
    public WxCloudUploadFileRequest();
    public WxCloudUploadFileRequest(String env, String path, InputStream inputStream);
    
    // Getters and setters
    public String getEnv();
    public void setEnv(String env);
    public String getPath();
    public void setPath(String path);
    public InputStream getInputStream();
    public void setInputStream(InputStream inputStream);
}

public class WxCloudUploadFileResult implements Serializable {
    private Integer errCode;            // Error code
    private String errMsg;              // Error message
    private String fileId;              // Uploaded file ID
    private String downloadUrl;         // Download URL
    
    // Getters and setters
    public Integer getErrCode();
    public void setErrCode(Integer errCode);
    public String getFileId();
    public void setFileId(String fileId);
    public String getDownloadUrl();
    public void setDownloadUrl(String downloadUrl);
    
    public boolean isSuccess();
}

public class WxCloudDownloadFileResult implements Serializable {
    private Integer errCode;            // Error code
    private String errMsg;              // Error message
    private List<FileInfo> fileList;    // Downloaded file information
    
    public static class FileInfo {
        private String fileId;          // File ID
        private String downloadUrl;     // Temporary download URL
        private Integer status;         // Download status
        
        public String getFileId();
        public void setFileId(String fileId);
        public String getDownloadUrl();
        public void setDownloadUrl(String downloadUrl);
        public Integer getStatus();
        public void setStatus(Integer status);
    }
    
    // Getters and setters
    public List<FileInfo> getFileList();
    public void setFileList(List<FileInfo> fileList);
    public boolean isSuccess();
}

Usage Examples

Cloud Function Integration

Invoke Cloud Functions

@Service
public class CloudFunctionService {
    
    @Autowired
    private WxMaService wxMaService;
    
    @Value("${wechat.cloud.env}")
    private String cloudEnv;
    
    public <T> T invokeFunction(String functionName, Object requestData, Class<T> responseType) {
        try {
            String jsonData = JsonUtils.toJson(requestData);
            
            WxCloudInvokeResult result = wxMaService.getCloudService()
                .invokeCloudFunction(cloudEnv, functionName, jsonData);
            
            if (result.isSuccess()) {
                return result.getResponseData(responseType);
            } else {
                throw new CloudFunctionException(
                    "Function invocation failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Cloud function {} invocation failed: {}", functionName, e.getMessage());
            throw new CloudFunctionException("Failed to invoke cloud function", e);
        }
    }
    
    public UserProfileResult getUserProfile(String userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("includePrivateData", false);
        
        return invokeFunction("getUserProfile", params, UserProfileResult.class);
    }
    
    public PaymentResult processPayment(PaymentRequest paymentRequest) {
        try {
            WxCloudInvokeRequest request = new WxCloudInvokeRequest()
                .setEnv(cloudEnv)
                .setFunctionName("processPayment")
                .withData(paymentRequest);
            
            WxCloudInvokeResult result = wxMaService.getCloudService()
                .invokeCloudFunction(request);
            
            if (result.isSuccess()) {
                return result.getResponseData(PaymentResult.class);
            } else {
                logger.error("Payment processing failed: {}", result.getErrMsg());
                throw new PaymentProcessingException(result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Payment cloud function failed: {}", e.getMessage());
            throw new PaymentProcessingException("Payment processing error", e);
        }
    }
    
    @Async
    public CompletableFuture<Void> sendAsyncNotification(NotificationRequest notification) {
        return CompletableFuture.runAsync(() -> {
            try {
                invokeFunction("sendNotification", notification, Void.class);
                logger.info("Async notification sent for user: {}", notification.getUserId());
                
            } catch (Exception e) {
                logger.error("Async notification failed: {}", e.getMessage());
            }
        });
    }
}

Cloud Database Operations

Database CRUD Operations

@Service
public class CloudDatabaseService {
    
    @Autowired
    private WxMaService wxMaService;
    
    @Value("${wechat.cloud.env}")
    private String cloudEnv;
    
    public <T> List<T> findDocuments(String collection, Object query, Class<T> entityType) {
        try {
            String queryJson = JsonUtils.toJson(query);
            
            WxCloudDatabaseResult result = wxMaService.getCloudService()
                .databaseQuery(cloudEnv, queryJson);
            
            if (result.isSuccess()) {
                return result.getDataAs(entityType);
            } else {
                throw new CloudDatabaseException("Query failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Database query failed for collection {}: {}", collection, e.getMessage());
            throw new CloudDatabaseException("Database query failed", e);
        }
    }
    
    public String createDocument(String collection, Object document) {
        try {
            String documentJson = JsonUtils.toJson(document);
            
            WxCloudDatabaseResult result = wxMaService.getCloudService()
                .databaseAdd(cloudEnv, collection, documentJson);
            
            if (result.isSuccess()) {
                return result.getId();
            } else {
                throw new CloudDatabaseException("Insert failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Document creation failed for collection {}: {}", collection, e.getMessage());
            throw new CloudDatabaseException("Document creation failed", e);
        }
    }
    
    public int updateDocuments(String collection, Object query, Object updateData) {
        try {
            String queryJson = JsonUtils.toJson(query);
            String updateJson = JsonUtils.toJson(updateData);
            
            WxCloudDatabaseResult result = wxMaService.getCloudService()
                .databaseUpdate(cloudEnv, collection, queryJson, updateJson);
            
            if (result.isSuccess()) {
                return result.getModified();
            } else {
                throw new CloudDatabaseException("Update failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Document update failed for collection {}: {}", collection, e.getMessage());
            throw new CloudDatabaseException("Document update failed", e);
        }
    }
    
    public int deleteDocuments(String collection, Object query) {
        try {
            String queryJson = JsonUtils.toJson(query);
            
            WxCloudDatabaseResult result = wxMaService.getCloudService()
                .databaseDelete(cloudEnv, collection, queryJson);
            
            if (result.isSuccess()) {
                return result.getDeleted();
            } else {
                throw new CloudDatabaseException("Delete failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Document deletion failed for collection {}: {}", collection, e.getMessage());
            throw new CloudDatabaseException("Document deletion failed", e);
        }
    }
}

Advanced Database Operations

@Repository
public class UserCloudRepository {
    
    @Autowired
    private CloudDatabaseService cloudDb;
    
    private static final String USER_COLLECTION = "users";
    
    public Optional<User> findByOpenid(String openid) {
        Map<String, Object> query = Map.of("openid", openid);
        
        List<User> users = cloudDb.findDocuments(USER_COLLECTION, query, User.class);
        return users.isEmpty() ? Optional.empty() : Optional.of(users.get(0));
    }
    
    public List<User> findActiveUsers() {
        Map<String, Object> query = Map.of(
            "status", "active",
            "lastLoginTime", Map.of(
                "$gte", System.currentTimeMillis() - (30L * 24 * 60 * 60 * 1000) // 30 days
            )
        );
        
        return cloudDb.findDocuments(USER_COLLECTION, query, User.class);
    }
    
    public String saveUser(User user) {
        user.setCreatedTime(System.currentTimeMillis());
        user.setUpdatedTime(System.currentTimeMillis());
        
        return cloudDb.createDocument(USER_COLLECTION, user);
    }
    
    public void updateUserLastLogin(String openid) {
        Map<String, Object> query = Map.of("openid", openid);
        Map<String, Object> update = Map.of(
            "lastLoginTime", System.currentTimeMillis(),
            "updatedTime", System.currentTimeMillis()
        );
        
        cloudDb.updateDocuments(USER_COLLECTION, query, update);
    }
    
    public long countUsersByCity(String city) {
        try {
            Map<String, Object> query = Map.of("city", city);
            String queryJson = JsonUtils.toJson(query);
            
            WxCloudDatabaseResult result = wxMaService.getCloudService()
                .databaseCount(cloudEnv, USER_COLLECTION, queryJson);
            
            if (result.isSuccess()) {
                return result.getMatched();
            }
            
        } catch (WxErrorException e) {
            logger.error("User count query failed: {}", e.getMessage());
        }
        
        return 0;
    }
    
    public List<UserAggregateResult> aggregateUsersByRegion() {
        try {
            List<Map<String, Object>> pipeline = Arrays.asList(
                Map.of("$group", Map.of(
                    "_id", "$province",
                    "count", Map.of("$sum", 1),
                    "avgAge", Map.of("$avg", "$age")
                )),
                Map.of("$sort", Map.of("count", -1))
            );
            
            String pipelineJson = JsonUtils.toJson(pipeline);
            
            WxCloudDatabaseResult result = wxMaService.getCloudService()
                .databaseAggregate(cloudEnv, USER_COLLECTION, pipelineJson);
            
            if (result.isSuccess()) {
                return result.getDataAs(UserAggregateResult.class);
            }
            
        } catch (WxErrorException e) {
            logger.error("User aggregation failed: {}", e.getMessage());
        }
        
        return Collections.emptyList();
    }
}

Cloud Storage Operations

File Upload and Management

@Service
public class CloudStorageService {
    
    @Autowired
    private WxMaService wxMaService;
    
    @Value("${wechat.cloud.env}")
    private String cloudEnv;
    
    public String uploadFile(MultipartFile file, String folder) {
        try {
            // Generate unique file path
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            String filePath = folder + "/" + fileName;
            
            WxCloudUploadFileRequest request = new WxCloudUploadFileRequest(
                cloudEnv, filePath, file.getInputStream()
            );
            request.setFileName(file.getOriginalFilename());
            
            WxCloudUploadFileResult result = wxMaService.getCloudService()
                .uploadFile(request);
            
            if (result.isSuccess()) {
                logger.info("File uploaded to cloud storage: {} -> {}", 
                           file.getOriginalFilename(), result.getFileId());
                return result.getFileId();
            } else {
                throw new CloudStorageException("Upload failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException | IOException e) {
            logger.error("Cloud file upload failed: {}", e.getMessage());
            throw new CloudStorageException("File upload failed", e);
        }
    }
    
    public String uploadUserAvatar(String openid, MultipartFile avatar) {
        String avatarFolder = "avatars/" + openid;
        return uploadFile(avatar, avatarFolder);
    }
    
    public String uploadProductImage(String productId, MultipartFile image) {
        String imageFolder = "products/" + productId;
        return uploadFile(image, imageFolder);
    }
    
    public List<String> getTempDownloadUrls(List<String> fileIds) {
        try {
            WxCloudGetTempFileUrlResult result = wxMaService.getCloudService()
                .getTempFileUrl(cloudEnv, fileIds);
            
            if (result.isSuccess()) {
                return result.getFileList().stream()
                    .map(WxCloudGetTempFileUrlResult.FileInfo::getTempFileUrl)
                    .collect(Collectors.toList());
            } else {
                throw new CloudStorageException("Get temp URLs failed: " + result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("Get temp file URLs failed: {}", e.getMessage());
            throw new CloudStorageException("Failed to get temporary URLs", e);
        }
    }
    
    public void deleteFiles(List<String> fileIds) {
        try {
            WxCloudDeleteFileResult result = wxMaService.getCloudService()
                .deleteFile(cloudEnv, fileIds);
            
            if (result.isSuccess()) {
                logger.info("Deleted {} files from cloud storage", fileIds.size());
            } else {
                logger.warn("Some files failed to delete: {}", result.getErrMsg());
            }
            
        } catch (WxErrorException e) {
            logger.error("File deletion failed: {}", e.getMessage());
        }
    }
    
    @Async
    public CompletableFuture<String> downloadAndProcessFile(String fileId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                WxCloudDownloadFileResult result = wxMaService.getCloudService()
                    .downloadFile(cloudEnv, List.of(fileId).toString());
                
                if (result.isSuccess() && !result.getFileList().isEmpty()) {
                    String downloadUrl = result.getFileList().get(0).getDownloadUrl();
                    
                    // Download and process the file
                    byte[] fileContent = downloadFileContent(downloadUrl);
                    
                    // Process file content (resize, convert, etc.)
                    byte[] processedContent = processFileContent(fileContent);
                    
                    // Upload processed file back to cloud storage
                    String processedFileId = uploadProcessedFile(processedContent);
                    
                    return processedFileId;
                }
                
            } catch (Exception e) {
                logger.error("Async file processing failed for {}: {}", fileId, e.getMessage());
            }
            
            return null;
        });
    }
}

Cloud-based User Management

@Service
public class CloudUserService {
    
    @Autowired
    private CloudFunctionService cloudFunctions;
    
    @Autowired
    private CloudDatabaseService cloudDatabase;
    
    @Autowired  
    private CloudStorageService cloudStorage;
    
    public UserProfile createUserProfile(UserRegistrationRequest request) {
        try {
            // Upload avatar to cloud storage
            String avatarFileId = null;
            if (request.getAvatar() != null) {
                avatarFileId = cloudStorage.uploadUserAvatar(
                    request.getOpenid(), request.getAvatar()
                );
            }
            
            // Create user document in cloud database
            User user = new User();
            user.setOpenid(request.getOpenid());
            user.setNickname(request.getNickname());
            user.setAvatarFileId(avatarFileId);
            user.setPhoneNumber(request.getPhoneNumber());
            user.setStatus("active");
            
            String userId = cloudDatabase.createDocument("users", user);
            user.setId(userId);
            
            // Initialize user data via cloud function
            Map<String, Object> initParams = Map.of(
                "userId", userId,
                "openid", request.getOpenid(),
                "initialData", request.getInitialData()
            );
            
            cloudFunctions.invokeFunction("initializeUser", initParams, Void.class);
            
            // Build user profile response
            UserProfile profile = new UserProfile();
            profile.setUser(user);
            
            if (avatarFileId != null) {
                List<String> avatarUrl = cloudStorage.getTempDownloadUrls(List.of(avatarFileId));
                if (!avatarUrl.isEmpty()) {
                    profile.setAvatarUrl(avatarUrl.get(0));
                }
            }
            
            logger.info("User profile created for: {}", request.getOpenid());
            return profile;
            
        } catch (Exception e) {
            logger.error("User profile creation failed: {}", e.getMessage());
            throw new UserProfileException("Failed to create user profile", e);
        }
    }
    
    public void updateUserActivity(String openid, UserActivity activity) {
        // Store activity in cloud database
        Map<String, Object> activityDoc = Map.of(
            "openid", openid,
            "type", activity.getType(),
            "data", activity.getData(),
            "timestamp", System.currentTimeMillis()
        );
        
        cloudDatabase.createDocument("user_activities", activityDoc);
        
        // Process activity asynchronously via cloud function
        Map<String, Object> processParams = Map.of(
            "openid", openid,
            "activity", activity
        );
        
        cloudFunctions.sendAsyncNotification(new NotificationRequest(
            "processUserActivity", processParams
        ));
    }
    
    public UserAnalytics getUserAnalytics(String openid, Date startDate, Date endDate) {
        // Use cloud function for complex analytics
        Map<String, Object> params = Map.of(
            "openid", openid,
            "startDate", startDate.getTime(),
            "endDate", endDate.getTime(),
            "includeActivities", true,
            "includePurchases", true
        );
        
        return cloudFunctions.invokeFunction("getUserAnalytics", params, UserAnalytics.class);
    }
}

Error Handling and Monitoring

@Component
public class CloudServiceMonitor {
    
    @EventListener
    public void handleCloudFunctionEvent(CloudFunctionInvokeEvent event) {
        // Log function invocation metrics
        logger.info("Cloud function {} invoked with duration: {}ms", 
                   event.getFunctionName(), event.getDuration());
        
        // Alert on function failures
        if (!event.isSuccess()) {
            alertService.sendCloudFunctionAlert(event);
        }
        
        // Track usage metrics
        metricsService.recordCloudFunctionUsage(event);
    }
    
    @EventListener
    public void handleDatabaseEvent(CloudDatabaseEvent event) {
        // Monitor database performance
        if (event.getDuration() > 5000) { // 5 seconds
            alertService.sendSlowDatabaseAlert(event);
        }
        
        // Track database operations
        metricsService.recordDatabaseOperation(event);
    }
    
    @Scheduled(fixedRate = 300000) // Every 5 minutes
    public void checkCloudResourceHealth() {
        try {
            // Test cloud function connectivity
            cloudFunctions.invokeFunction("healthCheck", Map.of(), Map.class);
            
            // Test database connectivity
            cloudDatabase.findDocuments("health_check", Map.of("type", "ping"), Map.class);
            
            logger.debug("Cloud resource health check passed");
            
        } catch (Exception e) {
            logger.error("Cloud resource health check failed: {}", e.getMessage());
            alertService.sendCloudHealthAlert(e);
        }
    }
}

This cloud development module provides comprehensive integration with WeChat Cloud Development services, enabling serverless backend functionality with cloud functions, database operations, and cloud storage for WeChat MiniApp applications.

Install with Tessl CLI

npx tessl i tessl/maven-com-github-binarywang--weixin-java-miniapp

docs

analytics.md

cloud-development.md

configuration.md

core-services.md

development-tools.md

ecommerce.md

index.md

live-streaming.md

logistics.md

media-content.md

messaging.md

qr-codes.md

user-management.md

tile.json