---
url: "https://pay.weixin.qq.com/doc/brand/4018381114-java.md"
title: "创建投放计划-请求示例-java"
doc_id: 4018381114
example_lang: "java"
---

## Java


需配合微信支付工具库 WXPayUtility 使用，请参考 [Java](https://pay.weixin.qq.com/doc/brand/4015826861.md)

```
package com.java.demo;

import com.java.utils.WXPayBrandUtility; // 引用微信支付工具库，参考：https://pay.weixin.qq.com/doc/brand/4015826861

import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建投放计划
 */
public class CreateDeliveryPlan {
  private static String HOST = "https://api.mch.weixin.qq.com";
  private static String METHOD = "POST";
  private static String PATH = "/brand/marketing/delivery-plan/delivery-plans";

  public static void main(String[] args) {
    // TODO: 请准备商户开发必要参数，参考：https://pay.weixin.qq.com/doc/brand/4015415289
    CreateDeliveryPlan client = new CreateDeliveryPlan(
      "xxxxxxxx",                    // 品牌ID，是由微信支付系统生成并分配给每个品牌方的唯一标识符，品牌ID获取方式参考 https://pay.weixin.qq.com/doc/brand/4015415289
      "1DDE55AD98Exxxxxxxxxx",         // 品牌API证书序列号，如何获取请参考 https://pay.weixin.qq.com/doc/brand/4015407570
      "/path/to/apiclient_key.pem",     // 品牌API证书私钥文件路径，本地文件路径
      "PUB_KEY_ID_xxxxxxxxxxxxx",      // 微信支付公钥ID，如何获取请参考 https://pay.weixin.qq.com/doc/brand/4015453439
      "/path/to/wxp_pub.pem"           // 微信支付公钥文件路径，本地文件路径
    );

    CreateDeliveryPlanRequest request = new CreateDeliveryPlanRequest();
    request.outRequestNo = "asdf-1234-40016";
    request.productCouponId = "701146876221757924829193824428";
    request.stockId = "701246876221757924829194755312";
    request.reuseCouponConfig = false;
    request.planName = "冬季饮料投放";
    request.totalCount = 11000L;
    request.userLimit = 1L;
    request.dailyLimit = 1L;
    request.deliveryStartTime = "2025-01-01T00:00:00+08:00";
    request.deliveryEndTime = "2025-01-01T00:00:00+08:00";
    request.recommendWord = "天天有惊喜";
    request.usageMode = ProductUsageMode.SINGLE;
    request.stockBundleId = "123456789";
    request.saveAsDraft = false;
    try {
      CreateDeliveryPlanReponse response = client.run(request);
        // TODO: 请求成功，继续业务逻辑
        System.out.println(response);
    } catch (WXPayBrandUtility.ApiException e) {
        // TODO: 请求失败，根据状态码执行不同的逻辑
        e.printStackTrace();
    }
  }

  public CreateDeliveryPlanReponse run(CreateDeliveryPlanRequest request) {
    String uri = PATH;
    String reqBody = WXPayBrandUtility.toJson(request);

    Request.Builder reqBuilder = new Request.Builder().url(HOST + uri);
    reqBuilder.addHeader("Accept", "application/json");
    reqBuilder.addHeader("Wechatpay-Serial", wechatPayPublicKeyId);
    reqBuilder.addHeader("Authorization", WXPayBrandUtility.buildAuthorization(brand_id, certificateSerialNo,privateKey, METHOD, uri, reqBody));
    reqBuilder.addHeader("Content-Type", "application/json");
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), reqBody);
    reqBuilder.method(METHOD, requestBody);
    Request httpRequest = reqBuilder.build();

    // 发送HTTP请求
    OkHttpClient client = new OkHttpClient.Builder().build();
    try (Response httpResponse = client.newCall(httpRequest).execute()) {
      String respBody = WXPayBrandUtility.extractBody(httpResponse);
      if (httpResponse.code() >= 200 && httpResponse.code() < 300) {
        // 2XX 成功，验证应答签名
        WXPayBrandUtility.validateResponse(this.wechatPayPublicKeyId, this.wechatPayPublicKey,
            httpResponse.headers(), respBody);

        // 从HTTP应答报文构建返回数据
        return WXPayBrandUtility.fromJson(respBody, CreateDeliveryPlanReponse.class);
      } else {
        throw new WXPayBrandUtility.ApiException(httpResponse.code(), respBody, httpResponse.headers());
      }
    } catch (IOException e) {
      throw new UncheckedIOException("Sending request to " + uri + " failed.", e);
    }
  }

  private final String brand_id;
  private final String certificateSerialNo;
  private final PrivateKey privateKey;
  private final String wechatPayPublicKeyId;
  private final PublicKey wechatPayPublicKey;

  public CreateDeliveryPlan(String brand_id, String certificateSerialNo, String privateKeyFilePath, String wechatPayPublicKeyId, String wechatPayPublicKeyFilePath) {
    this.brand_id = brand_id;
    this.certificateSerialNo = certificateSerialNo;
    this.privateKey = WXPayBrandUtility.loadPrivateKeyFromPath(privateKeyFilePath);
    this.wechatPayPublicKeyId = wechatPayPublicKeyId;
    this.wechatPayPublicKey = WXPayBrandUtility.loadPublicKeyFromPath(wechatPayPublicKeyFilePath);
  }

  public static class CreateDeliveryPlanRequest {
    @SerializedName("out_request_no")
    public String outRequestNo;

    @SerializedName("product_coupon_id")
    public String productCouponId;

    @SerializedName("stock_id")
    public String stockId;

    @SerializedName("reuse_coupon_config")
    public Boolean reuseCouponConfig;

    @SerializedName("plan_name")
    public String planName;

    @SerializedName("total_count")
    public Long totalCount;

    @SerializedName("user_limit")
    public Long userLimit;

    @SerializedName("daily_limit")
    public Long dailyLimit;

    @SerializedName("delivery_start_time")
    public String deliveryStartTime;

    @SerializedName("delivery_end_time")
    public String deliveryEndTime;

    @SerializedName("recommend_word")
    public String recommendWord;

    @SerializedName("usage_mode")
    public ProductUsageMode usageMode;

    @SerializedName("stock_bundle_id")
    public String stockBundleId;

    @SerializedName("save_as_draft")
    public Boolean saveAsDraft;
  }

  public static class CreateDeliveryPlanReponse {
    @SerializedName("plan")
    public DeliveryPlan plan;
  }

  public enum ProductUsageMode {
    @SerializedName("SINGLE")
    SINGLE,
    @SerializedName("PROGRESSIVE_BUNDLE")
    PROGRESSIVE_BUNDLE
  }

  public static class DeliveryPlan {
    @SerializedName("plan_id")
    public String planId;

    @SerializedName("plan_name")
    public String planName;

    @SerializedName("plan_state")
    public PlanState planState;

    @SerializedName("delivery_start_time")
    public String deliveryStartTime;

    @SerializedName("delivery_end_time")
    public String deliveryEndTime;

    @SerializedName("product_coupon_id")
    public String productCouponId;

    @SerializedName("usage_mode")
    public ProductUsageMode usageMode;

    @SerializedName("stock_id")
    public String stockId;

    @SerializedName("stock_bundle_id")
    public String stockBundleId;

    @SerializedName("recommend_word")
    public String recommendWord;

    @SerializedName("total_count")
    public Long totalCount;

    @SerializedName("user_limit")
    public Long userLimit;

    @SerializedName("daily_limit")
    public Long dailyLimit;

    @SerializedName("reuse_coupon_config")
    public Boolean reuseCouponConfig;

    @SerializedName("brand_id")
    public String brandId;
  }

  public enum PlanState {
    @SerializedName("CREATED")
    CREATED,
    @SerializedName("TERMINATED")
    TERMINATED,
    @SerializedName("EXPIRED")
    EXPIRED,
    @SerializedName("DELIVERING")
    DELIVERING,
    @SerializedName("PAUSED")
    PAUSED
  }

}

```
