以下为JAVA商城多端(小程序/APP/公众号)多商户+社交电商核心功能代码片段,涵盖商户管理、社交裂变、分账支付等模块:

1. 多商户入驻模块(Spring Boot后端)


java

// 商户入驻控制器
@RestController
@RequestMapping("/api/merchant")
public class MerchantController {
    
    @PostMapping("/register")
    public ResponseEntity<MerchantResponse> register(@RequestBody MerchantRegisterRequest request) {
        Merchant merchant = new Merchant();
        merchant.setName(request.getName());
        merchant.setPhone(request.getPhone());
        merchant.setStatus(MerchantStatus.PENDING);
        merchant.setCreateTime(new Date());
        
        // 保存商户信息
        Merchant saved = merchantService.save(merchant);
        
        // 触发审核流程
        rabbitTemplate.convertAndSend("audit_queue", new MerchantAuditEvent(saved.getId()));
        
        return ResponseEntity.ok(new MerchantResponse(saved));
    }
    
    @PutMapping("/{id}/approve")
    public ResponseEntity<Void> approve(@PathVariable Long id) {
        merchantService.approve(id);
        // 分配初始店铺ID
        storeService.createInitialStore(id);
        return ResponseEntity.ok().build();
    }
}

// 商户实体类
@Entity
public class Merchant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String phone;
    private String businessLicense; // 营业执照号
    @Enumerated(EnumType.STRING)
    private MerchantStatus status;
    @OneToMany(mappedBy = "merchant")
    private List<Store> stores;
}

2. 社交电商分销模块(Uniapp前端)


vue

<!-- 商品详情页分销组件 pages/product/detail.vue -->
<template>
  <view class="distribution">
    <view class="share-card" @click="shareToWechat">
      <image src="/static/share-icon.png"></image>
      <text>分享赚¥{{commissionAmount}}</text>
    </view>
    
    <!-- 分销关系链展示 -->
    <view class="relation-chain">
      <text>分销路径:</text>
      <view v-for="(user,idx) in distributionChain" :key="idx" class="user-node">
        {{user.nickname}} ({{user.level}}级)
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      commissionAmount: 5.8, // 分销佣金
      distributionChain: [] // 分销关系链
    }
  },
  methods: {
    shareToWechat() {
      // 生成带参数的分享链接
      const shareUrl = `https://mall.com/product/${this.product.id}?distributor=${this.userId}`;
      
      // 调用微信分享API
      uni.share({
        provider: 'weixin',
        type: 0,
        title: '发现好货',
        summary: this.product.name,
        imageUrl: this.product.cover,
        href: shareUrl,
        success: () => {
          uni.showToast({ title: '分享成功' });
        }
      });
    }
  },
  onLoad() {
    // 获取分销关系链
    this.distributionChain = uni.getStorageSync('distributionChain') || [];
  }
}
</script>

3. 拼团功能模块(Spring Boot服务层)


java

@Service
public class GroupBuyService {
    
    // 创建拼团
    public GroupBuy createGroup(Long productId, Long userId, int groupSize) {
        GroupBuy group = new GroupBuy();
        group.setProductId(productId);
        group.setInitiatorId(userId);
        group.setGroupSize(groupSize);
        group.setExpireTime(new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000)); // 2小时过期
        group.setStatus(GroupBuyStatus.ONGOING);
        
        // 保存拼团主信息
        GroupBuy saved = groupBuyRepository.save(group);
        
        // 创建团长参团记录
        GroupMember initiator = new GroupMember();
        initiator.setGroupId(saved.getId());
        initiator.setUserId(userId);
        initiator.setRole(GroupRole.INITIATOR);
        groupMemberRepository.save(initiator);
        
        return saved;
    }
    
    // 用户加入拼团
    public boolean joinGroup(Long groupId, Long userId) {
        GroupBuy group = groupBuyRepository.findById(groupId)
            .orElseThrow(() -> new GroupNotFoundException(groupId));
        
        if(group.getStatus() != GroupBuyStatus.ONGOING) {
            throw new GroupExpiredException("拼团已结束");
        }
        
        // 检查是否满员
        long memberCount = groupMemberRepository.countByGroupId(groupId);
        if(memberCount >= group.getGroupSize()) {
            group.setStatus(GroupBuyStatus.SUCCESS);
            groupBuyRepository.save(group);
            // 触发成团奖励发放
            rewardService.issueGroupReward(group);
        }
        
        // 保存参团记录
        GroupMember member = new GroupMember();
        member.setGroupId(groupId);
        member.setUserId(userId);
        member.setRole(GroupRole.MEMBER);
        groupMemberRepository.save(member);
        
        return true;
    }
}

4. 支付分账模块(微信支付回调处理)


java

@RestController
@RequestMapping("/api/pay")
public class PaymentController {
    
    @PostMapping("/notify")
    public String handlePaymentNotify(@RequestBody Map<String, String> notifyData) {
        // 解析微信支付回调
        String orderId = notifyData.get("out_trade_no");
        String totalAmount = notifyData.get("total_fee");
        
        // 更新订单状态
        Order order = orderRepository.findByOrderId(orderId);
        order.setStatus(OrderStatus.PAID);
        orderRepository.save(order);
        
        // 执行分账
        List<ProfitSharingRecipient> recipients = new ArrayList<>();
        // 平台抽成10%
        recipients.add(new ProfitSharingRecipient("PLATFORM", 10));
        // 商户分账90%
        Merchant merchant = merchantRepository.findByStoreId(order.getStoreId());
        recipients.add(new ProfitSharingRecipient(merchant.getAccountId(), 90));
        
        // 调用微信分账接口
        Map<String, String> profitSharingResult = wechatPayService.profitSharing(
            orderId, 
            totalAmount, 
            recipients
        );
        
        return profitSharingResult.get("return_code");
    }
}

5. 社交关系链存储(Uniapp前端)


javascript

// 用户关系处理工具类
export const handleUserRelation = (inviterId) => {
  if(!inviterId) return;
  
  // 存储分销关系链
  let relationChain = uni.getStorageSync('distributionChain') || [];
  
  // 添加当前用户到关系链
  const currentUser = {
    id: uni.getStorageSync('userId'),
    nickname: uni.getStorageSync('nickname'),
    level: relationChain.length + 1
  };
  
  // 添加到关系链
  relationChain.push(currentUser);
  
  // 保存更新后的关系链
  uni.setStorageSync('distributionChain', relationChain);
  
  // 上传关系链到后端
  uni.request({
    url: 'http://java-backend/api/relation/upload',
    method: 'POST',
    data: {
      inviterId: inviterId,
      chain: relationChain
    }
  });
};

技术亮点说明:

  1. 多商户架构:商户入驻审核流程、独立店铺管理、商品库存隔离
  2. 社交裂变:三级分销体系、拼团成团算法、分享链路追踪
  3. 支付分账:微信支付分账接口集成、平台与商户资金自动结算
  4. 多端适配:Uniapp实现小程序/APP/H5三端统一开发
  5. 数据隔离:不同商户数据通过store_id/merchant_id隔离存储
  6. 关系链管理:分销路径追踪、用户等级计算、佣金自动结算

该代码片段展示了多商户社交电商的核心功能实现,实际项目需补充商户后台管理、分销等级配置、拼团状态监控等模块,并完善支付安全验证与异常处理机制。

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐