---
url: "https://pay.weixin.qq.com/doc/v3/merchant/4012534633-java.md"
title: "创建代金券批次-请求示例-java"
doc_id: 4012534633
example_lang: "java"
---

## Java


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

```
package com.java.demo;

import com.java.utils.WXPayUtility; // 引用微信支付工具库，参考：https://pay.weixin.qq.com/doc/v3/merchant/4014931831

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 CreateCouponStock {
  private static String HOST = "https://api.mch.weixin.qq.com";
  private static String METHOD = "POST";
  private static String PATH = "/v3/marketing/favor/coupon-stocks";

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

    CreateCouponStockRequest request = new CreateCouponStockRequest();
    request.stockName = "微信支付代金券批次";
    request.comment = "零售批次";
    request.belongMerchant = "98568865";
    request.availableBeginTime = "2015-05-20T13:29:35.120+08:00";
    request.availableEndTime = "2015-05-20T13:29:35.120+08:00";
    request.stockUseRule = new StockRule();
    request.stockUseRule.maxCoupons = 100L;
    request.stockUseRule.maxAmount = 5000L;
    request.stockUseRule.maxAmountByDay = 400L;
    request.stockUseRule.maxCouponsPerUser = 3L;
    request.stockUseRule.naturalPersonLimit = false;
    request.stockUseRule.preventApiAbuse = false;
    request.patternInfo = new PatternInfo();
    request.patternInfo.description = "微信支付营销代金券";
    request.patternInfo.merchantLogo = "CDN地址";
    request.patternInfo.merchantName = "微信支付";
    request.patternInfo.backgroundColor = BackgroundColor.COLOR010;
    request.patternInfo.couponImage = "https://qpic.cn/xxx";
    request.patternInfo.jumpTarget = JumpTarget.PAYMENT_CODE;
    request.patternInfo.miniProgramAppid = "wx23232232323";
    request.patternInfo.miniProgramPath = "/path/index/index";
    request.couponUseRule = new CouponRule();
    request.couponUseRule.couponAvailableTime = new FavorAvailableTime();
    request.couponUseRule.couponAvailableTime.fixAvailableTime = new FixedAvailableTime();
    request.couponUseRule.couponAvailableTime.fixAvailableTime.availableWeekDay = new ArrayList<>();
    {
      request.couponUseRule.couponAvailableTime.fixAvailableTime.availableWeekDay.add(1L);
    };
    request.couponUseRule.couponAvailableTime.fixAvailableTime.beginTime = 0L;
    request.couponUseRule.couponAvailableTime.fixAvailableTime.endTime = 3600L;
    request.couponUseRule.couponAvailableTime.secondDayAvailable = false;
    request.couponUseRule.couponAvailableTime.availableTimeAfterReceive = 7L;
    request.couponUseRule.fixedNormalCoupon = new FixedValueStockMsg();
    request.couponUseRule.fixedNormalCoupon.couponAmount = 100L;
    request.couponUseRule.fixedNormalCoupon.transactionMinimum = 100L;
    request.couponUseRule.goodsTag = new ArrayList<>();
    {
      request.couponUseRule.goodsTag.add("123321");
    };
    request.couponUseRule.tradeType = new ArrayList<>();
    {
      request.couponUseRule.tradeType.add(TradeType.MICROAPP);
    };
    request.couponUseRule.combineUse = false;
    request.couponUseRule.availableItems = new ArrayList<>();
    {
      request.couponUseRule.availableItems.add("123321");
    };
    request.couponUseRule.unavailableItems = new ArrayList<>();
    {
      request.couponUseRule.unavailableItems.add("789987");
    };
    request.couponUseRule.availableMerchants = new ArrayList<>();
    {
      request.couponUseRule.availableMerchants.add("9856000");
    };
    request.couponUseRule.limitCard = new CardLimitation();
    request.couponUseRule.limitCard.name = "精粹白金";
    request.couponUseRule.limitCard.bin = new ArrayList<>();
    {
      request.couponUseRule.limitCard.bin.add("62542688");
    };
    request.noCash = false;
    request.stockType = "NORMAL";
    request.outRequestNo = "example_out_request_no";
    request.extInfo = "{'exinfo1':'1234','exinfo2':'3456'}";
    try {
      CreateCouponStockResponse response = client.run(request);
        // TODO: 请求成功，继续业务逻辑
        System.out.println(response);
    } catch (WXPayUtility.ApiException e) {
        // TODO: 请求失败，根据状态码执行不同的逻辑
        e.printStackTrace();
    }
  }

  public CreateCouponStockResponse run(CreateCouponStockRequest request) {
    String uri = PATH;
    String reqBody = WXPayUtility.toJson(request);

    Request.Builder reqBuilder = new Request.Builder().url(HOST + uri);
    reqBuilder.addHeader("Accept", "application/json");
    reqBuilder.addHeader("Wechatpay-Serial", wechatPayPublicKeyId);
    reqBuilder.addHeader("Authorization", WXPayUtility.buildAuthorization(mchid, 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 = WXPayUtility.extractBody(httpResponse);
      if (httpResponse.code() >= 200 && httpResponse.code() < 300) {
        // 2XX 成功，验证应答签名
        WXPayUtility.validateResponse(this.wechatPayPublicKeyId, this.wechatPayPublicKey,
            httpResponse.headers(), respBody);

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

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

  public CreateCouponStock(String mchid, String certificateSerialNo, String privateKeyFilePath, String wechatPayPublicKeyId, String wechatPayPublicKeyFilePath) {
    this.mchid = mchid;
    this.certificateSerialNo = certificateSerialNo;
    this.privateKey = WXPayUtility.loadPrivateKeyFromPath(privateKeyFilePath);
    this.wechatPayPublicKeyId = wechatPayPublicKeyId;
    this.wechatPayPublicKey = WXPayUtility.loadPublicKeyFromPath(wechatPayPublicKeyFilePath);
  }

  public static class CreateCouponStockRequest {
    @SerializedName("stock_name")
    public String stockName;

    @SerializedName("comment")
    public String comment;

    @SerializedName("belong_merchant")
    public String belongMerchant;

    @SerializedName("available_begin_time")
    public String availableBeginTime;

    @SerializedName("available_end_time")
    public String availableEndTime;

    @SerializedName("stock_use_rule")
    public StockRule stockUseRule;

    @SerializedName("pattern_info")
    public PatternInfo patternInfo;

    @SerializedName("coupon_use_rule")
    public CouponRule couponUseRule;

    @SerializedName("no_cash")
    public Boolean noCash;

    @SerializedName("stock_type")
    public String stockType;

    @SerializedName("out_request_no")
    public String outRequestNo;

    @SerializedName("ext_info")
    public String extInfo;
  }

  public static class CreateCouponStockResponse {
    @SerializedName("stock_id")
    public String stockId;

    @SerializedName("create_time")
    public String createTime;
  }

  public static class StockRule {
    @SerializedName("max_coupons")
    public Long maxCoupons;

    @SerializedName("max_amount")
    public Long maxAmount;

    @SerializedName("max_amount_by_day")
    public Long maxAmountByDay;

    @SerializedName("max_coupons_per_user")
    public Long maxCouponsPerUser;

    @SerializedName("natural_person_limit")
    public Boolean naturalPersonLimit;

    @SerializedName("prevent_api_abuse")
    public Boolean preventApiAbuse;
  }

  public static class PatternInfo {
    @SerializedName("description")
    public String description;

    @SerializedName("merchant_logo")
    public String merchantLogo;

    @SerializedName("merchant_name")
    public String merchantName;

    @SerializedName("background_color")
    public BackgroundColor backgroundColor;

    @SerializedName("coupon_image")
    public String couponImage;

    @SerializedName("jump_target")
    public JumpTarget jumpTarget;

    @SerializedName("mini_program_appid")
    public String miniProgramAppid;

    @SerializedName("mini_program_path")
    public String miniProgramPath;
  }

  public static class CouponRule {
    @SerializedName("coupon_available_time")
    public FavorAvailableTime couponAvailableTime;

    @SerializedName("fixed_normal_coupon")
    public FixedValueStockMsg fixedNormalCoupon;

    @SerializedName("goods_tag")
    public List<String> goodsTag;

    @SerializedName("trade_type")
    public List<TradeType> tradeType;

    @SerializedName("combine_use")
    public Boolean combineUse;

    @SerializedName("available_items")
    public List<String> availableItems;

    @SerializedName("unavailable_items")
    public List<String> unavailableItems;

    @SerializedName("available_merchants")
    public List<String> availableMerchants = new ArrayList<String>();

    @SerializedName("limit_card")
    public CardLimitation limitCard;
  }

  public enum BackgroundColor {
    @SerializedName("COLOR010")
    COLOR010,
    @SerializedName("COLOR020")
    COLOR020,
    @SerializedName("COLOR030")
    COLOR030,
    @SerializedName("COLOR040")
    COLOR040,
    @SerializedName("COLOR050")
    COLOR050,
    @SerializedName("COLOR060")
    COLOR060,
    @SerializedName("COLOR070")
    COLOR070,
    @SerializedName("COLOR080")
    COLOR080,
    @SerializedName("COLOR081")
    COLOR081,
    @SerializedName("COLOR082")
    COLOR082,
    @SerializedName("COLOR090")
    COLOR090,
    @SerializedName("COLOR100")
    COLOR100,
    @SerializedName("COLOR101")
    COLOR101,
    @SerializedName("COLOR102")
    COLOR102
  }

  public enum JumpTarget {
    @SerializedName("PAYMENT_CODE")
    PAYMENT_CODE,
    @SerializedName("MINI_PROGRAM")
    MINI_PROGRAM,
    @SerializedName("DEFAULT_PAGE")
    DEFAULT_PAGE
  }

  public static class FavorAvailableTime {
    @SerializedName("fix_available_time")
    public FixedAvailableTime fixAvailableTime;

    @SerializedName("second_day_available")
    public Boolean secondDayAvailable;

    @SerializedName("available_time_after_receive")
    public Long availableTimeAfterReceive;
  }

  public static class FixedValueStockMsg {
    @SerializedName("coupon_amount")
    public Long couponAmount;

    @SerializedName("transaction_minimum")
    public Long transactionMinimum;
  }

  public enum TradeType {
    @SerializedName("MICROAPP")
    MICROAPP,
    @SerializedName("APPPAY")
    APPPAY,
    @SerializedName("PPAY")
    PPAY,
    @SerializedName("CARD")
    CARD,
    @SerializedName("FACE")
    FACE,
    @SerializedName("OTHER")
    OTHER
  }

  public static class CardLimitation {
    @SerializedName("name")
    public String name;

    @SerializedName("bin")
    public List<String> bin = new ArrayList<String>();
  }

  public static class FixedAvailableTime {
    @SerializedName("available_week_day")
    public List<Long> availableWeekDay = new ArrayList<Long>();

    @SerializedName("begin_time")
    public Long beginTime;

    @SerializedName("end_time")
    public Long endTime;
  }

}

```
