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

## Go


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

```
package main

import (
	"bytes"
	"demo/wxpay_utility" // 引用微信支付工具库，参考 https://pay.weixin.qq.com/doc/v3/partner/4015119446
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

func main() {
	// TODO: 请准备商户开发必要参数，参考：https://pay.weixin.qq.com/doc/v3/partner/4013080340
	config, err := wxpay_utility.CreateMchConfig(
		"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",       // 微信支付公钥文件路径，本地文件路径
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	request := &ImportUserCardByOpenIdRequest{
		BrandId:        wxpay_utility.String("1004"),
		CardId:         wxpay_utility.String("pbLatjvWOibDc5-TBnbUk1pD12o0"),
		Openid:         wxpay_utility.String("obLatjnx9gnqzS4myYGmLZ7LgLBA"),
		UserCardCode:   wxpay_utility.String("478515832665"),
		PhoneNumber:    wxpay_utility.String("vvysDQeEaH3I+wRh14St0abIkvQyFgh/fbWYSs2bLtG9tj+bdJn4WSCPzLhShNHgujZzseiL6sYmT7E65mv/eFeTa7yslYfrX0hrhHazSM/+tfvN/C3OZwiBbcrF9LTIIdBVhGOqhCx0gK5YAVZc8dbW/yJqC5i79PDfVYJtpQe3A4v/GiDa2Q+Mv03taxgnEkzqlSPjkXiCYBj9UaFJ4bqCTXiO2Kt6TpczvAaZW+9/blxiJwqEFXe78LbrIQvkDUmVdZbqBdPQ+QGQgc/2Ea4IbP/EEt1qSyXnFbzaaKSE2j4mAFON3kzNexb/SYkHZNJAuCittaW4wpGj7U+h9A=="), /*请传入wxpay_utility.EncryptOAEPWithPublicKey 加密结果*/
		CardColor:      wxpay_utility.String("#FFFF00"),
		CardPictureUrl: wxpay_utility.String("https://wxpaylogo.qpic.cn/wxpaylogo/PiajxSqBRaEIPAeia7Imvtsn7sYGNcEj33YzVvJF88ECQ19LXId8ZL2Q/0"),
		Level:          wxpay_utility.String("钻石会员"),
		UserInformation: &UserInfo{
			CommonFieldList: []UserInfoCommonField{UserInfoCommonField{
				Name:  COMMONFIELDFLAG_USER_FORM_FLAG_BIRTHDAY.Ptr(),
				Value: wxpay_utility.String("vvysDQeEaH3I+wRh14St0abIkvQyFgh/fbWYSs2bLtG9tj+bdJn4WSCPzLhShNHgujZzseiL6sYmT7E65mv/eFeTa7yslYfrX0hrhHazSM/+tfvN/C3OZwiBbcrF9LTIIdBVhGOqhCx0gK5YAVZc8dbW/yJqC5i79PDfVYJtpQe3A4v/GiDa2Q+Mv03taxgnEkzqlSPjkXiCYBj9UaFJ4bqCTXiO2Kt6TpczvAaZW+9/blxiJwqEFXe78LbrIQvkDUmVdZbqBdPQ+QGQgc/2Ea4IbP/EEt1qSyXnFbzaaKSE2j4mAFON3kzNexb/SYkHZNJAuCittaW4wpGj7U+h9A=="), /*请传入wxpay_utility.EncryptOAEPWithPublicKey 加密结果*/
			}},
			CustomFieldList: []UserInfoCustomField{UserInfoCustomField{
				Name:             wxpay_utility.String("喜欢的运动"),
				UserChosenValues: []string{"vvysDQeEaH3I+wRh14St0abIkvQyFgh/fbWYSs2bLtG9tj+bdJn4WSCPzLhShNHgujZzseiL6sYmT7E65mv/eFeTa7yslYfrX0hrhHazSM/+tfvN/C3OZwiBbcrF9LTIIdBVhGOqhCx0gK5YAVZc8dbW/yJqC5i79PDfVYJtpQe3A4v/GiDa2Q+Mv03taxgnEkzqlSPjkXiCYBj9UaFJ4bqCTXiO2Kt6TpczvAaZW+9/blxiJwqEFXe78LbrIQvkDUmVdZbqBdPQ+QGQgc/2Ea4IbP/EEt1qSyXnFbzaaKSE2j4mAFON3kzNexb/SYkHZNJAuCittaW4wpGj7U+h9A=="},
			}},
		},
		ValidDateInformation: &DateInfo{
			Type:                     DATETYPE_PERMANENT.Ptr(),
			AvailableBeginTime:       wxpay_utility.Time(time.Now()),
			AvailableEndTime:         wxpay_utility.Time(time.Now()),
			AvailableDayAfterReceive: wxpay_utility.Int64(30),
		},
		PickupTime: wxpay_utility.Time(time.Now()),
	}

	response, err := ImportUserCardByOpenId(config, request)
	if err != nil {
		fmt.Printf("请求失败: %+v\n", err)
		// TODO: 请求失败，根据状态码执行不同的处理
		return
	}

	// TODO: 请求成功，继续业务逻辑
	fmt.Printf("请求成功: %+v\n", response)
}

func ImportUserCardByOpenId(config *wxpay_utility.MchConfig, request *ImportUserCardByOpenIdRequest) (response *UserCard, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/brand/partner/card-member/user-cards/import-by-openid"
	)

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	reqBody, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}
	httpRequest, err := http.NewRequest(method, reqUrl.String(), bytes.NewReader(reqBody))
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Accept", "application/json")
	httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
	httpRequest.Header.Set("Content-Type", "application/json")
	authorization, err := wxpay_utility.BuildAuthorization(config.MchId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), reqBody)
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Authorization", authorization)

	client := &http.Client{}
	httpResponse, err := client.Do(httpRequest)
	if err != nil {
		return nil, err
	}
	respBody, err := wxpay_utility.ExtractResponseBody(httpResponse)
	if err != nil {
		return nil, err
	}
	if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
		// 2XX 成功，验证应答签名
		err = wxpay_utility.ValidateResponse(
			config.WechatPayPublicKeyId(),
			config.WechatPayPublicKey(),
			&httpResponse.Header,
			respBody,
		)
		if err != nil {
			return nil, err
		}
		response := &UserCard{}
		if err := json.Unmarshal(respBody, response); err != nil {
			return nil, err
		}

		return response, nil
	} else {
		return nil, wxpay_utility.NewApiException(
			httpResponse.StatusCode,
			httpResponse.Header,
			respBody,
		)
	}
}

type ImportUserCardByOpenIdRequest struct {
	BrandId              *string    `json:"brand_id,omitempty"`
	CardId               *string    `json:"card_id,omitempty"`
	Openid               *string    `json:"openid,omitempty"`
	UserCardCode         *string    `json:"user_card_code,omitempty"`
	PhoneNumber          *string    `json:"phone_number,omitempty"`
	CardColor            *string    `json:"card_color,omitempty"`
	CardPictureUrl       *string    `json:"card_picture_url,omitempty"`
	Level                *string    `json:"level,omitempty"`
	UserInformation      *UserInfo  `json:"user_information,omitempty"`
	ValidDateInformation *DateInfo  `json:"valid_date_information,omitempty"`
	PickupTime           *time.Time `json:"pickup_time,omitempty"`
}

type UserCard struct {
	UserCardCode         *string        `json:"user_card_code,omitempty"`
	CardId               *string        `json:"card_id,omitempty"`
	Openid               *string        `json:"openid,omitempty"`
	CardColor            *string        `json:"card_color,omitempty"`
	CardPictureUrl       *string        `json:"card_picture_url,omitempty"`
	BrandId              *string        `json:"brand_id,omitempty"`
	CardType             *CardType      `json:"card_type,omitempty"`
	PhoneNumber          *string        `json:"phone_number,omitempty"`
	Level                *string        `json:"level,omitempty"`
	ValidDateInformation *DateInfo      `json:"valid_date_information,omitempty"`
	PickupTime           *string        `json:"pickup_time,omitempty"`
	UserInformation      *UserInfo      `json:"user_information,omitempty"`
	Attach               *string        `json:"attach,omitempty"`
	UserCardState        *UserCardState `json:"user_card_state,omitempty"`
	InvalidReason        *string        `json:"invalid_reason,omitempty"`
	InvalidTime          *string        `json:"invalid_time,omitempty"`
	CreateTime           *time.Time     `json:"create_time,omitempty"`
	ModifyTime           *time.Time     `json:"modify_time,omitempty"`
}

type UserInfo struct {
	CommonFieldList []UserInfoCommonField `json:"common_field_list,omitempty"`
	CustomFieldList []UserInfoCustomField `json:"custom_field_list,omitempty"`
}

type DateInfo struct {
	Type                     *DateType  `json:"type,omitempty"`
	AvailableBeginTime       *time.Time `json:"available_begin_time,omitempty"`
	AvailableEndTime         *time.Time `json:"available_end_time,omitempty"`
	AvailableDayAfterReceive *int64     `json:"available_day_after_receive,omitempty"`
}

type CardType string

func (e CardType) Ptr() *CardType {
	return &e
}

const (
	CARDTYPE_PURCHASE CardType = "PURCHASE"
	CARDTYPE_NORMAL   CardType = "NORMAL"
	CARDTYPE_BALANCE  CardType = "BALANCE"
)

type UserCardState string

func (e UserCardState) Ptr() *UserCardState {
	return &e
}

const (
	USERCARDSTATE_UNACTIVATED UserCardState = "UNACTIVATED"
	USERCARDSTATE_EFFECTIVE   UserCardState = "EFFECTIVE"
	USERCARDSTATE_EXPIRED     UserCardState = "EXPIRED"
	USERCARDSTATE_INVALID     UserCardState = "INVALID"
)

type UserInfoCommonField struct {
	Name  *CommonFieldFlag `json:"name,omitempty"`
	Value *string          `json:"value,omitempty"`
}

type UserInfoCustomField struct {
	Name             *string  `json:"name,omitempty"`
	UserChosenValues []string `json:"user_chosen_values,omitempty"`
}

type DateType string

func (e DateType) Ptr() *DateType {
	return &e
}

const (
	DATETYPE_FIX_TIME_RANGE DateType = "FIX_TIME_RANGE"
	DATETYPE_FIX_TERM       DateType = "FIX_TERM"
	DATETYPE_PERMANENT      DateType = "PERMANENT"
)

type CommonFieldFlag string

func (e CommonFieldFlag) Ptr() *CommonFieldFlag {
	return &e
}

const (
	COMMONFIELDFLAG_USER_FORM_FLAG_SEX      CommonFieldFlag = "USER_FORM_FLAG_SEX"
	COMMONFIELDFLAG_USER_FORM_FLAG_NAME     CommonFieldFlag = "USER_FORM_FLAG_NAME"
	COMMONFIELDFLAG_USER_FORM_FLAG_BIRTHDAY CommonFieldFlag = "USER_FORM_FLAG_BIRTHDAY"
	COMMONFIELDFLAG_USER_FORM_FLAG_ADDRESS  CommonFieldFlag = "USER_FORM_FLAG_ADDRESS"
	COMMONFIELDFLAG_USER_FORM_FLAG_EMAIL    CommonFieldFlag = "USER_FORM_FLAG_EMAIL"
	COMMONFIELDFLAG_USER_FORM_FLAG_CITY     CommonFieldFlag = "USER_FORM_FLAG_CITY"
)

```
