---
url: "https://pay.weixin.qq.com/doc/v3/partner/4015336977-go.md"
title: "修改会员卡模板信息-请求示例-go"
doc_id: 4015336977
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"
	"strings"
	"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 := &UpdateCardRequest{
		CardId:         wxpay_utility.String("pbLatjvWOibDc5-TBnbUk1pD1"),
		BrandId:        wxpay_utility.String("实例值"),
		CardTitle:      wxpay_utility.String("测试卡"),
		CardColor:      wxpay_utility.String("#FFFF00"),
		CardPictureUrl: wxpay_utility.String("https://wxpaylogo.qpic.cn/wxpaylogo/xxxxx/0"),
		CodeJumpInformation: &CodeJumpInfo{
			JumpAppid: wxpay_utility.String("wxea9c30a90fs8d3fe"),
			JumpPath:  wxpay_utility.String("/pages/code/code"),
		},
		Benefits:         wxpay_utility.String("会员折扣、专属价"),
		NotifyUrl:        wxpay_utility.String("https://www.weixin.qq.com/wxpay/notify.php"),
		NeedPinned:       wxpay_utility.Bool(true),
		NeedDisplayLevel: wxpay_utility.Bool(true),
		ServicePhone:     wxpay_utility.String("010-8877xxxx"),
		ValidDateInformation: &DateInfo{
			Type:                     DATETYPE_PERMANENT.Ptr(),
			AvailableBeginTime:       wxpay_utility.Time(time.Now()),
			AvailableEndTime:         wxpay_utility.Time(time.Now()),
			AvailableDayAfterReceive: wxpay_utility.Int64(30),
		},
		MemberInformation: &MemberInfo{
			JumpAppid: wxpay_utility.String("wxea9c30a90fs8d3fe"),
			JumpPath:  wxpay_utility.String("/pages/points/points"),
		},
		PointsInformation: &PointsInfo{
			JumpAppid: wxpay_utility.String("wxea9c30a90fs8d3fe"),
			JumpPath:  wxpay_utility.String("/pages/points/points"),
		},
		BalanceInformation: &BalanceInfo{
			JumpAppid: wxpay_utility.String("wxea9c30a90fs8d3fe"),
			JumpPath:  wxpay_utility.String("/pages/balance/balance"),
		},
		PurchaseInformation: &PurchaseInfo{
			Price:     wxpay_utility.Int64(100),
			JumpAppid: wxpay_utility.String("wxea9c30a90fs8d3fe"),
			JumpPath:  wxpay_utility.String("/pages/purchase/purchase"),
		},
		UserInformation: &UserInfoForm{
			CommonFieldList: []CommonFieldFlag{COMMONFIELDFLAG_USER_FORM_FLAG_SEX},
			CustomFieldList: []UserCustomFieldForm{UserCustomFieldForm{
				Type:   CUSTOMFIELDTYPE_CHECK_BOX.Ptr(),
				Name:   wxpay_utility.String("喜欢的运动"),
				Values: []string{"篮球"},
			}},
		},
	}

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

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

func UpdateCard(config *wxpay_utility.MchConfig, request *UpdateCardRequest) (response *Card, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "PATCH"
		path   = "/v3/brand/partner/card-member/cards/{card_id}"
	)

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	reqUrl.Path = strings.Replace(reqUrl.Path, "{card_id}", url.PathEscape(*request.CardId), -1)
	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 := &Card{}
		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 UpdateCardRequest struct {
	BrandId              *string       `json:"brand_id,omitempty"`
	CardId               *string       `json:"card_id,omitempty"`
	CardTitle            *string       `json:"card_title,omitempty"`
	CardColor            *string       `json:"card_color,omitempty"`
	CardPictureUrl       *string       `json:"card_picture_url,omitempty"`
	CodeJumpInformation  *CodeJumpInfo `json:"code_jump_information,omitempty"`
	Benefits             *string       `json:"benefits,omitempty"`
	NotifyUrl            *string       `json:"notify_url,omitempty"`
	NeedPinned           *bool         `json:"need_pinned,omitempty"`
	NeedDisplayLevel     *bool         `json:"need_display_level,omitempty"`
	ServicePhone         *string       `json:"service_phone,omitempty"`
	ValidDateInformation *DateInfo     `json:"valid_date_information,omitempty"`
	MemberInformation    *MemberInfo   `json:"member_information,omitempty"`
	PointsInformation    *PointsInfo   `json:"points_information,omitempty"`
	BalanceInformation   *BalanceInfo  `json:"balance_information,omitempty"`
	PurchaseInformation  *PurchaseInfo `json:"purchase_information,omitempty"`
	UserInformation      *UserInfoForm `json:"user_information,omitempty"`
}

func (o *UpdateCardRequest) MarshalJSON() ([]byte, error) {
	type Alias UpdateCardRequest
	a := &struct {
		CardId *string `json:"card_id,omitempty"`
		*Alias
	}{
		// 序列化时移除非 Body 字段
		CardId: nil,
		Alias:  (*Alias)(o),
	}
	return json.Marshal(a)
}

type Card struct {
	OutRequestNo         *string       `json:"out_request_no,omitempty"`
	CardId               *string       `json:"card_id,omitempty"`
	BrandId              *string       `json:"brand_id,omitempty"`
	Appid                *string       `json:"appid,omitempty"`
	CardType             *CardType     `json:"card_type,omitempty"`
	CardTitle            *string       `json:"card_title,omitempty"`
	CardColor            *string       `json:"card_color,omitempty"`
	CardPictureUrl       *string       `json:"card_picture_url,omitempty"`
	CodeMode             *CodeMode     `json:"code_mode,omitempty"`
	CodeType             *CodeType     `json:"code_type,omitempty"`
	CodeJumpInformation  *CodeJumpInfo `json:"code_jump_information,omitempty"`
	Benefits             *string       `json:"benefits,omitempty"`
	NotifyUrl            *string       `json:"notify_url,omitempty"`
	NeedPinned           *bool         `json:"need_pinned,omitempty"`
	NeedDisplayLevel     *bool         `json:"need_display_level,omitempty"`
	InitLevel            *string       `json:"init_level,omitempty"`
	ServicePhone         *string       `json:"service_phone,omitempty"`
	LegalAgreement       *string       `json:"legal_agreement,omitempty"`
	ValidDateInformation *DateInfo     `json:"valid_date_information,omitempty"`
	MemberInformation    *MemberInfo   `json:"member_information,omitempty"`
	PointsInformation    *PointsInfo   `json:"points_information,omitempty"`
	BalanceInformation   *BalanceInfo  `json:"balance_information,omitempty"`
	PurchaseInformation  *PurchaseInfo `json:"purchase_information,omitempty"`
	UserInformation      *UserInfoForm `json:"user_information,omitempty"`
	State                *CardState    `json:"state,omitempty"`
	CreateTime           *time.Time    `json:"create_time,omitempty"`
	ModifyTime           *time.Time    `json:"modify_time,omitempty"`
}

type CodeJumpInfo struct {
	JumpAppid *string `json:"jump_appid,omitempty"`
	JumpPath  *string `json:"jump_path,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 MemberInfo struct {
	JumpAppid *string `json:"jump_appid,omitempty"`
	JumpPath  *string `json:"jump_path,omitempty"`
}

type PointsInfo struct {
	JumpAppid *string `json:"jump_appid,omitempty"`
	JumpPath  *string `json:"jump_path,omitempty"`
}

type BalanceInfo struct {
	JumpAppid *string `json:"jump_appid,omitempty"`
	JumpPath  *string `json:"jump_path,omitempty"`
}

type PurchaseInfo struct {
	Price     *int64  `json:"price,omitempty"`
	JumpAppid *string `json:"jump_appid,omitempty"`
	JumpPath  *string `json:"jump_path,omitempty"`
}

type UserInfoForm struct {
	CommonFieldList []CommonFieldFlag     `json:"common_field_list,omitempty"`
	CustomFieldList []UserCustomFieldForm `json:"custom_field_list,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 CodeMode string

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

const (
	CODEMODE_SYSTEM_ALLOCATE   CodeMode = "SYSTEM_ALLOCATE"
	CODEMODE_MERCHANT_ALLOCATE CodeMode = "MERCHANT_ALLOCATE"
)

type CodeType string

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

const (
	CODETYPE_NONE_CODE            CodeType = "NONE_CODE"
	CODETYPE_BAR_CODE             CodeType = "BAR_CODE"
	CODETYPE_QR_CODE              CodeType = "QR_CODE"
	CODETYPE_BAR_CODE_AND_QR_CODE CodeType = "BAR_CODE_AND_QR_CODE"
	CODETYPE_JUMP_MINI_PROGRAM    CodeType = "JUMP_MINI_PROGRAM"
)

type CardState string

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

const (
	CARDSTATE_CARD_EFFECTIVE CardState = "CARD_EFFECTIVE"
	CARDSTATE_CARD_INVALID   CardState = "CARD_INVALID"
)

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"
)

type UserCustomFieldForm struct {
	Type   *CustomFieldType `json:"type,omitempty"`
	Name   *string          `json:"name,omitempty"`
	Values []string         `json:"values,omitempty"`
}

type CustomFieldType string

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

const (
	CUSTOMFIELDTYPE_CHECK_BOX CustomFieldType = "CHECK_BOX"
	CUSTOMFIELDTYPE_RADIO     CustomFieldType = "RADIO"
)

```
