github.com/gorocks/apikit@v0.0.0-20170808011444-396ab031afbd/pay/wechat/wechat.go (about)

     1  package wechat
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/md5"
     6  	"encoding/xml"
     7  	"fmt"
     8  	"net/http"
     9  	"sort"
    10  
    11  	"github.com/douglarek/apikit"
    12  	"github.com/fatih/structs"
    13  )
    14  
    15  const (
    16  	orderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder"
    17  	queryURL = "https://api.mch.weixin.qq.com/pay/orderquery"
    18  )
    19  
    20  // Wechat ...
    21  type Wechat struct {
    22  	client *apikit.Client
    23  }
    24  
    25  // New makes a wechat ...
    26  func New(httpClient *http.Client) *Wechat {
    27  	c := apikit.NewClient(httpClient)
    28  	c.SetHeader(apikit.H{"Content-Type": apikit.MediaXML})
    29  	return &Wechat{client: c}
    30  }
    31  
    32  // Req ...
    33  type Req struct {
    34  	XMLName  xml.Name `xml:"xml" json:"-"`
    35  	AppID    string   `xml:"appid" structs:"appid" json:"appId"`
    36  	MchID    string   `xml:"mch_id" structs:"mch_id" json:"partnerId"`
    37  	NonceStr string   `xml:"nonce_str" structs:"nonce_str" json:"nonceStr"`
    38  	Sign     string   `xml:"sign" structs:"sign" json:"sign"`
    39  }
    40  
    41  // OrderReq ...
    42  type OrderReq struct {
    43  	Req
    44  	DeviceInfo     string `xml:"device_info" structs:"device_info"`
    45  	Body           string `xml:"body" structs:"body"`
    46  	Detail         string `xml:"detail" structs:"detail"`
    47  	Attach         string `xml:"attach" structs:"attach"`
    48  	OutTradeNo     string `xml:"out_trade_no" structs:"out_trade_no"`
    49  	FeeType        string `xml:"fee_type" structs:"fee_type"`
    50  	TotalFee       int    `xml:"total_fee" structs:"total_fee"`
    51  	SpbillCreateIP string `xml:"spbill_create_ip" structs:"spbill_create_ip"`
    52  	TimeStart      string `xml:"time_start" structs:"time_start"`
    53  	TimeExpire     string `xml:"time_expire" structs:"time_expire"`
    54  	GoodsTag       string `xml:"goods_tag" structs:"goods_tag"`
    55  	NotifyURL      string `xml:"notify_url" structs:"notify_url"`
    56  	TradeType      string `xml:"trade_type" structs:"trade_type"`
    57  	ProductID      string `xml:"product_id" structs:"product_id"`
    58  	LimitPay       string `xml:"limit_pay" structs:"limit_pay"`
    59  	OpenID         string `xml:"openid" structs:"openid"`
    60  }
    61  
    62  // Resp ...
    63  type Resp struct {
    64  	ReturnCode string `structs:"return_code" xml:"return_code" json:"returnCode"`
    65  	ReturnMsg  string `structs:"return_msg" xml:"return_msg" json:"returnMsg"`
    66  	ResultCode string `structs:"result_code" xml:"result_code" json:"resultCode"`
    67  	ErrCode    string `structs:"err_code" xml:"err_code" json:"errCode"`
    68  	ErrCodeDes string `structs:"err_code_des" xml:"err_code_des" json:"errCodeDes"`
    69  }
    70  
    71  // OrderResp ...
    72  type OrderResp struct {
    73  	Resp
    74  	Req
    75  	DeviceInfo string `xml:"device_info" structs:"device_info"`
    76  	TradeType  string `xml:"trade_type"`
    77  	PrepayID   string `xml:"prepay_id"`
    78  	CodeURL    string `xml:"code_url"`
    79  }
    80  
    81  // QueryReq ...
    82  type QueryReq struct {
    83  	Req
    84  	TransactionID string `xml:"transaction_id" structs:"transaction_id"`
    85  	OutTradeNo    string `xml:"out_trade_no" structs:"out_trade_no"`
    86  }
    87  
    88  // QueryResp ...
    89  type QueryResp struct {
    90  	Resp
    91  	Req
    92  	DeviceInfo     string `structs:"device_info" xml:"device_info" json:"deviceInfo"`
    93  	OpenID         string `structs:"openid" xml:"openid" json:"openId"`
    94  	IsSubscribe    string `structs:"is_subscribe" xml:"is_subscribe" json:"isSubscribe"`
    95  	TradeType      string `structs:"trade_type" xml:"trade_type" json:"tradeType"`
    96  	TradeState     string `structs:"trade_state" xml:"trade_state" json:"tradeState"`
    97  	BankType       string `structs:"bank_type" xml:"bank_type" json:"bankType"`
    98  	TotalFee       string `structs:"total_fee" xml:"total_fee" json:"totalFee"`
    99  	FeeType        string `structs:"fee_type" xml:"fee_type" json:"feeType"`
   100  	CashFee        int    `structs:"cash_fee" xml:"cash_fee" json:"cashFee"`
   101  	CashFeeType    string `structs:"cash_fee_type" xml:"cash_fee_type" json:"cashFeeType"`
   102  	CouponFee      int    `structs:"coupon_fee" xml:"coupon_fee" json:"couponFee"`
   103  	CouponCount    int    `structs:"coupon_count" xml:"coupon_count" json:"couponCount"`
   104  	TransactionID  string `structs:"transaction_id" xml:"transaction_id" json:"transactionId"`
   105  	OutTradeNo     string `structs:"out_trade_no" xml:"out_trade_no" json:"outTradeNo"`
   106  	Attach         string `structs:"attach" xml:"attach" json:"attach"`
   107  	TimeEnd        string `structs:"time_end" xml:"time_end" json:"timeEnd"`
   108  	TradeStateDesc string `structs:"trade_state_desc" xml:"trade_state_desc" json:"tradeStateDesc"`
   109  }
   110  
   111  // NotifyReq ...
   112  type NotifyReq struct {
   113  	QueryResp
   114  }
   115  
   116  // NotifyResp ...
   117  type NotifyResp struct {
   118  	XMLName    xml.Name `xml:"xml"`
   119  	ReturnCode string   `xml:"return_code"`
   120  	ReturnMsg  string   `xml:"return_msg"`
   121  }
   122  
   123  // AppReq packages needed params for client.
   124  type AppReq struct {
   125  	AppID     string `structs:"appid" json:"appid"`
   126  	PartnerID string `structs:"partnerid" json:"partnerid"`
   127  	PrepayID  string `structs:"prepayid" json:"prepayid"`
   128  	Package   string `structs:"package" json:"package"`
   129  	NonceStr  string `structs:"noncestr" json:"noncestr"`
   130  	TimeStamp string `structs:"timestamp" json:"timestamp"`
   131  	Sign      string `structs:"sign" json:"sign"`
   132  }
   133  
   134  // Sign ...
   135  func (w *Wechat) Sign(s interface{}, secret string) string {
   136  	m := apikit.Params(structs.Map(s))
   137  	delete(m, "sign")
   138  	keys := make([]string, 0, len(m))
   139  	for k := range m {
   140  		keys = append(keys, k)
   141  	}
   142  	sort.Strings(keys)
   143  
   144  	var buf bytes.Buffer
   145  	for _, k := range keys {
   146  		buf.WriteString(fmt.Sprintf("%s=%s", k, m[k]))
   147  		buf.WriteString("&")
   148  	}
   149  	buf.WriteString("key=" + secret)
   150  	return fmt.Sprintf("%X", md5.Sum(buf.Bytes()))
   151  }
   152  
   153  // Order ...
   154  func (w *Wechat) Order(r *OrderReq) (*OrderResp, error) {
   155  	req, err := w.client.NewRequest("POST", orderURL, r)
   156  	if err != nil {
   157  		return nil, err
   158  	}
   159  	res := new(OrderResp)
   160  	if _, err := w.client.Do(req, res); err != nil {
   161  		return nil, err
   162  	}
   163  	return res, nil
   164  }
   165  
   166  // Query ...
   167  func (w *Wechat) Query(r *QueryReq) (*QueryResp, error) {
   168  	req, err := w.client.NewRequest("POST", queryURL, r)
   169  	if err != nil {
   170  		return nil, err
   171  	}
   172  	res := new(QueryResp)
   173  	if _, err := w.client.Do(req, res); err != nil {
   174  		return nil, err
   175  	}
   176  	return res, nil
   177  }