Jerry 6 лет назад
Родитель
Сommit
d7d9958582
8 измененных файлов с 500 добавлено и 584 удалено
  1. 222 278
      alipay_client.go
  2. 17 6
      alipay_client_test.go
  3. 38 51
      alipay_params.go
  4. 116 134
      alipay_service_api.go
  5. 30 31
      constant.go
  6. 48 48
      wechat_client.go
  7. 10 10
      wechat_params.go
  8. 19 26
      wechat_service_api.go

+ 222 - 278
alipay_client.go

@@ -4,14 +4,15 @@ import (
 	"encoding/json"
 	"encoding/json"
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
-	"log"
 	"strings"
 	"strings"
 	"time"
 	"time"
+
+	"github.com/parnurzeal/gorequest"
 )
 )
 
 
 type AliPayClient struct {
 type AliPayClient struct {
 	AppId            string
 	AppId            string
-	privateKey       string
+	PrivateKey       string
 	AlipayRootCertSN string
 	AlipayRootCertSN string
 	AppCertSN        string
 	AppCertSN        string
 	ReturnUrl        string
 	ReturnUrl        string
@@ -20,384 +21,363 @@ type AliPayClient struct {
 	SignType         string
 	SignType         string
 	AppAuthToken     string
 	AppAuthToken     string
 	AuthToken        string
 	AuthToken        string
-	isProd           bool
+	IsProd           bool
 }
 }
 
 
 //初始化支付宝客户端
 //初始化支付宝客户端
 //    注意:如果使用支付宝公钥证书验签,请设置 支付宝根证书SN(client.SetAlipayRootCertSN())、应用公钥证书SN(client.SetAppCertSN())
 //    注意:如果使用支付宝公钥证书验签,请设置 支付宝根证书SN(client.SetAlipayRootCertSN())、应用公钥证书SN(client.SetAppCertSN())
 //    appId:应用ID
 //    appId:应用ID
-//    privateKey:应用私钥
-//    isProd:是否是正式环境
+//    PrivateKey:应用私钥
+//    IsProd:是否是正式环境
 func NewAliPayClient(appId, privateKey string, isProd bool) (client *AliPayClient) {
 func NewAliPayClient(appId, privateKey string, isProd bool) (client *AliPayClient) {
-	client = new(AliPayClient)
-	client.AppId = appId
-	client.privateKey = privateKey
-	client.isProd = isProd
-	return client
+	return &AliPayClient{
+		AppId:      appId,
+		PrivateKey: privateKey,
+		IsProd:     isProd,
+	}
 }
 }
 
 
 //alipay.trade.fastpay.refund.query(统一收单交易退款查询)
 //alipay.trade.fastpay.refund.query(统一收单交易退款查询)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.fastpay.refund.query
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.fastpay.refund.query
-func (this *AliPayClient) AliPayTradeFastPayRefundQuery(body BodyMap) (aliRsp *AliPayTradeFastpayRefundQueryResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradeFastPayRefundQuery(body BodyMap) (aliRsp *AliPayTradeFastpayRefundQueryResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("trade_no")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.fastpay.refund.query")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.fastpay.refund.query"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradeFastPayRefundQuery::::", string(bytes))
 	aliRsp = new(AliPayTradeFastpayRefundQueryResponse)
 	aliRsp = new(AliPayTradeFastpayRefundQueryResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
-		return nil, fmt.Errorf("json.Unmarshal:%v", err.Error())
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
+		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradeFastpayRefundQueryResponse.Code != "10000" {
 	if aliRsp.AliPayTradeFastpayRefundQueryResponse.Code != "10000" {
 		info := aliRsp.AliPayTradeFastpayRefundQueryResponse
 		info := aliRsp.AliPayTradeFastpayRefundQueryResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.order.settle(统一收单交易结算接口)
 //alipay.trade.order.settle(统一收单交易结算接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.order.settle
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.order.settle
-func (this *AliPayClient) AliPayTradeOrderSettle(body BodyMap) (aliRsp *AliPayTradeOrderSettleResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_request_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null || trade2 == null {
+func (a *AliPayClient) AliPayTradeOrderSettle(body BodyMap) (aliRsp *AliPayTradeOrderSettleResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_request_no")
+	p2 = body.Get("trade_no")
+	if p1 == null || p2 == null {
 		return nil, errors.New("out_request_no or trade_no are not allowed to be null")
 		return nil, errors.New("out_request_no or trade_no are not allowed to be null")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.order.settle")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.order.settle"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradeOrderSettle::::", string(bytes))
 	aliRsp = new(AliPayTradeOrderSettleResponse)
 	aliRsp = new(AliPayTradeOrderSettleResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradeOrderSettleResponse.Code != "10000" {
 	if aliRsp.AliPayTradeOrderSettleResponse.Code != "10000" {
 		info := aliRsp.AliPayTradeOrderSettleResponse
 		info := aliRsp.AliPayTradeOrderSettleResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.create(统一收单交易创建接口)
 //alipay.trade.create(统一收单交易创建接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.create
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.create
-func (this *AliPayClient) AliPayTradeCreate(body BodyMap) (aliRsp *AliPayTradeCreateResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("buyer_id")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradeCreate(body BodyMap) (aliRsp *AliPayTradeCreateResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("buyer_id")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and buyer_id are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and buyer_id are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.create")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.create"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradeCreateResponse::::", string(bytes))
 	aliRsp = new(AliPayTradeCreateResponse)
 	aliRsp = new(AliPayTradeCreateResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradeCreateResponse.Code != "10000" {
 	if aliRsp.AliPayTradeCreateResponse.Code != "10000" {
 		info := aliRsp.AliPayTradeCreateResponse
 		info := aliRsp.AliPayTradeCreateResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.close(统一收单交易关闭接口)
 //alipay.trade.close(统一收单交易关闭接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.close
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.close
-func (this *AliPayClient) AliPayTradeClose(body BodyMap) (aliRsp *AliPayTradeCloseResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradeClose(body BodyMap) (aliRsp *AliPayTradeCloseResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("trade_no")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.close")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.close"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradeCloseResponse::::", string(bytes))
 	aliRsp = new(AliPayTradeCloseResponse)
 	aliRsp = new(AliPayTradeCloseResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradeCloseResponse.Code != "10000" {
 	if aliRsp.AliPayTradeCloseResponse.Code != "10000" {
 		info := aliRsp.AliPayTradeCloseResponse
 		info := aliRsp.AliPayTradeCloseResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.cancel(统一收单交易撤销接口)
 //alipay.trade.cancel(统一收单交易撤销接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.cancel
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.cancel
-func (this *AliPayClient) AliPayTradeCancel(body BodyMap) (aliRsp *AliPayTradeCancelResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradeCancel(body BodyMap) (aliRsp *AliPayTradeCancelResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("trade_no")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.cancel")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.cancel"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradeCancel::::", string(bytes))
 	aliRsp = new(AliPayTradeCancelResponse)
 	aliRsp = new(AliPayTradeCancelResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradeCancelResponse.Code != "10000" {
 	if aliRsp.AliPayTradeCancelResponse.Code != "10000" {
 		info := aliRsp.AliPayTradeCancelResponse
 		info := aliRsp.AliPayTradeCancelResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.refund(统一收单交易退款接口)
 //alipay.trade.refund(统一收单交易退款接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.refund
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.refund
-func (this *AliPayClient) AliPayTradeRefund(body BodyMap) (aliRsp *AliPayTradeRefundResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradeRefund(body BodyMap) (aliRsp *AliPayTradeRefundResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("trade_no")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.refund")
-	if err != nil {
+	if bs, err = a.doAliPay(body, "alipay.trade.refund"); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
-	//log.Println("AliPayTradeRefundResponse::::", string(bytes))
 	aliRsp = new(AliPayTradeRefundResponse)
 	aliRsp = new(AliPayTradeRefundResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AlipayTradeRefundResponse.Code != "10000" {
 	if aliRsp.AlipayTradeRefundResponse.Code != "10000" {
 		info := aliRsp.AlipayTradeRefundResponse
 		info := aliRsp.AlipayTradeRefundResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.refund(统一收单退款页面接口)
 //alipay.trade.refund(统一收单退款页面接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.page.refund
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.page.refund
-func (this *AliPayClient) AliPayTradePageRefund(body BodyMap) (aliRsp *AliPayTradePageRefundResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradePageRefund(body BodyMap) (aliRsp *AliPayTradePageRefundResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("trade_no")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "	alipay.trade.page.refund")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "	alipay.trade.page.refund"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradePageRefundResponse::::", string(bytes))
 	aliRsp = new(AliPayTradePageRefundResponse)
 	aliRsp = new(AliPayTradePageRefundResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradePageRefundResponse.Code != "10000" {
 	if aliRsp.AliPayTradePageRefundResponse.Code != "10000" {
 		info := aliRsp.AliPayTradePageRefundResponse
 		info := aliRsp.AliPayTradePageRefundResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.precreate(统一收单线下交易预创建)
 //alipay.trade.precreate(统一收单线下交易预创建)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.precreate
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.precreate
-func (this *AliPayClient) AliPayTradePrecreate(body BodyMap) (aliRsp *AlipayTradePrecreateResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	if trade1 == null {
+func (a *AliPayClient) AliPayTradePrecreate(body BodyMap) (aliRsp *AlipayTradePrecreateResponse, err error) {
+	var bs []byte
+	p := body.Get("out_trade_no")
+	if p == null {
 		return nil, errors.New("out_trade_no is not allowed to be null")
 		return nil, errors.New("out_trade_no is not allowed to be null")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.precreate")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.precreate"); err != nil {
+		return
 	}
 	}
-	//log.Println("AlipayTradePrecreateResponse::::", string(bytes))
 	aliRsp = new(AlipayTradePrecreateResponse)
 	aliRsp = new(AlipayTradePrecreateResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AlipayTradePrecreateResponse.Code != "10000" {
 	if aliRsp.AlipayTradePrecreateResponse.Code != "10000" {
 		info := aliRsp.AlipayTradePrecreateResponse
 		info := aliRsp.AlipayTradePrecreateResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.pay(统一收单交易支付接口)
 //alipay.trade.pay(统一收单交易支付接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.pay
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.pay
-func (this *AliPayClient) AliPayTradePay(body BodyMap) (aliRsp *AliPayTradePayResponse, err error) {
-	var bytes []byte
-	trade := body.Get("out_trade_no")
-	if trade == null {
+func (a *AliPayClient) AliPayTradePay(body BodyMap) (aliRsp *AliPayTradePayResponse, err error) {
+	var bs []byte
+	p := body.Get("out_trade_no")
+	if p == null {
 		return nil, errors.New("out_trade_no is not allowed to be null")
 		return nil, errors.New("out_trade_no is not allowed to be null")
 	}
 	}
-	//===============product_code值===================
-	//body.Set("product_code", "FACE_TO_FACE_PAYMENT")
-	bytes, err = this.doAliPay(body, "alipay.trade.pay")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.pay"); err != nil {
+		return
 	}
 	}
-
-	//log.Println("AliPayTradePayResponse::::", string(bytes))
 	aliRsp = new(AliPayTradePayResponse)
 	aliRsp = new(AliPayTradePayResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradePayResponse.Code != "10000" {
 	if aliRsp.AliPayTradePayResponse.Code != "10000" {
 		info := aliRsp.AliPayTradePayResponse
 		info := aliRsp.AliPayTradePayResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.query(统一收单线下交易查询)
 //alipay.trade.query(统一收单线下交易查询)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.query
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.query
-func (this *AliPayClient) AliPayTradeQuery(body BodyMap) (aliRsp *AliPayTradeQueryResponse, err error) {
-	var bytes []byte
-	trade1 := body.Get("out_trade_no")
-	trade2 := body.Get("trade_no")
-	if trade1 == null && trade2 == null {
+func (a *AliPayClient) AliPayTradeQuery(body BodyMap) (aliRsp *AliPayTradeQueryResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	p1 = body.Get("out_trade_no")
+	p2 = body.Get("trade_no")
+	if p1 == null && p2 == null {
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 		return nil, errors.New("out_trade_no and trade_no are not allowed to be null at the same time")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.trade.query")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.trade.query"); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPayTradeQueryResponse::::", string(bytes))
 	aliRsp = new(AliPayTradeQueryResponse)
 	aliRsp = new(AliPayTradeQueryResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPayTradeQueryResponse.Code != "10000" {
 	if aliRsp.AliPayTradeQueryResponse.Code != "10000" {
 		info := aliRsp.AliPayTradeQueryResponse
 		info := aliRsp.AliPayTradeQueryResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.app.pay(app支付接口2.0)
 //alipay.trade.app.pay(app支付接口2.0)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.app.pay
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.app.pay
-func (this *AliPayClient) AliPayTradeAppPay(body BodyMap) (payParam string, err error) {
-	var bytes []byte
+func (a *AliPayClient) AliPayTradeAppPay(body BodyMap) (payParam string, err error) {
+	var bs []byte
 	trade := body.Get("out_trade_no")
 	trade := body.Get("out_trade_no")
 	if trade == null {
 	if trade == null {
 		return null, errors.New("out_trade_no is not allowed to be null")
 		return null, errors.New("out_trade_no is not allowed to be null")
 	}
 	}
-	//===============product_code值===================
-	//body.Set("product_code", "QUICK_MSECURITY_PAY")
-	bytes, err = this.doAliPay(body, "alipay.trade.app.pay")
-	if err != nil {
+	if bs, err = a.doAliPay(body, "alipay.trade.app.pay"); err != nil {
 		return null, err
 		return null, err
 	}
 	}
-	payParam = string(bytes)
-	return payParam, nil
+	payParam = string(bs)
+	return
 }
 }
 
 
 //alipay.trade.wap.pay(手机网站支付接口2.0)
 //alipay.trade.wap.pay(手机网站支付接口2.0)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.wap.pay
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.wap.pay
-func (this *AliPayClient) AliPayTradeWapPay(body BodyMap) (payUrl string, err error) {
-	var bytes []byte
+func (a *AliPayClient) AliPayTradeWapPay(body BodyMap) (payUrl string, err error) {
+	var bs []byte
 	trade := body.Get("out_trade_no")
 	trade := body.Get("out_trade_no")
 	if trade == null {
 	if trade == null {
 		return null, errors.New("out_trade_no is not allowed to be null")
 		return null, errors.New("out_trade_no is not allowed to be null")
 	}
 	}
-	//===============product_code值===================
 	body.Set("product_code", "QUICK_WAP_WAY")
 	body.Set("product_code", "QUICK_WAP_WAY")
-	bytes, err = this.doAliPay(body, "alipay.trade.wap.pay")
-	if err != nil {
-		//log.Println("err::", err.Error())
+	if bs, err = a.doAliPay(body, "alipay.trade.wap.pay"); err != nil {
 		return null, err
 		return null, err
 	}
 	}
-	payUrl = string(bytes)
-	return payUrl, nil
+	payUrl = string(bs)
+	return
 }
 }
 
 
 //alipay.trade.page.pay(统一收单下单并支付页面接口)
 //alipay.trade.page.pay(统一收单下单并支付页面接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.page.pay
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.page.pay
-func (this *AliPayClient) AliPayTradePagePay(body BodyMap) (payUrl string, err error) {
-	var bytes []byte
+func (a *AliPayClient) AliPayTradePagePay(body BodyMap) (payUrl string, err error) {
+	var bs []byte
 	trade := body.Get("out_trade_no")
 	trade := body.Get("out_trade_no")
 	if trade == null {
 	if trade == null {
 		return null, errors.New("out_trade_no is not allowed to be null")
 		return null, errors.New("out_trade_no is not allowed to be null")
 	}
 	}
-	//===============product_code值===================
 	body.Set("product_code", "FAST_INSTANT_TRADE_PAY")
 	body.Set("product_code", "FAST_INSTANT_TRADE_PAY")
-	bytes, err = this.doAliPay(body, "alipay.trade.page.pay")
-	if err != nil {
-		//log.Println("err::", err.Error())
+	if bs, err = a.doAliPay(body, "alipay.trade.page.pay"); err != nil {
 		return null, err
 		return null, err
 	}
 	}
-	payUrl = string(bytes)
-	return payUrl, nil
+	payUrl = string(bs)
+	return
 }
 }
 
 
 //alipay.fund.trans.toaccount.transfer(单笔转账到支付宝账户接口)
 //alipay.fund.trans.toaccount.transfer(单笔转账到支付宝账户接口)
 //    文档地址:https://docs.open.alipay.com/api_28/alipay.fund.trans.toaccount.transfer
 //    文档地址:https://docs.open.alipay.com/api_28/alipay.fund.trans.toaccount.transfer
-func (this *AliPayClient) AlipayFundTransToaccountTransfer(body BodyMap) (aliRsp *AlipayFundTransToaccountTransferResponse, err error) {
-	var bytes []byte
+func (a *AliPayClient) AlipayFundTransToaccountTransfer(body BodyMap) (aliRsp *AlipayFundTransToaccountTransferResponse, err error) {
+	var bs []byte
 	trade1 := body.Get("out_biz_no")
 	trade1 := body.Get("out_biz_no")
 	if trade1 == null {
 	if trade1 == null {
 		return nil, errors.New("out_biz_no is not allowed to be null")
 		return nil, errors.New("out_biz_no is not allowed to be null")
 	}
 	}
-	bytes, err = this.doAliPay(body, "alipay.fund.trans.toaccount.transfer")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.fund.trans.toaccount.transfer"); err != nil {
+		return
 	}
 	}
-	//log.Println("AlipayFundTransToaccountTransferResponse::::", string(bytes))
 	aliRsp = new(AlipayFundTransToaccountTransferResponse)
 	aliRsp = new(AlipayFundTransToaccountTransferResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AlipayFundTransToaccountTransferResponse.Code != "10000" {
 	if aliRsp.AlipayFundTransToaccountTransferResponse.Code != "10000" {
 		info := aliRsp.AlipayFundTransToaccountTransferResponse
 		info := aliRsp.AlipayFundTransToaccountTransferResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //alipay.trade.orderinfo.sync(支付宝订单信息同步接口)
 //alipay.trade.orderinfo.sync(支付宝订单信息同步接口)
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.orderinfo.sync
 //    文档地址:https://docs.open.alipay.com/api_1/alipay.trade.orderinfo.sync
-func (this *AliPayClient) AliPayTradeOrderinfoSync(body BodyMap) {
+func (a *AliPayClient) AliPayTradeOrderinfoSync(body BodyMap) {
 
 
 }
 }
 
 
 //alipay.system.oauth.token(换取授权访问令牌)
 //alipay.system.oauth.token(换取授权访问令牌)
 //    文档地址:https://docs.open.alipay.com/api_9/alipay.system.oauth.token
 //    文档地址:https://docs.open.alipay.com/api_9/alipay.system.oauth.token
-func (this *AliPayClient) AliPaySystemOauthToken(body BodyMap) (aliRsp *AliPaySystemOauthTokenResponse, err error) {
+func (a *AliPayClient) AliPaySystemOauthToken(body BodyMap) (aliRsp *AliPaySystemOauthTokenResponse, err error) {
 	var bs []byte
 	var bs []byte
 	grantType := body.Get("grant_type")
 	grantType := body.Get("grant_type")
 	if grantType == null {
 	if grantType == null {
@@ -408,15 +388,11 @@ func (this *AliPayClient) AliPaySystemOauthToken(body BodyMap) (aliRsp *AliPaySy
 	if code == null && refreshToken == null {
 	if code == null && refreshToken == null {
 		return nil, errors.New("code and refresh_token are not allowed to be null at the same time")
 		return nil, errors.New("code and refresh_token are not allowed to be null at the same time")
 	}
 	}
-
-	bs, err = aliPaySystemOauthToken(this.AppId, this.privateKey, body, "alipay.system.oauth.token", this.isProd)
-	if err != nil {
-		return nil, err
+	if bs, err = aliPaySystemOauthToken(a.AppId, a.PrivateKey, body, "alipay.system.oauth.token", a.IsProd); err != nil {
+		return
 	}
 	}
-	//log.Println("AliPaySystemOauthToken::::", string(bytes))
 	aliRsp = new(AliPaySystemOauthTokenResponse)
 	aliRsp = new(AliPaySystemOauthTokenResponse)
-	err = json.Unmarshal(bs, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AliPaySystemOauthTokenResponse.AccessToken == null {
 	if aliRsp.AliPaySystemOauthTokenResponse.AccessToken == null {
@@ -424,22 +400,19 @@ func (this *AliPayClient) AliPaySystemOauthToken(body BodyMap) (aliRsp *AliPaySy
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
 	aliRsp.SignData = getSignData(bs)
 	aliRsp.SignData = getSignData(bs)
-	return aliRsp, nil
+	return
 }
 }
 
 
 //alipay.user.info.share(支付宝会员授权信息查询接口)
 //alipay.user.info.share(支付宝会员授权信息查询接口)
 //    body:此接口无需body参数
 //    body:此接口无需body参数
 //    文档地址:https://docs.open.alipay.com/api_2/alipay.user.info.share
 //    文档地址:https://docs.open.alipay.com/api_2/alipay.user.info.share
-func (this *AliPayClient) AlipayUserInfoShare() (aliRsp *AlipayUserInfoShareResponse, err error) {
+func (a *AliPayClient) AlipayUserInfoShare() (aliRsp *AlipayUserInfoShareResponse, err error) {
 	var bs []byte
 	var bs []byte
-	bs, err = this.doAliPay(nil, "alipay.user.info.share")
-	if err != nil {
+	if bs, err = a.doAliPay(nil, "alipay.user.info.share"); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
-	//log.Println("AlipayUserInfoShare::::", string(bs))
 	aliRsp = new(AlipayUserInfoShareResponse)
 	aliRsp = new(AlipayUserInfoShareResponse)
-	err = json.Unmarshal(bs, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AlipayUserInfoShareResponse.Code != "10000" {
 	if aliRsp.AlipayUserInfoShareResponse.Code != "10000" {
@@ -447,12 +420,12 @@ func (this *AliPayClient) AlipayUserInfoShare() (aliRsp *AlipayUserInfoShareResp
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
 	aliRsp.SignData = getSignData(bs)
 	aliRsp.SignData = getSignData(bs)
-	return aliRsp, nil
+	return
 }
 }
 
 
 //alipay.open.auth.token.app(换取应用授权令牌)
 //alipay.open.auth.token.app(换取应用授权令牌)
 //    文档地址:https://docs.open.alipay.com/api_9/alipay.open.auth.token.app
 //    文档地址:https://docs.open.alipay.com/api_9/alipay.open.auth.token.app
-func (this *AliPayClient) AlipayOpenAuthTokenApp(body BodyMap) (aliRsp *AlipayOpenAuthTokenAppResponse, err error) {
+func (a *AliPayClient) AlipayOpenAuthTokenApp(body BodyMap) (aliRsp *AlipayOpenAuthTokenAppResponse, err error) {
 	var bs []byte
 	var bs []byte
 	grantType := body.Get("grant_type")
 	grantType := body.Get("grant_type")
 	if grantType == null {
 	if grantType == null {
@@ -463,15 +436,11 @@ func (this *AliPayClient) AlipayOpenAuthTokenApp(body BodyMap) (aliRsp *AlipayOp
 	if code == null && refreshToken == null {
 	if code == null && refreshToken == null {
 		return nil, errors.New("code and refresh_token are not allowed to be null at the same time")
 		return nil, errors.New("code and refresh_token are not allowed to be null at the same time")
 	}
 	}
-
-	bs, err = this.doAliPay(body, "alipay.open.auth.token.app")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "alipay.open.auth.token.app"); err != nil {
+		return
 	}
 	}
-	//log.Println("AlipayOpenAuthTokenApp::::", string(bs))
 	aliRsp = new(AlipayOpenAuthTokenAppResponse)
 	aliRsp = new(AlipayOpenAuthTokenAppResponse)
-	err = json.Unmarshal(bs, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.AlipayOpenAuthTokenAppResponse.Code != "10000" {
 	if aliRsp.AlipayOpenAuthTokenAppResponse.Code != "10000" {
@@ -479,147 +448,122 @@ func (this *AliPayClient) AlipayOpenAuthTokenApp(body BodyMap) (aliRsp *AlipayOp
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
 	aliRsp.SignData = getSignData(bs)
 	aliRsp.SignData = getSignData(bs)
-	return aliRsp, nil
+	return
 }
 }
 
 
 //zhima.credit.score.get(芝麻分)
 //zhima.credit.score.get(芝麻分)
 //    文档地址:https://docs.open.alipay.com/api_8/zhima.credit.score.get
 //    文档地址:https://docs.open.alipay.com/api_8/zhima.credit.score.get
-func (this *AliPayClient) ZhimaCreditScoreGet(body BodyMap) (aliRsp *ZhimaCreditScoreGetResponse, err error) {
-	var bytes []byte
-
-	trade1 := body.Get("product_code")
-	if trade1 == null {
+func (a *AliPayClient) ZhimaCreditScoreGet(body BodyMap) (aliRsp *ZhimaCreditScoreGetResponse, err error) {
+	var (
+		p1, p2 string
+		bs     []byte
+	)
+	if p1 = body.Get("product_code"); p1 == null {
 		body.Set("product_code", "w1010100100000000001")
 		body.Set("product_code", "w1010100100000000001")
 	}
 	}
-	trade2 := body.Get("transaction_id")
-	if trade2 == null {
+	if p2 = body.Get("transaction_id"); p2 == null {
 		return nil, errors.New("transaction_id is not allowed to be null")
 		return nil, errors.New("transaction_id is not allowed to be null")
 	}
 	}
-	bytes, err = this.doAliPay(body, "zhima.credit.score.get")
-	if err != nil {
-		return nil, err
+	if bs, err = a.doAliPay(body, "zhima.credit.score.get"); err != nil {
+		return
 	}
 	}
-	//log.Println("ZhimaCreditScoreGet::::", string(bytes))
 	aliRsp = new(ZhimaCreditScoreGetResponse)
 	aliRsp = new(ZhimaCreditScoreGetResponse)
-	err = json.Unmarshal(bytes, aliRsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, aliRsp); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 	if aliRsp.ZhimaCreditScoreGetResponse.Code != "10000" {
 	if aliRsp.ZhimaCreditScoreGetResponse.Code != "10000" {
 		info := aliRsp.ZhimaCreditScoreGetResponse
 		info := aliRsp.ZhimaCreditScoreGetResponse
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 		return nil, fmt.Errorf(`{"code":"%v","msg":"%v","sub_code":"%v","sub_msg":"%v"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
 	}
 	}
-	aliRsp.SignData = getSignData(bytes)
-	return aliRsp, nil
+	aliRsp.SignData = getSignData(bs)
+	return
 }
 }
 
 
 //向支付宝发送请求
 //向支付宝发送请求
-func (this *AliPayClient) doAliPay(body BodyMap, method string) (bytes []byte, err error) {
-	//===============转换body参数===================
-	var bodyStr string
+func (a *AliPayClient) doAliPay(body BodyMap, method string) (bytes []byte, err error) {
+	var (
+		bodyStr, sign, url, urlParam string
+		bodyBs                       []byte
+		res                          gorequest.Response
+		errs                         []error
+	)
 	if body != nil {
 	if body != nil {
-		bodyBs, err := json.Marshal(body)
-		if err != nil {
-			log.Println("json.Marshal:", err)
-			return nil, err
+		if bodyBs, err = json.Marshal(body); err != nil {
+			return nil, fmt.Errorf("json.Marshal:%v", err.Error())
 		}
 		}
 		bodyStr = string(bodyBs)
 		bodyStr = string(bodyBs)
 	}
 	}
-	//fmt.Println(string(bodyStr))
-	//===============生成参数===================
 	pubBody := make(BodyMap)
 	pubBody := make(BodyMap)
-	pubBody.Set("app_id", this.AppId)
+	pubBody.Set("app_id", a.AppId)
 	pubBody.Set("method", method)
 	pubBody.Set("method", method)
 	pubBody.Set("format", "JSON")
 	pubBody.Set("format", "JSON")
-	if this.AppCertSN != null {
-		pubBody.Set("app_cert_sn", this.AppCertSN)
+	if a.AppCertSN != null {
+		pubBody.Set("app_cert_sn", a.AppCertSN)
 	}
 	}
-	if this.AlipayRootCertSN != null {
-		pubBody.Set("alipay_root_cert_sn", this.AlipayRootCertSN)
+	if a.AlipayRootCertSN != null {
+		pubBody.Set("alipay_root_cert_sn", a.AlipayRootCertSN)
 	}
 	}
-	if this.ReturnUrl != null {
-		pubBody.Set("return_url", this.ReturnUrl)
+	if a.ReturnUrl != null {
+		pubBody.Set("return_url", a.ReturnUrl)
 	}
 	}
-	if this.Charset == null {
+	if a.Charset == null {
 		pubBody.Set("charset", "utf-8")
 		pubBody.Set("charset", "utf-8")
 	} else {
 	} else {
-		pubBody.Set("charset", this.Charset)
+		pubBody.Set("charset", a.Charset)
 	}
 	}
-	if this.SignType == null {
+	if a.SignType == null {
 		pubBody.Set("sign_type", "RSA2")
 		pubBody.Set("sign_type", "RSA2")
 	} else {
 	} else {
-		pubBody.Set("sign_type", this.SignType)
+		pubBody.Set("sign_type", a.SignType)
 	}
 	}
 	pubBody.Set("timestamp", time.Now().Format(TimeLayout))
 	pubBody.Set("timestamp", time.Now().Format(TimeLayout))
 	pubBody.Set("version", "1.0")
 	pubBody.Set("version", "1.0")
-	if this.NotifyUrl != null {
-		pubBody.Set("notify_url", this.NotifyUrl)
+	if a.NotifyUrl != null {
+		pubBody.Set("notify_url", a.NotifyUrl)
 	}
 	}
-	if this.AppAuthToken != null {
-		pubBody.Set("app_auth_token", this.AppAuthToken)
+	if a.AppAuthToken != null {
+		pubBody.Set("app_auth_token", a.AppAuthToken)
 	}
 	}
-	if this.AuthToken != null {
-		pubBody.Set("auth_token", this.AuthToken)
+	if a.AuthToken != null {
+		pubBody.Set("auth_token", a.AuthToken)
 	}
 	}
-	//fmt.Println("biz_content", string(bodyStr))
 	if bodyStr != null {
 	if bodyStr != null {
 		pubBody.Set("biz_content", bodyStr)
 		pubBody.Set("biz_content", bodyStr)
 	}
 	}
-	//===============获取签名===================
-	pKey := FormatPrivateKey(this.privateKey)
-	sign, err := getRsaSign(pubBody, pubBody.Get("sign_type"), pKey)
-	if err != nil {
-		return nil, err
+	if sign, err = getRsaSign(pubBody, pubBody.Get("sign_type"), FormatPrivateKey(a.PrivateKey)); err != nil {
+		return
 	}
 	}
 	pubBody.Set("sign", sign)
 	pubBody.Set("sign", sign)
-	//fmt.Println("rsaSign:", sign)
-	//===============发起请求===================
-	urlParam := FormatAliPayURLParam(pubBody)
-	//fmt.Println("urlParam:", urlParam)
+	urlParam = FormatAliPayURLParam(pubBody)
 	if method == "alipay.trade.app.pay" {
 	if method == "alipay.trade.app.pay" {
 		return []byte(urlParam), nil
 		return []byte(urlParam), nil
 	}
 	}
 	if method == "alipay.trade.page.pay" {
 	if method == "alipay.trade.page.pay" {
-		if !this.isProd {
-			//沙箱环境
-			return []byte(zfb_sanbox_base_url + "?" + urlParam), nil
+		if !a.IsProd {
+			return []byte(zfbSandboxBaseUrl + "?" + urlParam), nil
 		} else {
 		} else {
-			//正式环境
-			return []byte(zfb_base_url + "?" + urlParam), nil
+			return []byte(zfbBaseUrl + "?" + urlParam), nil
 		}
 		}
 	}
 	}
-	var url string
 	agent := HttpAgent()
 	agent := HttpAgent()
-	if !this.isProd {
-		//沙箱环境
-		url = zfb_sanbox_base_url_utf8
-		//fmt.Println(url)
-		agent.Post(url)
+	if !a.IsProd {
+		url = zfbSandboxBaseUrlUtf8
 	} else {
 	} else {
-		//正式环境
-		url = zfb_base_url_utf8
-		//fmt.Println(url)
-		agent.Post(url)
-	}
-	res, bs, errs := agent.
-		Type("form-data").
-		SendString(urlParam).
-		EndBytes()
-	if len(errs) > 0 {
+		url = zfbBaseUrlUtf8
+	}
+	if res, bytes, errs = agent.Post(url).Type("form-data").SendString(urlParam).EndBytes(); len(errs) > 0 {
 		return nil, errs[0]
 		return nil, errs[0]
 	}
 	}
-	//fmt.Println("res:", res.StatusCode)
 	if res.StatusCode != 200 {
 	if res.StatusCode != 200 {
 		return nil, fmt.Errorf("HTTP Request Error, StatusCode = %v", res.StatusCode)
 		return nil, fmt.Errorf("HTTP Request Error, StatusCode = %v", res.StatusCode)
 	}
 	}
 	if method == "alipay.trade.wap.pay" {
 	if method == "alipay.trade.wap.pay" {
-		//fmt.Println("rsp:::", rsp.Body)
-		if res.Request.URL.String() == zfb_sanbox_base_url || res.Request.URL.String() == zfb_base_url {
-			return nil, errors.New("请求手机网站支付出错,请检查各个参数或秘钥是否正确")
+		if res.Request.URL.String() == zfbSandboxBaseUrl || res.Request.URL.String() == zfbBaseUrl {
+			return nil, errors.New("alipay.trade.wap.pay error,please check the parameters")
 		}
 		}
 		return []byte(res.Request.URL.String()), nil
 		return []byte(res.Request.URL.String()), nil
 	}
 	}
-	return bs, nil
+	return
 }
 }
 
 
 func getSignData(bs []byte) (signData string) {
 func getSignData(bs []byte) (signData string) {

+ 17 - 6
alipay_client_test.go

@@ -71,12 +71,23 @@ func TestSubString(t *testing.T) {
 }
 }
 
 
 func TestGetCertSN(t *testing.T) {
 func TestGetCertSN(t *testing.T) {
-
 	//sn, err := GetCertSN("alipay_cert/alipayCertPublicKey_RSA2.crt")
 	//sn, err := GetCertSN("alipay_cert/alipayCertPublicKey_RSA2.crt")
 	//sn, err := GetCertSN("alipay_cert/appCertPublicKey.crt")
 	//sn, err := GetCertSN("alipay_cert/appCertPublicKey.crt")
-	//sn, err := GetCertSN("alipay_cert/alipayRootCert.crt")
-	//if err != nil {
-	//	fmt.Println("err:", err)
-	//}
-	//fmt.Println("sn:", sn)
+	sn, err := GetCertSN("alipay_cert/alipayRootCert.crt")
+	if err != nil {
+		fmt.Println("err:", err)
+		return
+	}
+	fmt.Println("sn:", sn)
+}
+
+func TestDecryptAliPayOpenDataToBodyMap(t *testing.T) {
+	data := "MkvuiIZsGOC8S038cu/JIpoRKnF+ZFjoIRGf5d/K4+ctYjCtb/eEkwgrdB5TeH/93bxff1Ylb+SE+UGStlpvcg=="
+	key := "TDftre9FpItr46e9BVNJcw=="
+	bm, err := DecryptAliPayOpenDataToBodyMap(data, key)
+	if err != nil {
+		fmt.Println("err:", err)
+		return
+	}
+	fmt.Println("bm:", bm)
 }
 }

+ 38 - 51
alipay_params.go

@@ -38,83 +38,78 @@ type OpenApiRoyaltyDetailInfoPojo struct {
 
 
 //设置 应用公钥证书SN
 //设置 应用公钥证书SN
 //    appCertSN:应用公钥证书SN,通过 gopay.GetCertSN() 获取
 //    appCertSN:应用公钥证书SN,通过 gopay.GetCertSN() 获取
-func (this *AliPayClient) SetAppCertSN(appCertSN string) (client *AliPayClient) {
-	this.AppCertSN = appCertSN
-	return this
+func (a *AliPayClient) SetAppCertSN(appCertSN string) (client *AliPayClient) {
+	a.AppCertSN = appCertSN
+	return a
 }
 }
 
 
 //设置 支付宝根证书SN
 //设置 支付宝根证书SN
 //    alipayRootCertSN:支付宝根证书SN,通过 gopay.GetCertSN() 获取
 //    alipayRootCertSN:支付宝根证书SN,通过 gopay.GetCertSN() 获取
-func (this *AliPayClient) SetAliPayRootCertSN(alipayRootCertSN string) (client *AliPayClient) {
-	this.AlipayRootCertSN = alipayRootCertSN
-	return this
+func (a *AliPayClient) SetAliPayRootCertSN(alipayRootCertSN string) (client *AliPayClient) {
+	a.AlipayRootCertSN = alipayRootCertSN
+	return a
 }
 }
 
 
 //设置支付后的ReturnUrl
 //设置支付后的ReturnUrl
-func (this *AliPayClient) SetReturnUrl(url string) (client *AliPayClient) {
-	this.ReturnUrl = url
-	return this
+func (a *AliPayClient) SetReturnUrl(url string) (client *AliPayClient) {
+	a.ReturnUrl = url
+	return a
 }
 }
 
 
 //设置支付宝服务器主动通知商户服务器里指定的页面http/https路径。
 //设置支付宝服务器主动通知商户服务器里指定的页面http/https路径。
-func (this *AliPayClient) SetNotifyUrl(url string) (client *AliPayClient) {
-	this.NotifyUrl = url
-	return this
+func (a *AliPayClient) SetNotifyUrl(url string) (client *AliPayClient) {
+	a.NotifyUrl = url
+	return a
 }
 }
 
 
 //设置编码格式,如utf-8,gbk,gb2312等,默认推荐使用 utf-8
 //设置编码格式,如utf-8,gbk,gb2312等,默认推荐使用 utf-8
-func (this *AliPayClient) SetCharset(charset string) (client *AliPayClient) {
+func (a *AliPayClient) SetCharset(charset string) (client *AliPayClient) {
 	if charset == null {
 	if charset == null {
-		this.Charset = "utf-8"
+		a.Charset = "utf-8"
 	} else {
 	} else {
-		this.Charset = charset
+		a.Charset = charset
 	}
 	}
-	return this
+	return a
 }
 }
 
 
 //设置签名算法类型,目前支持RSA2和RSA,默认推荐使用 RSA2
 //设置签名算法类型,目前支持RSA2和RSA,默认推荐使用 RSA2
-func (this *AliPayClient) SetSignType(signType string) (client *AliPayClient) {
+func (a *AliPayClient) SetSignType(signType string) (client *AliPayClient) {
 	if signType == null {
 	if signType == null {
-		this.SignType = "RSA2"
+		a.SignType = "RSA2"
 	} else {
 	} else {
-		this.SignType = signType
+		a.SignType = signType
 	}
 	}
-	return this
+	return a
 }
 }
 
 
 //设置应用授权
 //设置应用授权
-func (this *AliPayClient) SetAppAuthToken(appAuthToken string) (client *AliPayClient) {
-	this.AppAuthToken = appAuthToken
-	return this
+func (a *AliPayClient) SetAppAuthToken(appAuthToken string) (client *AliPayClient) {
+	a.AppAuthToken = appAuthToken
+	return a
 }
 }
 
 
 //设置用户信息授权
 //设置用户信息授权
-func (this *AliPayClient) SetAuthToken(authToken string) (client *AliPayClient) {
-	this.AuthToken = authToken
-	return this
+func (a *AliPayClient) SetAuthToken(authToken string) (client *AliPayClient) {
+	a.AuthToken = authToken
+	return a
 }
 }
 
 
 //获取参数签名
 //获取参数签名
 func getRsaSign(bm BodyMap, signType, privateKey string) (sign string, err error) {
 func getRsaSign(bm BodyMap, signType, privateKey string) (sign string, err error) {
 	var (
 	var (
+		block          *pem.Block
 		h              hash.Hash
 		h              hash.Hash
 		key            *rsa.PrivateKey
 		key            *rsa.PrivateKey
 		hashs          crypto.Hash
 		hashs          crypto.Hash
-		signStr        string
 		encryptedBytes []byte
 		encryptedBytes []byte
 	)
 	)
-	//解析秘钥
-	block, _ := pem.Decode([]byte(privateKey))
-	if block == nil {
-		return null, errors.New("秘钥错误")
+
+	if block, _ = pem.Decode([]byte(privateKey)); block == nil {
+		return null, errors.New("pem.Decode:privateKey decode error")
 	}
 	}
-	//log.Println(block.Type)
-	key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
-	if err != nil {
-		//log.Println("x509.ParsePKCS1PrivateKey:", err)
-		return null, err
+	if key, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
+		return
 	}
 	}
-
 	switch signType {
 	switch signType {
 	case "RSA":
 	case "RSA":
 		h = sha1.New()
 		h = sha1.New()
@@ -126,21 +121,14 @@ func getRsaSign(bm BodyMap, signType, privateKey string) (sign string, err error
 		h = sha256.New()
 		h = sha256.New()
 		hashs = crypto.SHA256
 		hashs = crypto.SHA256
 	}
 	}
-
-	//signStr = sortAliPaySignParams(bm)
-	signStr = bm.EncodeAliPaySignParams()
-	//fmt.Println("原始字符串:", signStr)
-	_, err = h.Write([]byte(signStr))
-	if err != nil {
-		return null, err
+	if _, err = h.Write([]byte(bm.EncodeAliPaySignParams())); err != nil {
+		return
 	}
 	}
-	encryptedBytes, err = rsa.SignPKCS1v15(rand.Reader, key, hashs, h.Sum(nil))
-	if err != nil {
-		//log.Println("rsa.SignPKCS1v15:", err)
-		return null, err
+	if encryptedBytes, err = rsa.SignPKCS1v15(rand.Reader, key, hashs, h.Sum(nil)); err != nil {
+		return
 	}
 	}
-	secretData := base64.StdEncoding.EncodeToString(encryptedBytes)
-	return secretData, nil
+	sign = base64.StdEncoding.EncodeToString(encryptedBytes)
+	return
 }
 }
 
 
 //格式化请求URL参数
 //格式化请求URL参数
@@ -150,6 +138,5 @@ func FormatAliPayURLParam(body BodyMap) (urlParam string) {
 		v.Add(key, value.(string))
 		v.Add(key, value.(string))
 	}
 	}
 	urlParam = v.Encode()
 	urlParam = v.Encode()
-	//fmt.Println("Encode后参数:", urlParam)
 	return
 	return
 }
 }

+ 116 - 134
alipay_service_api.go

@@ -13,13 +13,14 @@ import (
 	"encoding/pem"
 	"encoding/pem"
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
-	"github.com/tjfoc/gmsm/sm2"
 	"hash"
 	"hash"
 	"io/ioutil"
 	"io/ioutil"
 	"net/http"
 	"net/http"
 	"reflect"
 	"reflect"
 	"strings"
 	"strings"
 	"time"
 	"time"
+
+	"github.com/tjfoc/gmsm/sm2"
 )
 )
 
 
 //解析支付宝支付完成后的Notify信息
 //解析支付宝支付完成后的Notify信息
@@ -55,11 +56,9 @@ func ParseAliPayNotifyResult(req *http.Request) (notifyReq *AliPayNotifyRequest,
 	notifyReq.GmtRefund = req.FormValue("gmt_refund")
 	notifyReq.GmtRefund = req.FormValue("gmt_refund")
 	notifyReq.GmtClose = req.FormValue("gmt_close")
 	notifyReq.GmtClose = req.FormValue("gmt_close")
 	billList := req.FormValue("fund_bill_list")
 	billList := req.FormValue("fund_bill_list")
-	//log.Println("billList:", billList)
 	if billList != null {
 	if billList != null {
 		bills := make([]fundBillListInfo, 0)
 		bills := make([]fundBillListInfo, 0)
-		err = json.Unmarshal([]byte(billList), &bills)
-		if err != nil {
+		if err = json.Unmarshal([]byte(billList), &bills); err != nil {
 			return nil, fmt.Errorf("xml.Unmarshal:%v", err.Error())
 			return nil, fmt.Errorf("xml.Unmarshal:%v", err.Error())
 		}
 		}
 		notifyReq.FundBillList = bills
 		notifyReq.FundBillList = bills
@@ -68,18 +67,16 @@ func ParseAliPayNotifyResult(req *http.Request) (notifyReq *AliPayNotifyRequest,
 	}
 	}
 	notifyReq.PassbackParams = req.FormValue("passback_params")
 	notifyReq.PassbackParams = req.FormValue("passback_params")
 	detailList := req.FormValue("voucher_detail_list")
 	detailList := req.FormValue("voucher_detail_list")
-	//log.Println("detailList:", detailList)
 	if detailList != null {
 	if detailList != null {
 		details := make([]voucherDetailListInfo, 0)
 		details := make([]voucherDetailListInfo, 0)
-		err = json.Unmarshal([]byte(detailList), &details)
-		if err != nil {
+		if err = json.Unmarshal([]byte(detailList), &details); err != nil {
 			return nil, fmt.Errorf("xml.Unmarshal:%v", err.Error())
 			return nil, fmt.Errorf("xml.Unmarshal:%v", err.Error())
 		}
 		}
 		notifyReq.VoucherDetailList = details
 		notifyReq.VoucherDetailList = details
 	} else {
 	} else {
 		notifyReq.VoucherDetailList = nil
 		notifyReq.VoucherDetailList = nil
 	}
 	}
-	return notifyReq, err
+	return
 }
 }
 
 
 //支付通知的签名验证和参数签名后的Sign(Deprecated)
 //支付通知的签名验证和参数签名后的Sign(Deprecated)
@@ -121,20 +118,15 @@ func VerifyAliPayResultSign(aliPayPublicKey string, notifyReq *AliPayNotifyReque
 	body.Set("fund_bill_list", jsonToString(notifyReq.FundBillList))
 	body.Set("fund_bill_list", jsonToString(notifyReq.FundBillList))
 	body.Set("passback_params", notifyReq.PassbackParams)
 	body.Set("passback_params", notifyReq.PassbackParams)
 	body.Set("voucher_detail_list", jsonToString(notifyReq.VoucherDetailList))
 	body.Set("voucher_detail_list", jsonToString(notifyReq.VoucherDetailList))
-
 	newBody := make(BodyMap)
 	newBody := make(BodyMap)
 	for k, v := range body {
 	for k, v := range body {
 		if v != null {
 		if v != null {
 			newBody.Set(k, v)
 			newBody.Set(k, v)
 		}
 		}
 	}
 	}
-
 	pKey := FormatAliPayPublicKey(aliPayPublicKey)
 	pKey := FormatAliPayPublicKey(aliPayPublicKey)
 	signData := newBody.EncodeAliPaySignParams()
 	signData := newBody.EncodeAliPaySignParams()
-
-	//log.Println("签名字符串:", signData)
-	err = verifyAliPaySign(signData, notifyReq.Sign, notifyReq.SignType, pKey)
-	if err != nil {
+	if err = verifyAliPaySign(signData, notifyReq.Sign, notifyReq.SignType, pKey); err != nil {
 		return false, err
 		return false, err
 	}
 	}
 	return true, nil
 	return true, nil
@@ -182,32 +174,21 @@ func VerifyAliPaySign(aliPayPublicKey string, bean interface{}, syncSign ...stri
 		signData = bean.(string)
 		signData = bean.(string)
 		goto Verify
 		goto Verify
 	}
 	}
-
-	bs, err = json.Marshal(bean)
-	if err != nil {
+	if bs, err = json.Marshal(bean); err != nil {
 		return false, fmt.Errorf("json.Marshal:%v", err.Error())
 		return false, fmt.Errorf("json.Marshal:%v", err.Error())
 	}
 	}
-
 	bm = make(BodyMap)
 	bm = make(BodyMap)
-	err = json.Unmarshal(bs, &bm)
-	if err != nil {
+	if err = json.Unmarshal(bs, &bm); err != nil {
 		return false, fmt.Errorf("json.Unmarshal:%v", err.Error())
 		return false, fmt.Errorf("json.Unmarshal:%v", err.Error())
 	}
 	}
-
 	bodySign = bm.Get("sign")
 	bodySign = bm.Get("sign")
 	bodySignType = bm.Get("sign_type")
 	bodySignType = bm.Get("sign_type")
 	bm.Remove("sign")
 	bm.Remove("sign")
 	bm.Remove("sign_type")
 	bm.Remove("sign_type")
-
 	signData = bm.EncodeAliPaySignParams()
 	signData = bm.EncodeAliPaySignParams()
-
 Verify:
 Verify:
-	//fmt.Println("signData:", signData)
-	//fmt.Println("bodySign:", bodySign)
-	//fmt.Println("bodySignType:", bodySignType)
 	pKey = FormatAliPayPublicKey(aliPayPublicKey)
 	pKey = FormatAliPayPublicKey(aliPayPublicKey)
-	err = verifyAliPaySign(signData, bodySign, bodySignType, pKey)
-	if err != nil {
+	if err = verifyAliPaySign(signData, bodySign, bodySignType, pKey); err != nil {
 		return false, err
 		return false, err
 	}
 	}
 	return true, nil
 	return true, nil
@@ -215,24 +196,23 @@ Verify:
 
 
 func verifyAliPaySign(signData, sign, signType, aliPayPublicKey string) (err error) {
 func verifyAliPaySign(signData, sign, signType, aliPayPublicKey string) (err error) {
 	var (
 	var (
-		h     hash.Hash
-		hashs crypto.Hash
+		h         hash.Hash
+		hashs     crypto.Hash
+		block     *pem.Block
+		pubKey    interface{}
+		publicKey *rsa.PublicKey
+		ok        bool
 	)
 	)
 	signBytes, _ := base64.StdEncoding.DecodeString(sign)
 	signBytes, _ := base64.StdEncoding.DecodeString(sign)
-	//解析秘钥
-	block, _ := pem.Decode([]byte(aliPayPublicKey))
-	if block == nil {
+	if block, _ = pem.Decode([]byte(aliPayPublicKey)); block == nil {
 		return errors.New("支付宝公钥Decode错误")
 		return errors.New("支付宝公钥Decode错误")
 	}
 	}
-	key, err := x509.ParsePKIXPublicKey(block.Bytes)
-	if err != nil {
+	if pubKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
 		return fmt.Errorf("x509.ParsePKIXPublicKey:%v", err.Error())
 		return fmt.Errorf("x509.ParsePKIXPublicKey:%v", err.Error())
 	}
 	}
-	publicKey, ok := key.(*rsa.PublicKey)
-	if !ok {
+	if publicKey, ok = pubKey.(*rsa.PublicKey); !ok {
 		return errors.New("支付宝公钥转换错误")
 		return errors.New("支付宝公钥转换错误")
 	}
 	}
-	//判断签名方式
 	switch signType {
 	switch signType {
 	case "RSA":
 	case "RSA":
 		hashs = crypto.SHA1
 		hashs = crypto.SHA1
@@ -241,10 +221,8 @@ func verifyAliPaySign(signData, sign, signType, aliPayPublicKey string) (err err
 	default:
 	default:
 		hashs = crypto.SHA256
 		hashs = crypto.SHA256
 	}
 	}
-
 	h = hashs.New()
 	h = hashs.New()
 	h.Write([]byte(signData))
 	h.Write([]byte(signData))
-
 	return rsa.VerifyPKCS1v15(publicKey, hashs, h.Sum(nil), signBytes)
 	return rsa.VerifyPKCS1v15(publicKey, hashs, h.Sum(nil), signBytes)
 }
 }
 
 
@@ -252,28 +230,28 @@ func jsonToString(v interface{}) (str string) {
 	if v == nil {
 	if v == nil {
 		return null
 		return null
 	}
 	}
-	bs, err := json.Marshal(v)
-	if err != nil {
-		//fmt.Println("err:", err)
+	var (
+		bs  []byte
+		err error
+	)
+	if bs, err = json.Marshal(v); err != nil {
 		return null
 		return null
 	}
 	}
-	s := string(bs)
-	if s == null {
+
+	if str = string(bs); str == null {
 		return null
 		return null
 	}
 	}
-	return s
+	return
 }
 }
 
 
 //格式化 普通应用秘钥
 //格式化 普通应用秘钥
 func FormatPrivateKey(privateKey string) (pKey string) {
 func FormatPrivateKey(privateKey string) (pKey string) {
 	var buffer strings.Builder
 	var buffer strings.Builder
 	buffer.WriteString("-----BEGIN RSA PRIVATE KEY-----\n")
 	buffer.WriteString("-----BEGIN RSA PRIVATE KEY-----\n")
-
 	rawLen := 64
 	rawLen := 64
 	keyLen := len(privateKey)
 	keyLen := len(privateKey)
 	raws := keyLen / rawLen
 	raws := keyLen / rawLen
 	temp := keyLen % rawLen
 	temp := keyLen % rawLen
-
 	if temp > 0 {
 	if temp > 0 {
 		raws++
 		raws++
 	}
 	}
@@ -298,12 +276,10 @@ func FormatPrivateKey(privateKey string) (pKey string) {
 func FormatAliPayPublicKey(publicKey string) (pKey string) {
 func FormatAliPayPublicKey(publicKey string) (pKey string) {
 	var buffer strings.Builder
 	var buffer strings.Builder
 	buffer.WriteString("-----BEGIN PUBLIC KEY-----\n")
 	buffer.WriteString("-----BEGIN PUBLIC KEY-----\n")
-
 	rawLen := 64
 	rawLen := 64
 	keyLen := len(publicKey)
 	keyLen := len(publicKey)
 	raws := keyLen / rawLen
 	raws := keyLen / rawLen
 	temp := keyLen % rawLen
 	temp := keyLen % rawLen
-
 	if temp > 0 {
 	if temp > 0 {
 		raws++
 		raws++
 	}
 	}
@@ -330,128 +306,147 @@ func FormatAliPayPublicKey(publicKey string) (pKey string) {
 //    返回 err:error 信息
 //    返回 err:error 信息
 func GetCertSN(certPath string) (sn string, err error) {
 func GetCertSN(certPath string) (sn string, err error) {
 	var (
 	var (
-		certData []byte
+		certData           []byte
+		block              *pem.Block
+		certs              []*x509.Certificate
+		sm2Certs           []*sm2.Certificate
+		name, serialNumber string
+		h                  hash.Hash
 	)
 	)
 	if certData, err = ioutil.ReadFile(certPath); err != nil {
 	if certData, err = ioutil.ReadFile(certPath); err != nil {
 		return null, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
 		return null, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
 	}
 	}
-	block, _ := pem.Decode(certData)
-	if block == nil {
-		return null, errors.New("x509.ParseCertificates:pem Decode error block is null")
+	if block, _ = pem.Decode(certData); block == nil {
+		return null, errors.New("pem.Decode:pem Decode error,block is null")
 	}
 	}
-	var (
-		certs        []*x509.Certificate
-		sm2Certs     []*sm2.Certificate
-		name         string
-		serialNumber string
-	)
-	certs, err = x509.ParseCertificates(block.Bytes)
-	if err != nil {
-		sm2Certs, err = sm2.ParseCertificates(block.Bytes)
-		if err != nil {
+	if certs, err = x509.ParseCertificates(block.Bytes); err != nil {
+		if sm2Certs, err = sm2.ParseCertificates(block.Bytes); err != nil {
 			return null, fmt.Errorf("sm2.ParseCertificates:%v", err.Error())
 			return null, fmt.Errorf("sm2.ParseCertificates:%v", err.Error())
 		}
 		}
-	}
-	if certs != nil {
-		name = certs[0].Issuer.String()
-		serialNumber = certs[0].SerialNumber.String()
-	} else {
 		name = sm2Certs[0].Issuer.String()
 		name = sm2Certs[0].Issuer.String()
 		serialNumber = sm2Certs[0].SerialNumber.String()
 		serialNumber = sm2Certs[0].SerialNumber.String()
-	}
-	//fmt.Println("Name:", name)
-	//fmt.Println("SerialNumber:", serialNumber)
-	m5 := md5.New()
-	m5.Write([]byte(name))
-	m5.Write([]byte(serialNumber))
-	sum := m5.Sum(nil)
-	sn = hex.EncodeToString(sum)
+		goto Sign
+	}
+	if certs == nil {
+		return null, fmt.Errorf("x509.ParseCertificates:certs is null")
+	}
+	name = certs[0].Issuer.String()
+	serialNumber = certs[0].SerialNumber.String()
+Sign:
+	h = md5.New()
+	h.Write([]byte(name))
+	h.Write([]byte(serialNumber))
+	sn = hex.EncodeToString(h.Sum(nil))
 	return sn, nil
 	return sn, nil
 }
 }
 
 
-//解密支付宝开放数据
+//解密支付宝开放数据到 结构体
 //    encryptedData:包括敏感数据在内的完整用户信息的加密数据
 //    encryptedData:包括敏感数据在内的完整用户信息的加密数据
 //    secretKey:AES密钥,支付宝管理平台配置
 //    secretKey:AES密钥,支付宝管理平台配置
 //    beanPtr:需要解析到的结构体指针
 //    beanPtr:需要解析到的结构体指针
 //    文档:https://docs.alipay.com/mini/introduce/aes
 //    文档:https://docs.alipay.com/mini/introduce/aes
 //    文档:https://docs.open.alipay.com/common/104567
 //    文档:https://docs.open.alipay.com/common/104567
 func DecryptAliPayOpenDataToStruct(encryptedData, secretKey string, beanPtr interface{}) (err error) {
 func DecryptAliPayOpenDataToStruct(encryptedData, secretKey string, beanPtr interface{}) (err error) {
-	//验证参数类型
 	beanValue := reflect.ValueOf(beanPtr)
 	beanValue := reflect.ValueOf(beanPtr)
 	if beanValue.Kind() != reflect.Ptr {
 	if beanValue.Kind() != reflect.Ptr {
 		return errors.New("传入参数类型必须是以指针形式")
 		return errors.New("传入参数类型必须是以指针形式")
 	}
 	}
-	//验证interface{}类型
 	if beanValue.Elem().Kind() != reflect.Struct {
 	if beanValue.Elem().Kind() != reflect.Struct {
 		return errors.New("传入interface{}必须是结构体")
 		return errors.New("传入interface{}必须是结构体")
 	}
 	}
+	var (
+		block      cipher.Block
+		blockMode  cipher.BlockMode
+		originData []byte
+	)
 	aesKey, _ := base64.StdEncoding.DecodeString(secretKey)
 	aesKey, _ := base64.StdEncoding.DecodeString(secretKey)
 	ivKey := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
 	ivKey := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
 	secretData, _ := base64.StdEncoding.DecodeString(encryptedData)
 	secretData, _ := base64.StdEncoding.DecodeString(encryptedData)
-
-	block, err := aes.NewCipher(aesKey)
-	if err != nil {
+	if block, err = aes.NewCipher(aesKey); err != nil {
 		return fmt.Errorf("aes.NewCipher:%v", err.Error())
 		return fmt.Errorf("aes.NewCipher:%v", err.Error())
 	}
 	}
 	if len(secretData)%len(aesKey) != 0 {
 	if len(secretData)%len(aesKey) != 0 {
 		return errors.New("encryptedData is error")
 		return errors.New("encryptedData is error")
 	}
 	}
-
-	blockMode := cipher.NewCBCDecrypter(block, ivKey)
-	originData := make([]byte, len(secretData))
+	blockMode = cipher.NewCBCDecrypter(block, ivKey)
+	originData = make([]byte, len(secretData))
 	blockMode.CryptBlocks(originData, secretData)
 	blockMode.CryptBlocks(originData, secretData)
-
 	if len(originData) > 0 {
 	if len(originData) > 0 {
 		originData = PKCS5UnPadding(originData)
 		originData = PKCS5UnPadding(originData)
 	}
 	}
-	//fmt.Println("originDataStr:", string(originData))
-	//解析
-	err = json.Unmarshal(originData, beanPtr)
-	if err != nil {
+	if err = json.Unmarshal(originData, beanPtr); err != nil {
 		return fmt.Errorf("json.Unmarshal:%v", err.Error())
 		return fmt.Errorf("json.Unmarshal:%v", err.Error())
 	}
 	}
 	return nil
 	return nil
 }
 }
 
 
+//解密支付宝开放数据到 BodyMap
+//    encryptedData:包括敏感数据在内的完整用户信息的加密数据
+//    secretKey:AES密钥,支付宝管理平台配置
+//    文档:https://docs.alipay.com/mini/introduce/aes
+//    文档:https://docs.open.alipay.com/common/104567
+func DecryptAliPayOpenDataToBodyMap(encryptedData, secretKey string) (bm BodyMap, err error) {
+	var (
+		aesKey, originData []byte
+		ivKey              = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+		block              cipher.Block
+		blockMode          cipher.BlockMode
+	)
+	aesKey, _ = base64.StdEncoding.DecodeString(secretKey)
+	secretData, _ := base64.StdEncoding.DecodeString(encryptedData)
+	if block, err = aes.NewCipher(aesKey); err != nil {
+		return nil, fmt.Errorf("aes.NewCipher:%v", err.Error())
+	}
+	if len(secretData)%len(aesKey) != 0 {
+		return nil, errors.New("encryptedData is error")
+	}
+	blockMode = cipher.NewCBCDecrypter(block, ivKey)
+	originData = make([]byte, len(secretData))
+	blockMode.CryptBlocks(originData, secretData)
+	if len(originData) > 0 {
+		originData = PKCS5UnPadding(originData)
+	}
+	bm = make(BodyMap)
+	if err = json.Unmarshal(originData, &bm); err != nil {
+		return nil, fmt.Errorf("json.Unmarshal:%v", err.Error())
+	}
+	return
+}
+
 //换取授权访问令牌(默认使用utf-8,RSA2)
 //换取授权访问令牌(默认使用utf-8,RSA2)
 //    appId:应用ID
 //    appId:应用ID
-//    privateKey:应用私钥
+//    PrivateKey:应用私钥
 //    grantType:值为 authorization_code 时,代表用code换取;值为 refresh_token 时,代表用refresh_token换取,传空默认code换取
 //    grantType:值为 authorization_code 时,代表用code换取;值为 refresh_token 时,代表用refresh_token换取,传空默认code换取
 //    codeOrToken:支付宝授权码或refresh_token
 //    codeOrToken:支付宝授权码或refresh_token
 //    文档:https://docs.open.alipay.com/api_9/alipay.system.oauth.token
 //    文档:https://docs.open.alipay.com/api_9/alipay.system.oauth.token
 func AliPaySystemOauthToken(appId, privateKey, grantType, codeOrToken string) (rsp *AliPaySystemOauthTokenResponse, err error) {
 func AliPaySystemOauthToken(appId, privateKey, grantType, codeOrToken string) (rsp *AliPaySystemOauthTokenResponse, err error) {
 	var bs []byte
 	var bs []byte
-	body := make(BodyMap)
+	bm := make(BodyMap)
 	if "authorization_code" == grantType {
 	if "authorization_code" == grantType {
-		body.Set("grant_type", "authorization_code")
-		body.Set("code", codeOrToken)
+		bm.Set("grant_type", "authorization_code")
+		bm.Set("code", codeOrToken)
 	} else if "refresh_token" == grantType {
 	} else if "refresh_token" == grantType {
-		body.Set("grant_type", "refresh_token")
-		body.Set("refresh_token", codeOrToken)
+		bm.Set("grant_type", "refresh_token")
+		bm.Set("refresh_token", codeOrToken)
 	} else {
 	} else {
-		body.Set("grant_type", "authorization_code")
-		body.Set("code", codeOrToken)
+		bm.Set("grant_type", "authorization_code")
+		bm.Set("code", codeOrToken)
 	}
 	}
-	bs, err = aliPaySystemOauthToken(appId, privateKey, body, "alipay.system.oauth.token", true)
-	if err != nil {
-		return nil, err
+	if bs, err = aliPaySystemOauthToken(appId, privateKey, bm, "alipay.system.oauth.token", true); err != nil {
+		return
 	}
 	}
-	//fmt.Println("bs:", string(bs))
 	rsp = new(AliPaySystemOauthTokenResponse)
 	rsp = new(AliPaySystemOauthTokenResponse)
-	err = json.Unmarshal(bs, rsp)
-	if err != nil {
+	if err = json.Unmarshal(bs, rsp); err != nil {
 		return nil, fmt.Errorf("json.Unmarshal:%v", err.Error())
 		return nil, fmt.Errorf("json.Unmarshal:%v", err.Error())
 	}
 	}
-	if rsp.AliPaySystemOauthTokenResponse.AccessToken != "" {
-		return rsp, nil
-	} else {
-		return
+	if rsp.AliPaySystemOauthTokenResponse.AccessToken == "" {
+		return nil, errors.New("access_token is null")
 	}
 	}
+	return
 }
 }
 
 
 //向支付宝发送请求
 //向支付宝发送请求
 func aliPaySystemOauthToken(appId, privateKey string, body BodyMap, method string, isProd bool) (bytes []byte, err error) {
 func aliPaySystemOauthToken(appId, privateKey string, body BodyMap, method string, isProd bool) (bytes []byte, err error) {
-	//===============生成参数===================
 	body.Set("app_id", appId)
 	body.Set("app_id", appId)
 	body.Set("method", method)
 	body.Set("method", method)
 	body.Set("format", "JSON")
 	body.Set("format", "JSON")
@@ -459,36 +454,23 @@ func aliPaySystemOauthToken(appId, privateKey string, body BodyMap, method strin
 	body.Set("sign_type", "RSA2")
 	body.Set("sign_type", "RSA2")
 	body.Set("timestamp", time.Now().Format(TimeLayout))
 	body.Set("timestamp", time.Now().Format(TimeLayout))
 	body.Set("version", "1.0")
 	body.Set("version", "1.0")
-	//===============获取签名===================
+	var (
+		sign, url string
+		errs      []error
+	)
 	pKey := FormatPrivateKey(privateKey)
 	pKey := FormatPrivateKey(privateKey)
-	sign, err := getRsaSign(body, "RSA2", pKey)
-	if err != nil {
-		return nil, err
+	if sign, err = getRsaSign(body, "RSA2", pKey); err != nil {
+		return
 	}
 	}
 	body.Set("sign", sign)
 	body.Set("sign", sign)
-	//fmt.Println("rsaSign:", sign)
-	//===============发起请求===================
-	urlParam := FormatAliPayURLParam(body)
-
-	var url string
 	agent := HttpAgent()
 	agent := HttpAgent()
 	if !isProd {
 	if !isProd {
-		//沙箱环境
-		url = zfb_sanbox_base_url_utf8
-		//fmt.Println(url)
-		agent.Post(url)
+		url = zfbSandboxBaseUrlUtf8
 	} else {
 	} else {
-		//正式环境
-		url = zfb_base_url_utf8
-		//fmt.Println(url)
-		agent.Post(url)
-	}
-	_, bs, errs := agent.
-		Type("form-data").
-		SendString(urlParam).
-		EndBytes()
-	if len(errs) > 0 {
+		url = zfbBaseUrlUtf8
+	}
+	if _, bytes, errs = agent.Post(url).Type("form-data").SendString(FormatAliPayURLParam(body)).EndBytes(); len(errs) > 0 {
 		return nil, errs[0]
 		return nil, errs[0]
 	}
 	}
-	return bs, nil
+	return
 }
 }

+ 30 - 31
constant.go

@@ -15,37 +15,36 @@ const (
 	Other         Country = 4 //其他国家
 	Other         Country = 4 //其他国家
 
 
 	//URL
 	//URL
-	wx_base_url_ch  = "https://api.mch.weixin.qq.com/"   //中国国内
-	wx_base_url_ch2 = "https://api2.mch.weixin.qq.com/"  //中国国内
-	wx_base_url_hk  = "https://apihk.mch.weixin.qq.com/" //东南亚
-	wx_base_url_us  = "https://apius.mch.weixin.qq.com/" //其他
+	wxBaseUrlCh  = "https://api.mch.weixin.qq.com/"   //中国国内
+	wxBaseUrlCh2 = "https://api2.mch.weixin.qq.com/"  //中国国内
+	wxBaseUrlHk  = "https://apihk.mch.weixin.qq.com/" //东南亚
+	wxBaseUrlUs  = "https://apius.mch.weixin.qq.com/" //其他
 
 
 	//正式
 	//正式
-	wx_Micropay          = "pay/micropay"                          //提交付款码支付
-	wx_UnifiedOrder      = "pay/unifiedorder"                      //统一下单
-	wx_OrderQuery        = "pay/orderquery"                        //查询订单
-	wx_CloseOrder        = "pay/closeorder"                        //关闭订单
-	wx_Refund            = "secapi/pay/refund"                     //申请退款
-	wx_Reverse           = "secapi/pay/reverse"                    //撤销订单
-	wx_RefundQuery       = "pay/refundquery"                       //查询退款
-	wx_DownloadBill      = "pay/downloadbill"                      //下载对账单
-	wx_DownloadFundFlow  = "pay/downloadfundflow"                  //下载资金账单
-	wx_BatchQueryComment = "billcommentsp/batchquerycomment"       //拉取订单评价数据
-	wx_Transfers         = "mmpaymkttransfers/promotion/transfers" //企业向微信用户个人付款
+	wxMicropay          = "pay/micropay"                          //提交付款码支付
+	wxUnifiedorder      = "pay/unifiedorder"                      //统一下单
+	wxOrderquery        = "pay/orderquery"                        //查询订单
+	wxCloseorder        = "pay/closeorder"                        //关闭订单
+	wxRefund            = "secapi/pay/refund"                     //申请退款
+	wxReverse           = "secapi/pay/reverse"                    //撤销订单
+	wxRefundquery       = "pay/refundquery"                       //查询退款
+	wxDownloadbill      = "pay/downloadbill"                      //下载对账单
+	wxDownloadfundflow  = "pay/downloadfundflow"                  //下载资金账单
+	wxBatchquerycomment = "billcommentsp/batchquerycomment"       //拉取订单评价数据
+	wxTransfers         = "mmpaymkttransfers/promotion/transfers" //企业向微信用户个人付款
 
 
 	//SanBox
 	//SanBox
-	wx_SanBox_GetSignKey        = "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey"
-	wx_SanBox_Micropay          = "sandboxnew/pay/micropay"
-	wx_SanBox_UnifiedOrder      = "sandboxnew/pay/unifiedorder"
-	wx_SanBox_OrderQuery        = "sandboxnew/pay/orderquery"
-	wx_SanBox_CloseOrder        = "sandboxnew/pay/closeorder"
-	wx_SanBox_Refund            = "sandboxnew/pay/refund"
-	wx_SanBox_Reverse           = "sandboxnew/pay/reverse"
-	wx_SanBox_RefundQuery       = "sandboxnew/pay/refundquery"
-	wx_SanBox_DownloadBill      = "sandboxnew/pay/downloadbill"
-	wx_SanBox_DownloadFundFlow  = "sandboxnew/pay/downloadfundflow"
-	wx_SanBox_BatchQueryComment = "sandboxnew/billcommentsp/batchquerycomment"
-	wx_SanBox_Transfers         = "sandboxnew/mmpaymkttransfers/promotion/transfers"
+	wxSandboxGetsignkey        = "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey"
+	wxSandboxMicropay          = "sandboxnew/pay/micropay"
+	wxSandboxUnifiedorder      = "sandboxnew/pay/unifiedorder"
+	wxSandboxOrderquery        = "sandboxnew/pay/orderquery"
+	wxSandboxCloseorder        = "sandboxnew/pay/closeorder"
+	wxSandboxRefund            = "sandboxnew/pay/refund"
+	wxSandboxReverse           = "sandboxnew/pay/reverse"
+	wxSandboxRefundquery       = "sandboxnew/pay/refundquery"
+	wxSandboxDownloadbill      = "sandboxnew/pay/downloadbill"
+	wxSandboxDownloadfundflow  = "sandboxnew/pay/downloadfundflow"
+	wxSandboxBatchquerycomment = "sandboxnew/billcommentsp/batchquerycomment"
 
 
 	//支付类型
 	//支付类型
 	TradeType_Mini   = "JSAPI"
 	TradeType_Mini   = "JSAPI"
@@ -62,8 +61,8 @@ const (
 	//===========================================================================================
 	//===========================================================================================
 
 
 	//URL
 	//URL
-	zfb_base_url             = "https://openapi.alipay.com/gateway.do"
-	zfb_sanbox_base_url      = "https://openapi.alipaydev.com/gateway.do"
-	zfb_base_url_utf8        = "https://openapi.alipay.com/gateway.do?charset=utf-8"
-	zfb_sanbox_base_url_utf8 = "https://openapi.alipaydev.com/gateway.do?charset=utf-8"
+	zfbBaseUrl            = "https://openapi.alipay.com/gateway.do"
+	zfbSandboxBaseUrl     = "https://openapi.alipaydev.com/gateway.do"
+	zfbBaseUrlUtf8        = "https://openapi.alipay.com/gateway.do?charset=utf-8"
+	zfbSandboxBaseUrlUtf8 = "https://openapi.alipaydev.com/gateway.do?charset=utf-8"
 )
 )

+ 48 - 48
wechat_client.go

@@ -15,32 +15,32 @@ import (
 type WeChatClient struct {
 type WeChatClient struct {
 	AppId   string
 	AppId   string
 	MchId   string
 	MchId   string
-	apiKey  string
-	baseURL string
-	isProd  bool
+	ApiKey  string
+	BaseURL string
+	IsProd  bool
 }
 }
 
 
 //初始化微信客户端 ok
 //初始化微信客户端 ok
 //    appId:应用ID
 //    appId:应用ID
 //    mchId:商户ID
 //    mchId:商户ID
-//    apiKey:API秘钥值
-//    isProd:是否是正式环境
+//    ApiKey:API秘钥值
+//    IsProd:是否是正式环境
 func NewWeChatClient(appId, mchId, apiKey string, isProd bool) (client *WeChatClient) {
 func NewWeChatClient(appId, mchId, apiKey string, isProd bool) (client *WeChatClient) {
 	return &WeChatClient{
 	return &WeChatClient{
 		AppId:  appId,
 		AppId:  appId,
 		MchId:  mchId,
 		MchId:  mchId,
-		apiKey: apiKey,
-		isProd: isProd}
+		ApiKey: apiKey,
+		IsProd: isProd}
 }
 }
 
 
 //提交付款码支付 ok
 //提交付款码支付 ok
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_10&index=1
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_10&index=1
 func (w *WeChatClient) Micropay(body BodyMap) (wxRsp *WeChatMicropayResponse, err error) {
 func (w *WeChatClient) Micropay(body BodyMap) (wxRsp *WeChatMicropayResponse, err error) {
 	var bs []byte
 	var bs []byte
-	if w.isProd {
-		bs, err = w.doWeChat(body, wx_Micropay)
+	if w.IsProd {
+		bs, err = w.doWeChat(body, wxMicropay)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_Micropay)
+		bs, err = w.doWeChat(body, wxSandboxMicropay)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -56,11 +56,11 @@ func (w *WeChatClient) Micropay(body BodyMap) (wxRsp *WeChatMicropayResponse, er
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
 func (w *WeChatClient) UnifiedOrder(body BodyMap) (wxRsp *WeChatUnifiedOrderResponse, err error) {
 func (w *WeChatClient) UnifiedOrder(body BodyMap) (wxRsp *WeChatUnifiedOrderResponse, err error) {
 	var bs []byte
 	var bs []byte
-	if w.isProd {
-		bs, err = w.doWeChat(body, wx_UnifiedOrder)
+	if w.IsProd {
+		bs, err = w.doWeChat(body, wxUnifiedorder)
 	} else {
 	} else {
 		body.Set("total_fee", 101)
 		body.Set("total_fee", 101)
-		bs, err = w.doWeChat(body, wx_SanBox_UnifiedOrder)
+		bs, err = w.doWeChat(body, wxSandboxUnifiedorder)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -76,10 +76,10 @@ func (w *WeChatClient) UnifiedOrder(body BodyMap) (wxRsp *WeChatUnifiedOrderResp
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
 func (w *WeChatClient) QueryOrder(body BodyMap) (wxRsp *WeChatQueryOrderResponse, err error) {
 func (w *WeChatClient) QueryOrder(body BodyMap) (wxRsp *WeChatQueryOrderResponse, err error) {
 	var bs []byte
 	var bs []byte
-	if w.isProd {
-		bs, err = w.doWeChat(body, wx_OrderQuery)
+	if w.IsProd {
+		bs, err = w.doWeChat(body, wxOrderquery)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_OrderQuery)
+		bs, err = w.doWeChat(body, wxSandboxOrderquery)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -95,10 +95,10 @@ func (w *WeChatClient) QueryOrder(body BodyMap) (wxRsp *WeChatQueryOrderResponse
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_3
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_3
 func (w *WeChatClient) CloseOrder(body BodyMap) (wxRsp *WeChatCloseOrderResponse, err error) {
 func (w *WeChatClient) CloseOrder(body BodyMap) (wxRsp *WeChatCloseOrderResponse, err error) {
 	var bs []byte
 	var bs []byte
-	if w.isProd {
-		bs, err = w.doWeChat(body, wx_CloseOrder)
+	if w.IsProd {
+		bs, err = w.doWeChat(body, wxCloseorder)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_CloseOrder)
+		bs, err = w.doWeChat(body, wxSandboxCloseorder)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -119,7 +119,7 @@ func (w *WeChatClient) Reverse(body BodyMap, certFilePath, keyFilePath, pkcs12Fi
 		certificate tls.Certificate
 		certificate tls.Certificate
 		tlsConfig   *tls.Config
 		tlsConfig   *tls.Config
 	)
 	)
-	if w.isProd {
+	if w.IsProd {
 		pkcsPool = x509.NewCertPool()
 		pkcsPool = x509.NewCertPool()
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 			return nil, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
 			return nil, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
@@ -132,9 +132,9 @@ func (w *WeChatClient) Reverse(body BodyMap, certFilePath, keyFilePath, pkcs12Fi
 			Certificates:       []tls.Certificate{certificate},
 			Certificates:       []tls.Certificate{certificate},
 			RootCAs:            pkcsPool,
 			RootCAs:            pkcsPool,
 			InsecureSkipVerify: true}
 			InsecureSkipVerify: true}
-		bs, err = w.doWeChat(body, wx_Reverse, tlsConfig)
+		bs, err = w.doWeChat(body, wxReverse, tlsConfig)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_Reverse)
+		bs, err = w.doWeChat(body, wxSandboxReverse)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -155,7 +155,7 @@ func (w *WeChatClient) Refund(body BodyMap, certFilePath, keyFilePath, pkcs12Fil
 		certificate tls.Certificate
 		certificate tls.Certificate
 		tlsConfig   *tls.Config
 		tlsConfig   *tls.Config
 	)
 	)
-	if w.isProd {
+	if w.IsProd {
 		pkcsPool = x509.NewCertPool()
 		pkcsPool = x509.NewCertPool()
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 			return nil, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
 			return nil, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
@@ -168,9 +168,9 @@ func (w *WeChatClient) Refund(body BodyMap, certFilePath, keyFilePath, pkcs12Fil
 			Certificates:       []tls.Certificate{certificate},
 			Certificates:       []tls.Certificate{certificate},
 			RootCAs:            pkcsPool,
 			RootCAs:            pkcsPool,
 			InsecureSkipVerify: true}
 			InsecureSkipVerify: true}
-		bs, err = w.doWeChat(body, wx_Refund, tlsConfig)
+		bs, err = w.doWeChat(body, wxRefund, tlsConfig)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_Refund)
+		bs, err = w.doWeChat(body, wxSandboxRefund)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -186,10 +186,10 @@ func (w *WeChatClient) Refund(body BodyMap, certFilePath, keyFilePath, pkcs12Fil
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_5
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_5
 func (w *WeChatClient) QueryRefund(body BodyMap) (wxRsp *WeChatQueryRefundResponse, err error) {
 func (w *WeChatClient) QueryRefund(body BodyMap) (wxRsp *WeChatQueryRefundResponse, err error) {
 	var bs []byte
 	var bs []byte
-	if w.isProd {
-		bs, err = w.doWeChat(body, wx_RefundQuery)
+	if w.IsProd {
+		bs, err = w.doWeChat(body, wxRefundquery)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_RefundQuery)
+		bs, err = w.doWeChat(body, wxSandboxRefundquery)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -205,10 +205,10 @@ func (w *WeChatClient) QueryRefund(body BodyMap) (wxRsp *WeChatQueryRefundRespon
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_6
 //    文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_6
 func (w *WeChatClient) DownloadBill(body BodyMap) (wxRsp string, err error) {
 func (w *WeChatClient) DownloadBill(body BodyMap) (wxRsp string, err error) {
 	var bs []byte
 	var bs []byte
-	if w.isProd {
-		bs, err = w.doWeChat(body, wx_DownloadBill)
+	if w.IsProd {
+		bs, err = w.doWeChat(body, wxDownloadbill)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_DownloadBill)
+		bs, err = w.doWeChat(body, wxSandboxDownloadbill)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -227,7 +227,7 @@ func (w *WeChatClient) DownloadFundFlow(body BodyMap, certFilePath, keyFilePath,
 		certificate tls.Certificate
 		certificate tls.Certificate
 		tlsConfig   *tls.Config
 		tlsConfig   *tls.Config
 	)
 	)
-	if w.isProd {
+	if w.IsProd {
 		pkcsPool = x509.NewCertPool()
 		pkcsPool = x509.NewCertPool()
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 			return null, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
 			return null, fmt.Errorf("ioutil.ReadFile:%v", err.Error())
@@ -240,9 +240,9 @@ func (w *WeChatClient) DownloadFundFlow(body BodyMap, certFilePath, keyFilePath,
 			Certificates:       []tls.Certificate{certificate},
 			Certificates:       []tls.Certificate{certificate},
 			RootCAs:            pkcsPool,
 			RootCAs:            pkcsPool,
 			InsecureSkipVerify: true}
 			InsecureSkipVerify: true}
-		bs, err = w.doWeChat(body, wx_DownloadFundFlow, tlsConfig)
+		bs, err = w.doWeChat(body, wxDownloadfundflow, tlsConfig)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_DownloadFundFlow)
+		bs, err = w.doWeChat(body, wxSandboxDownloadfundflow)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -261,7 +261,7 @@ func (w *WeChatClient) BatchQueryComment(body BodyMap, certFilePath, keyFilePath
 		certificate tls.Certificate
 		certificate tls.Certificate
 		tlsConfig   *tls.Config
 		tlsConfig   *tls.Config
 	)
 	)
-	if w.isProd {
+	if w.IsProd {
 		body.Set("sign_type", SignType_HMAC_SHA256)
 		body.Set("sign_type", SignType_HMAC_SHA256)
 		pkcsPool = x509.NewCertPool()
 		pkcsPool = x509.NewCertPool()
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
 		if pkcs, err = ioutil.ReadFile(pkcs12FilePath); err != nil {
@@ -275,9 +275,9 @@ func (w *WeChatClient) BatchQueryComment(body BodyMap, certFilePath, keyFilePath
 			Certificates:       []tls.Certificate{certificate},
 			Certificates:       []tls.Certificate{certificate},
 			RootCAs:            pkcsPool,
 			RootCAs:            pkcsPool,
 			InsecureSkipVerify: true}
 			InsecureSkipVerify: true}
-		bs, err = w.doWeChat(body, wx_BatchQueryComment, tlsConfig)
+		bs, err = w.doWeChat(body, wxBatchquerycomment, tlsConfig)
 	} else {
 	} else {
-		bs, err = w.doWeChat(body, wx_SanBox_BatchQueryComment)
+		bs, err = w.doWeChat(body, wxSandboxBatchquerycomment)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		return
 		return
@@ -313,12 +313,12 @@ func (w *WeChatClient) Transfer(body BodyMap, certFilePath, keyFilePath, pkcs12F
 		Certificates:       []tls.Certificate{certificate},
 		Certificates:       []tls.Certificate{certificate},
 		RootCAs:            pkcsPool,
 		RootCAs:            pkcsPool,
 		InsecureSkipVerify: true}
 		InsecureSkipVerify: true}
-	body.Set("sign", getWeChatReleaseSign(w.apiKey, SignType_MD5, body))
+	body.Set("sign", getWeChatReleaseSign(w.ApiKey, SignType_MD5, body))
 	agent = HttpAgent().TLSClientConfig(tlsConfig)
 	agent = HttpAgent().TLSClientConfig(tlsConfig)
-	if w.baseURL != null {
-		agent.Post(w.baseURL + wx_Transfers)
+	if w.BaseURL != null {
+		agent.Post(w.BaseURL + wxTransfers)
 	} else {
 	} else {
-		agent.Post(wx_base_url_ch + wx_Transfers)
+		agent.Post(wxBaseUrlCh + wxTransfers)
 	}
 	}
 	if res, bs, errs = agent.Type("xml").SendString(generateXml(body)).EndBytes(); len(errs) > 0 {
 	if res, bs, errs = agent.Type("xml").SendString(generateXml(body)).EndBytes(); len(errs) > 0 {
 		return nil, errs[0]
 		return nil, errs[0]
@@ -345,24 +345,24 @@ func (w *WeChatClient) doWeChat(body BodyMap, path string, tlsConfig ...*tls.Con
 	if body.Get("sign") != null {
 	if body.Get("sign") != null {
 		goto GoRequest
 		goto GoRequest
 	}
 	}
-	if !w.isProd {
+	if !w.IsProd {
 		body.Set("sign_type", SignType_MD5)
 		body.Set("sign_type", SignType_MD5)
-		if sign, err = getWeChatSignBoxSign(w.MchId, w.apiKey, body); err != nil {
+		if sign, err = getWeChatSignBoxSign(w.MchId, w.ApiKey, body); err != nil {
 			return
 			return
 		}
 		}
 	} else {
 	} else {
-		sign = getWeChatReleaseSign(w.apiKey, body.Get("sign_type"), body)
+		sign = getWeChatReleaseSign(w.ApiKey, body.Get("sign_type"), body)
 	}
 	}
 	body.Set("sign", sign)
 	body.Set("sign", sign)
 GoRequest:
 GoRequest:
 	agent := HttpAgent()
 	agent := HttpAgent()
-	if w.isProd && tlsConfig != nil {
+	if w.IsProd && tlsConfig != nil {
 		agent.TLSClientConfig(tlsConfig[0])
 		agent.TLSClientConfig(tlsConfig[0])
 	}
 	}
-	if w.baseURL != null {
-		agent.Post(w.baseURL + path)
+	if w.BaseURL != null {
+		agent.Post(w.BaseURL + path)
 	} else {
 	} else {
-		agent.Post(wx_base_url_ch + path)
+		agent.Post(wxBaseUrlCh + path)
 	}
 	}
 	if res, bytes, errs = agent.Type("xml").SendString(generateXml(body)).EndBytes(); len(errs) > 0 {
 	if res, bytes, errs = agent.Type("xml").SendString(generateXml(body)).EndBytes(); len(errs) > 0 {
 		return nil, errs[0]
 		return nil, errs[0]

+ 10 - 10
wechat_params.go

@@ -19,15 +19,15 @@ type Country int
 func (w *WeChatClient) SetCountry(country Country) (client *WeChatClient) {
 func (w *WeChatClient) SetCountry(country Country) (client *WeChatClient) {
 	switch country {
 	switch country {
 	case China:
 	case China:
-		w.baseURL = wx_base_url_ch
+		w.BaseURL = wxBaseUrlCh
 	case China2:
 	case China2:
-		w.baseURL = wx_base_url_ch2
+		w.BaseURL = wxBaseUrlCh2
 	case SoutheastAsia:
 	case SoutheastAsia:
-		w.baseURL = wx_base_url_hk
+		w.BaseURL = wxBaseUrlHk
 	case Other:
 	case Other:
-		w.baseURL = wx_base_url_us
+		w.BaseURL = wxBaseUrlUs
 	default:
 	default:
-		w.baseURL = wx_base_url_ch
+		w.BaseURL = wxBaseUrlCh
 	}
 	}
 	return w
 	return w
 }
 }
@@ -48,14 +48,14 @@ func getWeChatReleaseSign(apiKey string, signType string, bm BodyMap) (sign stri
 //获取微信支付沙箱环境Sign值
 //获取微信支付沙箱环境Sign值
 func getWeChatSignBoxSign(mchId, apiKey string, bm BodyMap) (sign string, err error) {
 func getWeChatSignBoxSign(mchId, apiKey string, bm BodyMap) (sign string, err error) {
 	var (
 	var (
-		sanBoxApiKey string
-		h            hash.Hash
+		sandBoxApiKey string
+		h             hash.Hash
 	)
 	)
-	if sanBoxApiKey, err = getSanBoxKey(mchId, GetRandomString(32), apiKey, SignType_MD5); err != nil {
+	if sandBoxApiKey, err = getSanBoxKey(mchId, GetRandomString(32), apiKey, SignType_MD5); err != nil {
 		return
 		return
 	}
 	}
 	h = md5.New()
 	h = md5.New()
-	h.Write([]byte(bm.EncodeWeChatSignParams(sanBoxApiKey)))
+	h.Write([]byte(bm.EncodeWeChatSignParams(sandBoxApiKey)))
 	sign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
 	sign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
 	return
 	return
 }
 }
@@ -83,7 +83,7 @@ func getSanBoxSignKey(mchId, nonceStr, sign string) (key string, err error) {
 		errorList   []error
 		errorList   []error
 		keyResponse *getSignKeyResponse
 		keyResponse *getSignKeyResponse
 	)
 	)
-	if _, byteList, errorList = HttpAgent().Post(wx_SanBox_GetSignKey).Type("xml").SendString(generateXml(reqs)).EndBytes(); len(errorList) > 0 {
+	if _, byteList, errorList = HttpAgent().Post(wxSandboxGetsignkey).Type("xml").SendString(generateXml(reqs)).EndBytes(); len(errorList) > 0 {
 		return null, errorList[0]
 		return null, errorList[0]
 	}
 	}
 	keyResponse = new(getSignKeyResponse)
 	keyResponse = new(getSignKeyResponse)

+ 19 - 26
wechat_service_api.go

@@ -23,7 +23,7 @@ import (
 //    注意:BodyMap中如无 sign_type 参数,默认赋值 sign_type 为 MD5
 //    注意:BodyMap中如无 sign_type 参数,默认赋值 sign_type 为 MD5
 //    appId:应用ID
 //    appId:应用ID
 //    mchId:商户ID
 //    mchId:商户ID
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    返回参数 sign:通过Appid、MchId、ApiKey和BodyMap中的参数计算出的Sign值
 //    返回参数 sign:通过Appid、MchId、ApiKey和BodyMap中的参数计算出的Sign值
 func GetWeChatParamSign(appId, mchId, apiKey string, bm BodyMap) (sign string) {
 func GetWeChatParamSign(appId, mchId, apiKey string, bm BodyMap) (sign string) {
 	bm.Set("appid", appId)
 	bm.Set("appid", appId)
@@ -50,21 +50,21 @@ func GetWeChatParamSign(appId, mchId, apiKey string, bm BodyMap) (sign string) {
 //    注意:沙箱环境默认 sign_type 为 MD5
 //    注意:沙箱环境默认 sign_type 为 MD5
 //    appId:应用ID
 //    appId:应用ID
 //    mchId:商户ID
 //    mchId:商户ID
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    返回参数 sign:通过Appid、MchId、ApiKey和BodyMap中的参数计算出的Sign值
 //    返回参数 sign:通过Appid、MchId、ApiKey和BodyMap中的参数计算出的Sign值
 func GetWeChatSanBoxParamSign(appId, mchId, apiKey string, bm BodyMap) (sign string, err error) {
 func GetWeChatSanBoxParamSign(appId, mchId, apiKey string, bm BodyMap) (sign string, err error) {
 	bm.Set("appid", appId)
 	bm.Set("appid", appId)
 	bm.Set("mch_id", mchId)
 	bm.Set("mch_id", mchId)
 	bm.Set("sign_type", SignType_MD5)
 	bm.Set("sign_type", SignType_MD5)
 	var (
 	var (
-		sanBoxApiKey string
-		hashMd5      hash.Hash
+		sandBoxApiKey string
+		hashMd5       hash.Hash
 	)
 	)
-	if sanBoxApiKey, err = getSanBoxKey(mchId, GetRandomString(32), apiKey, SignType_MD5); err != nil {
+	if sandBoxApiKey, err = getSanBoxKey(mchId, GetRandomString(32), apiKey, SignType_MD5); err != nil {
 		return
 		return
 	}
 	}
 	hashMd5 = md5.New()
 	hashMd5 = md5.New()
-	hashMd5.Write([]byte(bm.EncodeWeChatSignParams(sanBoxApiKey)))
+	hashMd5.Write([]byte(bm.EncodeWeChatSignParams(sandBoxApiKey)))
 	sign = strings.ToUpper(hex.EncodeToString(hashMd5.Sum(nil)))
 	sign = strings.ToUpper(hex.EncodeToString(hashMd5.Sum(nil)))
 	return
 	return
 }
 }
@@ -98,7 +98,7 @@ func ParseWeChatNotifyResult(req *http.Request) (notifyReq *WeChatNotifyRequest,
 }
 }
 
 
 //验证微信支付异步通知的Sign值(Deprecated)
 //验证微信支付异步通知的Sign值(Deprecated)
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    signType:签名类型 MD5 或 HMAC-SHA256(默认请填写 MD5)
 //    signType:签名类型 MD5 或 HMAC-SHA256(默认请填写 MD5)
 //    notifyReq:利用 gopay.ParseWeChatNotifyResult() 得到的结构体
 //    notifyReq:利用 gopay.ParseWeChatNotifyResult() 得到的结构体
 //    返回参数ok:是否验证通过
 //    返回参数ok:是否验证通过
@@ -149,7 +149,7 @@ func VerifyWeChatResultSign(apiKey, signType string, notifyReq *WeChatNotifyRequ
 }
 }
 
 
 //微信同步返回参数验签或异步通知参数验签
 //微信同步返回参数验签或异步通知参数验签
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    signType:签名类型(调用API方法时填写的类型)
 //    signType:签名类型(调用API方法时填写的类型)
 //    bean:微信同步返回的结构体 wxRsp 或 异步通知解析的结构体 notifyReq
 //    bean:微信同步返回的结构体 wxRsp 或 异步通知解析的结构体 notifyReq
 //    返回参数ok:是否验签通过
 //    返回参数ok:是否验签通过
@@ -206,7 +206,7 @@ func (w *WeChatNotifyResponse) ToXmlString() (xmlStr string) {
 //    prepayId:统一下单成功后得到的值
 //    prepayId:统一下单成功后得到的值
 //    signType:签名类型
 //    signType:签名类型
 //    timeStamp:时间
 //    timeStamp:时间
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    微信小程序支付API:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
 //    微信小程序支付API:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
 func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
 func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
 	var (
 	var (
@@ -240,7 +240,7 @@ func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey strin
 //    packages:统一下单成功后拼接得到的值
 //    packages:统一下单成功后拼接得到的值
 //    signType:签名类型
 //    signType:签名类型
 //    timeStamp:时间
 //    timeStamp:时间
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    微信内H5支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/external/jsapi.php?chapter=7_7&index=6
 //    微信内H5支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/external/jsapi.php?chapter=7_7&index=6
 func GetH5PaySign(appId, nonceStr, packages, signType, timeStamp, apiKey string) (paySign string) {
 func GetH5PaySign(appId, nonceStr, packages, signType, timeStamp, apiKey string) (paySign string) {
 	var (
 	var (
@@ -276,7 +276,7 @@ func GetH5PaySign(appId, nonceStr, packages, signType, timeStamp, apiKey string)
 //    prepayId:统一下单成功后得到的值
 //    prepayId:统一下单成功后得到的值
 //    signType:此处签名方式,务必与统一下单时用的签名方式一致
 //    signType:此处签名方式,务必与统一下单时用的签名方式一致
 //    timeStamp:时间
 //    timeStamp:时间
-//    apiKey:API秘钥值
+//    ApiKey:API秘钥值
 //    APP支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12
 //    APP支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12
 func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, apiKey string) (paySign string) {
 func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, apiKey string) (paySign string) {
 	var (
 	var (
@@ -314,12 +314,9 @@ func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, ap
 //    文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
 //    文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
 func DecryptWeChatOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr interface{}) (err error) {
 func DecryptWeChatOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr interface{}) (err error) {
 	var (
 	var (
-		cipherText []byte
-		aesKey     []byte
-		ivKey      []byte
-		block      cipher.Block
-		blockMode  cipher.BlockMode
-		plainText  []byte
+		cipherText, aesKey, ivKey, plainText []byte
+		block                                cipher.Block
+		blockMode                            cipher.BlockMode
 	)
 	)
 	beanValue := reflect.ValueOf(beanPtr)
 	beanValue := reflect.ValueOf(beanPtr)
 	if beanValue.Kind() != reflect.Ptr {
 	if beanValue.Kind() != reflect.Ptr {
@@ -334,8 +331,7 @@ func DecryptWeChatOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr
 	if len(cipherText)%len(aesKey) != 0 {
 	if len(cipherText)%len(aesKey) != 0 {
 		return errors.New("encryptedData is error")
 		return errors.New("encryptedData is error")
 	}
 	}
-	block, err = aes.NewCipher(aesKey)
-	if err != nil {
+	if block, err = aes.NewCipher(aesKey); err != nil {
 		return fmt.Errorf("aes.NewCipher:%v", err.Error())
 		return fmt.Errorf("aes.NewCipher:%v", err.Error())
 	}
 	}
 	blockMode = cipher.NewCBCDecrypter(block, ivKey)
 	blockMode = cipher.NewCBCDecrypter(block, ivKey)
@@ -357,12 +353,9 @@ func DecryptWeChatOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr
 //    文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
 //    文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
 func DecryptWeChatOpenDataToBodyMap(encryptedData, iv, sessionKey string) (bm BodyMap, err error) {
 func DecryptWeChatOpenDataToBodyMap(encryptedData, iv, sessionKey string) (bm BodyMap, err error) {
 	var (
 	var (
-		cipherText []byte
-		aesKey     []byte
-		ivKey      []byte
-		block      cipher.Block
-		blockMode  cipher.BlockMode
-		plainText  []byte
+		cipherText, aesKey, ivKey, plainText []byte
+		block                                cipher.Block
+		blockMode                            cipher.BlockMode
 	)
 	)
 	cipherText, _ = base64.StdEncoding.DecodeString(encryptedData)
 	cipherText, _ = base64.StdEncoding.DecodeString(encryptedData)
 	aesKey, _ = base64.StdEncoding.DecodeString(sessionKey)
 	aesKey, _ = base64.StdEncoding.DecodeString(sessionKey)
@@ -443,7 +436,7 @@ func GetWeChatAppletAccessToken(appId, appSecret string) (accessToken *AccessTok
 //授权码查询openid(AccessToken:157字符)
 //授权码查询openid(AccessToken:157字符)
 //    appId:APPID
 //    appId:APPID
 //    mchId:商户号
 //    mchId:商户号
-//    apiKey:ApiKey
+//    ApiKey:apiKey
 //    authCode:用户授权码
 //    authCode:用户授权码
 //    nonceStr:随即字符串
 //    nonceStr:随即字符串
 //    文档:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_13&index=9
 //    文档:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_13&index=9