You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
alipayopen/client.go

119 lines
3.3 KiB

package alipayopen
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"go.dtapp.net/dorm"
"go.dtapp.net/golog"
"go.dtapp.net/gophp"
"go.dtapp.net/gorequest"
)
// client *dorm.GormClient
type gormClientFun func() *dorm.GormClient
// client *dorm.MongoClient
// databaseName string
type mongoClientFun func() (*dorm.MongoClient, string)
// ClientConfig 实例配置
type ClientConfig struct {
AppId string // 支付宝分配给开发者的应用ID
AppKey string // 支付宝分配给开发者的应用私钥
AppRSA2 string // 应用公钥
AlipayRSA2 string // 支付宝公钥
Aes string // 接口内容加密方式
GormClientFun gormClientFun // 日志配置
MongoClientFun mongoClientFun // 日志配置
Debug bool // 日志开关
ZapLog *golog.ZapLog // 日志服务
}
// Client 实例
type Client struct {
requestClient *gorequest.App // 请求服务
zapLog *golog.ZapLog // 日志服务
privateKey *rsa.PrivateKey // 私钥服务
config struct {
appId string // 支付宝分配给开发者的应用ID
appKey string // 支付宝分配给开发者的应用私钥
appRSA2 string // 应用公钥
alipayRSA2 string // 支付宝公钥
aes string // 接口内容加密方式
}
log struct {
gorm bool // 日志开关
gormClient *dorm.GormClient // 日志数据库
logGormClient *golog.ApiClient // 日志服务
mongo bool // 日志开关
mongoClient *dorm.MongoClient // 日志数据库
logMongoClient *golog.ApiClient // 日志服务
}
}
// NewClient 创建实例化
func NewClient(config *ClientConfig) (*Client, error) {
var err error
c := &Client{}
c.zapLog = config.ZapLog
c.config.appId = config.AppId
c.config.appKey = config.AppKey
c.config.appRSA2 = config.AppRSA2
c.config.alipayRSA2 = config.AlipayRSA2
c.config.aes = config.Aes
// 私钥解码
block, _ := pem.Decode([]byte("-----BEGIN RSA PRIVATE KEY-----\n" + gophp.ChunkSplit(config.AppKey, 64, "\n") + "-----END RSA PRIVATE KEY-----\n"))
if block == nil {
return nil, errors.New("签名私钥解码错误")
}
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
c.privateKey = privateKey.(*rsa.PrivateKey)
// 请求
c.requestClient = gorequest.NewHttp()
c.requestClient.Uri = apiUrl
gormClient := config.GormClientFun()
if gormClient != nil && gormClient.Db != nil {
c.log.logGormClient, err = golog.NewApiGormClient(&golog.ApiGormClientConfig{
GormClientFun: func() (*dorm.GormClient, string) {
return gormClient, logTable
},
Debug: config.Debug,
ZapLog: c.zapLog,
})
if err != nil {
return nil, err
}
c.log.gorm = true
c.log.gormClient = gormClient
}
mongoClient, databaseName := config.MongoClientFun()
if mongoClient != nil && mongoClient.Db != nil {
c.log.logMongoClient, err = golog.NewApiMongoClient(&golog.ApiMongoClientConfig{
MongoClientFun: func() (*dorm.MongoClient, string, string) {
return mongoClient, databaseName, logTable
},
Debug: config.Debug,
ZapLog: c.zapLog,
})
if err != nil {
return nil, err
}
c.log.mongo = true
c.log.mongoClient = mongoClient
}
return c, nil
}