---
url: "https://pay.weixin.qq.com/doc/v3/partner/4015336981-java.md"
title: "根据OPENID导入用户会员卡-请求示例-java"
doc_id: 4015336981
example_lang: "java"
---

## Java


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

```
package com.java.demo;

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

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;

/**
 * 根据OpenID导入用户会员卡
 */
public class ImportUserCardByOpenId {
  private static String HOST = "https://api.mch.weixin.qq.com";
  private static String METHOD = "POST";
  private static String PATH = "/v3/brand/partner/card-member/user-cards/import-by-openid";

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

    ImportUserCardByOpenIdRequest request = new ImportUserCardByOpenIdRequest();
    request.brandId = "1004";
    request.cardId = "pbLatjvWOibDc5-TBnbUk1pD12o0";
    request.openid = "obLatjnx9gnqzS4myYGmLZ7LgLBA";
    request.userCardCode = "478515832665";
    request.phoneNumber = client.encrypt("phone_number");
    request.cardColor = "#FFFF00";
    request.cardPictureUrl = "https://wxpaylogo.qpic.cn/wxpaylogo/PiajxSqBRaEIPAeia7Imvtsn7sYGNcEj33YzVvJF88ECQ19LXId8ZL2Q/0";
    request.level = "钻石会员";
    request.userInformation = new UserInfo();
    request.userInformation.commonFieldList = new ArrayList<>();
    {
      UserInfoCommonField commonFieldListItem = new UserInfoCommonField();
      commonFieldListItem.name = CommonFieldFlag.USER_FORM_FLAG_BIRTHDAY;
      commonFieldListItem.value = client.encrypt("value");
      request.userInformation.commonFieldList.add(commonFieldListItem);
    };
    request.userInformation.customFieldList = new ArrayList<>();
    {
      UserInfoCustomField customFieldListItem = new UserInfoCustomField();
      customFieldListItem.name = "喜欢的运动";
      customFieldListItem.userChosenValues = new ArrayList<>();
      {
        customFieldListItem.userChosenValues.add("vvysDQeEaH3I+wRh14St0abIkvQyFgh/fbWYSs2bLtG9tj+bdJn4WSCPzLhShNHgujZzseiL6sYmT7E65mv/eFeTa7yslYfrX0hrhHazSM/+tfvN/C3OZwiBbcrF9LTIIdBVhGOqhCx0gK5YAVZc8dbW/yJqC5i79PDfVYJtpQe3A4v/GiDa2Q+Mv03taxgnEkzqlSPjkXiCYBj9UaFJ4bqCTXiO2Kt6TpczvAaZW+9/blxiJwqEFXe78LbrIQvkDUmVdZbqBdPQ+QGQgc/2Ea4IbP/EEt1qSyXnFbzaaKSE2j4mAFON3kzNexb/SYkHZNJAuCittaW4wpGj7U+h9A==");
      };
      request.userInformation.customFieldList.add(customFieldListItem);
    };
    request.validDateInformation = new DateInfo();
    request.validDateInformation.type = DateType.PERMANENT;
    request.validDateInformation.availableBeginTime = "2020-05-20T13:29:35.120+08:00";
    request.validDateInformation.availableEndTime = "2020-05-20T13:29:35.120+08:00";
    request.validDateInformation.availableDayAfterReceive = 30L;
    request.pickupTime = "2020-05-20T13:29:35.120+08:00";
    try {
      UserCard response = client.run(request);
        // TODO: 请求成功，继续业务逻辑
        System.out.println(response);
    } catch (WXPayUtility.ApiException e) {
        // TODO: 请求失败，根据状态码执行不同的逻辑
        e.printStackTrace();
    }
  }

  public UserCard run(ImportUserCardByOpenIdRequest 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, UserCard.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 ImportUserCardByOpenId(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 String encrypt(String plainText) {
    return WXPayUtility.encrypt(this.wechatPayPublicKey, plainText);
  }

  public static class ImportUserCardByOpenIdRequest {
    @SerializedName("brand_id")
    public String brandId;

    @SerializedName("card_id")
    public String cardId;

    @SerializedName("openid")
    public String openid;

    @SerializedName("user_card_code")
    public String userCardCode;

    @SerializedName("phone_number")
    public String phoneNumber;

    @SerializedName("card_color")
    public String cardColor;

    @SerializedName("card_picture_url")
    public String cardPictureUrl;

    @SerializedName("level")
    public String level;

    @SerializedName("user_information")
    public UserInfo userInformation;

    @SerializedName("valid_date_information")
    public DateInfo validDateInformation;

    @SerializedName("pickup_time")
    public String pickupTime;
  }

  public static class UserCard {
    @SerializedName("user_card_code")
    public String userCardCode;

    @SerializedName("card_id")
    public String cardId;

    @SerializedName("openid")
    public String openid;

    @SerializedName("card_color")
    public String cardColor;

    @SerializedName("card_picture_url")
    public String cardPictureUrl;

    @SerializedName("brand_id")
    public String brandId;

    @SerializedName("card_type")
    public CardType cardType;

    @SerializedName("phone_number")
    public String phoneNumber;

    @SerializedName("level")
    public String level;

    @SerializedName("valid_date_information")
    public DateInfo validDateInformation;

    @SerializedName("pickup_time")
    public String pickupTime;

    @SerializedName("user_information")
    public UserInfo userInformation;

    @SerializedName("attach")
    public String attach;

    @SerializedName("user_card_state")
    public UserCardState userCardState;

    @SerializedName("invalid_reason")
    public String invalidReason;

    @SerializedName("invalid_time")
    public String invalidTime;

    @SerializedName("create_time")
    public String createTime;

    @SerializedName("modify_time")
    public String modifyTime;
  }

  public static class UserInfo {
    @SerializedName("common_field_list")
    public List<UserInfoCommonField> commonFieldList;

    @SerializedName("custom_field_list")
    public List<UserInfoCustomField> customFieldList;
  }

  public static class DateInfo {
    @SerializedName("type")
    public DateType type;

    @SerializedName("available_begin_time")
    public String availableBeginTime;

    @SerializedName("available_end_time")
    public String availableEndTime;

    @SerializedName("available_day_after_receive")
    public Long availableDayAfterReceive;
  }

  public enum CardType {
    @SerializedName("PURCHASE")
    PURCHASE,
    @SerializedName("NORMAL")
    NORMAL,
    @SerializedName("BALANCE")
    BALANCE
  }

  public enum UserCardState {
    @SerializedName("UNACTIVATED")
    UNACTIVATED,
    @SerializedName("EFFECTIVE")
    EFFECTIVE,
    @SerializedName("EXPIRED")
    EXPIRED,
    @SerializedName("INVALID")
    INVALID
  }

  public static class UserInfoCommonField {
    @SerializedName("name")
    public CommonFieldFlag name;

    @SerializedName("value")
    public String value;
  }

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

    @SerializedName("user_chosen_values")
    public List<String> userChosenValues;
  }

  public enum DateType {
    @SerializedName("FIX_TIME_RANGE")
    FIX_TIME_RANGE,
    @SerializedName("FIX_TERM")
    FIX_TERM,
    @SerializedName("PERMANENT")
    PERMANENT
  }

  public enum CommonFieldFlag {
    @SerializedName("USER_FORM_FLAG_SEX")
    USER_FORM_FLAG_SEX,
    @SerializedName("USER_FORM_FLAG_NAME")
    USER_FORM_FLAG_NAME,
    @SerializedName("USER_FORM_FLAG_BIRTHDAY")
    USER_FORM_FLAG_BIRTHDAY,
    @SerializedName("USER_FORM_FLAG_ADDRESS")
    USER_FORM_FLAG_ADDRESS,
    @SerializedName("USER_FORM_FLAG_EMAIL")
    USER_FORM_FLAG_EMAIL,
    @SerializedName("USER_FORM_FLAG_CITY")
    USER_FORM_FLAG_CITY
  }

}

```
