找回密码
 立即注册
首页 业界区 业界 Java 实现微信小程序不同人员生成不同小程序码并追踪扫 ...

Java 实现微信小程序不同人员生成不同小程序码并追踪扫码来源

边书仪 3 天前
Java后台实现微信小程序不同人员生成不同小程序码并追踪扫码来源

下面我将详细介绍如何使用Java后台实现这一功能。
一、整体架构设计


  • 前端:微信小程序
  • 后端:Java (Spring Boot)
  • 数据库:MySQL/其他
  • 微信接口:调用微信小程序码生成API
二、数据库设计

1. 推广人员表(promoter)
  1. CREATE TABLE `promoter` (
  2.   `id` bigint NOT NULL AUTO_INCREMENT,
  3.   `name` varchar(50) NOT NULL COMMENT '推广人员姓名',
  4.   `mobile` varchar(20) COMMENT '联系电话',
  5.   `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  6.   PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
复制代码
2. 用户-推广关系表(user_promoter_relation)
  1. CREATE TABLE `user_promoter_relation` (
  2.   `id` bigint NOT NULL AUTO_INCREMENT,
  3.   `user_id` varchar(64) NOT NULL COMMENT '小程序用户openid',
  4.   `promoter_id` bigint NOT NULL COMMENT '推广人员ID',
  5.   `first_scan_time` datetime NOT NULL COMMENT '首次扫码时间',
  6.   `last_scan_time` datetime NOT NULL COMMENT '最近扫码时间',
  7.   `scan_count` int NOT NULL DEFAULT '1' COMMENT '扫码次数',
  8.   PRIMARY KEY (`id`),
  9.   UNIQUE KEY `idx_user_promoter` (`user_id`,`promoter_id`),
  10.   KEY `idx_promoter` (`promoter_id`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
复制代码
三、Java后端实现

1. 添加微信小程序Java SDK依赖
  1. <dependency>
  2.     <groupId>com.github.binarywang</groupId>
  3.     weixin-java-miniapp</artifactId>
  4.     <version>4.1.0</version>
  5. </dependency>
复制代码
2. 配置微信小程序参数
  1. @Configuration
  2. public class WxMaConfiguration {
  3.    
  4.     @Value("${wx.miniapp.appid}")
  5.     private String appid;
  6.    
  7.     @Value("${wx.miniapp.secret}")
  8.     private String secret;
  9.    
  10.     @Bean
  11.     public WxMaService wxMaService() {
  12.         WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
  13.         config.setAppid(appid);
  14.         config.setSecret(secret);
  15.         
  16.         WxMaService service = new WxMaServiceImpl();
  17.         service.setWxMaConfig(config);
  18.         return service;
  19.     }
  20. }
复制代码
3. 生成带参数的小程序码
  1. @RestController
  2. @RequestMapping("/api/qrcode")
  3. public class QrCodeController {
  4.    
  5.     @Autowired
  6.     private WxMaService wxMaService;
  7.    
  8.     @Autowired
  9.     private PromoterService promoterService;
  10.    
  11.     /**
  12.      * 生成推广二维码
  13.      * @param promoterId 推广人员ID
  14.      * @return 二维码图片字节流
  15.      */
  16.     @GetMapping("/generate")
  17.     public void generatePromoterQrCode(@RequestParam Long promoterId,
  18.                                      HttpServletResponse response) throws IOException {
  19.         // 验证推广人员是否存在
  20.         Promoter promoter = promoterService.getById(promoterId);
  21.         if (promoter == null) {
  22.             throw new RuntimeException("推广人员不存在");
  23.         }
  24.         
  25.         // 生成小程序码
  26.         String scene = "promoterId=" + promoterId;
  27.         WxMaQrcodeService qrcodeService = wxMaService.getQrcodeService();
  28.         File qrCodeFile = qrcodeService.createWxaCodeUnlimit(scene, "pages/index/index", 430, true, null, false);
  29.         
  30.         // 返回图片流
  31.         response.setContentType("image/jpeg");
  32.         try (InputStream in = new FileInputStream(qrCodeFile);
  33.              OutputStream out = response.getOutputStream()) {
  34.             byte[] buffer = new byte[1024];
  35.             int len;
  36.             while ((len = in.read(buffer)) != -1) {
  37.                 out.write(buffer, 0, len);
  38.             }
  39.         }
  40.     }
  41. }
复制代码
4. 处理扫码进入事件
  1. @RestController
  2. @RequestMapping("/api/track")
  3. public class TrackController {
  4.    
  5.     @Autowired
  6.     private UserPromoterRelationService relationService;
  7.    
  8.     /**
  9.      * 记录用户扫码行为
  10.      * @param dto 包含用户信息和推广信息
  11.      * @return 操作结果
  12.      */
  13.     @PostMapping("/scan")
  14.     public Result trackScan(@RequestBody ScanTrackDTO dto) {
  15.         // 解析scene参数
  16.         String scene = dto.getScene();
  17.         Map<String, String> sceneParams = parseScene(scene);
  18.         String promoterIdStr = sceneParams.get("promoterId");
  19.         
  20.         if (StringUtils.isBlank(promoterIdStr)) {
  21.             return Result.fail("缺少推广人员参数");
  22.         }
  23.         
  24.         try {
  25.             Long promoterId = Long.parseLong(promoterIdStr);
  26.             relationService.recordUserScan(dto.getOpenid(), promoterId);
  27.             return Result.success();
  28.         } catch (NumberFormatException e) {
  29.             return Result.fail("推广人员参数格式错误");
  30.         }
  31.     }
  32.    
  33.     private Map<String, String> parseScene(String scene) {
  34.         Map<String, String> params = new HashMap<>();
  35.         if (StringUtils.isBlank(scene)) {
  36.             return params;
  37.         }
  38.         
  39.         String[] pairs = scene.split("&");
  40.         for (String pair : pairs) {
  41.             String[] kv = pair.split("=");
  42.             if (kv.length == 2) {
  43.                 params.put(kv[0], kv[1]);
  44.             }
  45.         }
  46.         return params;
  47.     }
  48. }
复制代码
5. 用户-推广关系服务
  1. @Service
  2. public class UserPromoterRelationServiceImpl implements UserPromoterRelationService {
  3.    
  4.     @Autowired
  5.     private UserPromoterRelationMapper relationMapper;
  6.    
  7.     @Override
  8.     @Transactional
  9.     public void recordUserScan(String openid, Long promoterId) {
  10.         // 查询是否已有记录
  11.         UserPromoterRelation relation = relationMapper.selectByUserAndPromoter(openid, promoterId);
  12.         
  13.         Date now = new Date();
  14.         if (relation == null) {
  15.             // 新建关系记录
  16.             relation = new UserPromoterRelation();
  17.             relation.setUserId(openid);
  18.             relation.setPromoterId(promoterId);
  19.             relation.setFirstScanTime(now);
  20.             relation.setLastScanTime(now);
  21.             relation.setScanCount(1);
  22.             relationMapper.insert(relation);
  23.         } else {
  24.             // 更新已有记录
  25.             relation.setLastScanTime(now);
  26.             relation.setScanCount(relation.getScanCount() + 1);
  27.             relationMapper.updateById(relation);
  28.         }
  29.     }
  30. }
复制代码
四、小程序前端处理

在小程序的app.js中处理扫码进入的场景:
  1. App({
  2.   onLaunch: function(options) {
  3.     // 处理扫码进入的情况
  4.     if (options.scene === 1047 || options.scene === 1048 || options.scene === 1049) {
  5.       // 这些scene值表示是通过扫码进入
  6.       const scene = decodeURIComponent(options.query.scene);
  7.       
  8.       // 上报扫码信息到后端
  9.       wx.request({
  10.         url: 'https://yourdomain.com/api/track/scan',
  11.         method: 'POST',
  12.         data: {
  13.           scene: scene,
  14.           openid: this.globalData.openid // 需要先获取用户openid
  15.         },
  16.         success: function(res) {
  17.           console.log('扫码记录成功', res);
  18.         }
  19.       });
  20.     }
  21.   }
  22. })
复制代码
五、数据统计接口实现
  1. @RestController
  2. @RequestMapping("/api/stat")
  3. public class StatController {
  4.    
  5.     @Autowired
  6.     private UserPromoterRelationMapper relationMapper;
  7.    
  8.     /**
  9.      * 获取推广人员业绩统计
  10.      * @param promoterId 推广人员ID
  11.      * @param startDate 开始日期
  12.      * @param endDate 结束日期
  13.      * @return 统计结果
  14.      */
  15.     @GetMapping("/promoter")
  16.     public Result getPromoterStats(@RequestParam Long promoterId,
  17.                                  @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") Date startDate,
  18.                                  @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") Date endDate) {
  19.         
  20.         // 构建查询条件
  21.         QueryWrapper<UserPromoterRelation> query = new QueryWrapper<>();
  22.         query.eq("promoter_id", promoterId);
  23.         
  24.         if (startDate != null) {
  25.             query.ge("first_scan_time", startDate);
  26.         }
  27.         if (endDate != null) {
  28.             query.le("first_scan_time", endDate);
  29.         }
  30.         
  31.         // 执行查询
  32.         int totalUsers = relationMapper.selectCount(query);
  33.         List<Map<String, Object>> dailyStats = relationMapper.selectDailyStatsByPromoter(promoterId, startDate, endDate);
  34.         
  35.         // 返回结果
  36.         Map<String, Object> result = new HashMap<>();
  37.         result.put("totalUsers", totalUsers);
  38.         result.put("dailyStats", dailyStats);
  39.         
  40.         return Result.success(result);
  41.     }
  42. }
复制代码
六、安全注意事项


  • 参数校验:所有传入的promoterId需要验证是否存在
  • 防刷机制:限制同一用户频繁上报扫码记录
  • HTTPS:确保所有接口使用HTTPS协议
  • 权限控制:推广数据统计接口需要添加权限验证
  • 日志记录:记录所有二维码生成和扫码行为
七、扩展功能建议


  • 二级分销:可以扩展支持多级推广关系
  • 奖励机制:根据扫码用户的活动情况给推广人员奖励
  • 实时通知:当有新用户扫码时,实时通知推广人员
  • 数据分析:提供更详细的数据分析报表
通过以上Java实现,你可以完整地构建一个支持不同人员生成不同小程序码并能追踪扫码来源的系统。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册