diff --git a/.github/workflows/services.yml b/.github/workflows/services.yml index cafd8d442eb..54cd9eae9e7 100644 --- a/.github/workflows/services.yml +++ b/.github/workflows/services.yml @@ -74,7 +74,7 @@ jobs: strategy: matrix: ## TODO: add more modules - module: [ database ] + module: [ database, pay ] steps: - name: Checkout uses: actions/checkout@v3 @@ -169,7 +169,7 @@ jobs: strategy: matrix: ## TODO: add more modules - module: [ database ] + module: [ database, pay ] steps: - name: Checkout uses: actions/checkout@v3 @@ -229,7 +229,7 @@ jobs: CLUSTER_IMAGE_NAME=${{ steps.prepare.outputs.cluster_repo }}:${{ steps.prepare.outputs.tag_name }} CLUSTER_IMAGE_NAME_LATEST=${{ steps.prepare.outputs.cluster_repo }}:latest sudo sealos tag ${CLUSTER_IMAGE_NAME}-amd64 ${CLUSTER_IMAGE_NAME_LATEST}-amd64 - sudo sealos tag ${CLUSTER_IMAGE_NAME}-amd64 ${CLUSTER_IMAGE_NAME_LATEST}-amd64 + sudo sealos tag ${CLUSTER_IMAGE_NAME}-arm64 ${CLUSTER_IMAGE_NAME_LATEST}-arm64 sudo sealos images bash docker/patch/manifest-cluster-images.sh $CLUSTER_IMAGE_NAME_LATEST - name: Renew issue and Sync Images diff --git a/controllers/account/controllers/account_controller.go b/controllers/account/controllers/account_controller.go index 88c5495953e..255111616d9 100644 --- a/controllers/account/controllers/account_controller.go +++ b/controllers/account/controllers/account_controller.go @@ -131,6 +131,7 @@ func (r *AccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, err } // get payment details(status, amount) + // TODO The GetPaymentDetails may cause issues when using Stripe status, orderAmount, err := payHandler.GetPaymentDetails(payment.Status.TradeNO) if err != nil { return ctrl.Result{}, fmt.Errorf("query order failed: %v", err) diff --git a/controllers/pkg/pay/common.go b/controllers/pkg/pay/common.go index b0099f61f2e..b830d9908fd 100644 --- a/controllers/pkg/pay/common.go +++ b/controllers/pkg/pay/common.go @@ -15,11 +15,11 @@ package pay const ( - PaymentSuccess = "success" - PaymentNotPaid = "not_paid" + PaymentNotPaid = "notpaid" PaymentProcessing = "processing" - PaymentExpired = "expired" PaymentFailed = "failed" + PaymentExpired = "expired" + PaymentSuccess = "success" PaymentUnknown = "unknown" ) diff --git a/go.work b/go.work index bfbe890f469..c7634ce6b14 100644 --- a/go.work +++ b/go.work @@ -15,6 +15,7 @@ use ( ./controllers/pkg ./service/database ./service/hub + ./service/pay ./staging/src/github.com/labring/image-cri-shim ./staging/src/github.com/labring/lvscare ./staging/src/github.com/labring/controllers/imagehub diff --git a/go.work.sum b/go.work.sum index a499a628a3e..a4de3e0a4b0 100644 --- a/go.work.sum +++ b/go.work.sum @@ -1049,7 +1049,6 @@ github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA github.com/census-instrumentation/opencensus-proto v0.4.1 h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= github.com/certifi/gocertifi v0.0.0-20200922220541-2c3bb06c6054 h1:uH66TXeswKn5PW5zdZ39xEwfS9an067BirqA+P4QaLI= -github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/chai2010/gettext-go v1.0.2 h1:1Lwwip6Q2QGsAdl/ZKPCwTe9fe0CjlUbqj5bFNSjIRk= github.com/chai2010/gettext-go v1.0.2/go.mod h1:y+wnP2cHYaVj19NZhYKAwEMH2CI1gNHeQQ+5AjwawxA= github.com/checkpoint-restore/go-criu/v4 v4.1.0 h1:WW2B2uxx9KWF6bGlHqhm8Okiafwwx7Y2kcpn8lCpjgo= @@ -1075,6 +1074,7 @@ github.com/cncf/xds/go v0.0.0-20220314180256-7f1daf1720fc/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20230105202645-06c439db220b/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20230310173818-32f1caf87195 h1:58f1tJ1ra+zFINPlwLWvQsR9CzAKt2e+EWV2yX9oXQ4= github.com/cncf/xds/go v0.0.0-20230310173818-32f1caf87195/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= github.com/cockroachdb/cockroach-go/v2 v2.3.3/go.mod h1:1wNJ45eSXW9AnOc3skntW9ZUZz6gxrQK3cOj3rK+BC8= github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5 h1:xD/lrqdvwsc+O2bjSSi3YqY73Ke3LAiSCx49aCesA0E= @@ -1247,6 +1247,7 @@ github.com/envoyproxy/go-control-plane v0.10.1/go.mod h1:AY7fTTXNdv/aJ2O5jwpxAPO github.com/envoyproxy/go-control-plane v0.10.3/go.mod h1:fJJn/j26vwOu972OllsvAgJJM//w9BV6Fxbg2LuVd34= github.com/envoyproxy/go-control-plane v0.11.0 h1:jtLewhRR2vMRNnq2ZZUoCjUlgut+Y0+sDDWPOfwOi1o= github.com/envoyproxy/go-control-plane v0.11.0/go.mod h1:VnHyVMpzcLvCFt9yUz1UnCwHLhwx1WguiVDV7pTG/tI= +github.com/envoyproxy/go-control-plane v0.11.1-0.20230524094728-9239064ad72f/go.mod h1:sfYdkwUW4BA3PbKjySwjJy+O4Pu0h62rlqCMHNk+K+Q= github.com/envoyproxy/protoc-gen-validate v0.0.14/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.6.2/go.mod h1:2t7qjJNvHPx8IjnBOzl9E9/baC+qXE/TeeyBRzgJDws= @@ -1254,6 +1255,7 @@ github.com/envoyproxy/protoc-gen-validate v0.6.7/go.mod h1:dyJXwwfPK2VSqiB9Klm1J github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w= github.com/envoyproxy/protoc-gen-validate v0.10.0 h1:oIfnZFdC0YhpNNEX+SuIqko4cqqVZeN9IGTrhZje83Y= github.com/envoyproxy/protoc-gen-validate v0.10.0/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= +github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= github.com/etcd-io/gofail v0.0.0-20190801230047-ad7f989257ca/go.mod h1:49H/RkXP8pKaZy4h0d+NW16rSLhyVBt4o6VLJbmOqDE= github.com/euank/go-kmsg-parser v2.0.0+incompatible h1:cHD53+PLQuuQyLZeriD1V/esuG4MuU0Pjs5y6iknohY= github.com/euank/go-kmsg-parser v2.0.0+incompatible/go.mod h1:MhmAMZ8V4CYH4ybgdRwPr2TU5ThnS43puaKEMpja1uw= @@ -2620,6 +2622,8 @@ google.golang.org/genproto v0.0.0-20230222225845-10f96fb3dbec/go.mod h1:3Dl5ZL0q google.golang.org/genproto v0.0.0-20230223222841-637eb2293923/go.mod h1:3Dl5ZL0q0isWJt+FVcfpQyirqemEuLAK/iFvg1UP1Hw= google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= google.golang.org/genproto v0.0.0-20230323212658-478b75c54725/go.mod h1:UUQDJDOlWu4KYeJZffbWgBkS1YFobzKbLVfK69pe0Ak= +google.golang.org/genproto v0.0.0-20230526161137-0005af68ea54/go.mod h1:zqTuNwFlFRsw5zIts5VnzLQxSRqh+CGOTVMlYbY0Eyk= +google.golang.org/genproto/googleapis/api v0.0.0-20230525234035-dd9d682886f9/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= google.golang.org/grpc v1.43.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= diff --git a/service/pay/.gitignore b/service/pay/.gitignore new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/service/pay/.gitignore @@ -0,0 +1 @@ + diff --git a/service/pay/Dockerfile b/service/pay/Dockerfile new file mode 100644 index 00000000000..934627a3450 --- /dev/null +++ b/service/pay/Dockerfile @@ -0,0 +1,8 @@ +FROM gcr.io/distroless/static:nonroot + +ARG TARGETARCH +COPY bin/service-pay-$TARGETARCH /manager +EXPOSE 2303 +USER 65532:65532 + +ENTRYPOINT ["/manager"] \ No newline at end of file diff --git a/service/pay/Makefile b/service/pay/Makefile new file mode 100644 index 00000000000..fce8cd7e906 --- /dev/null +++ b/service/pay/Makefile @@ -0,0 +1,58 @@ +# Image URL to use all building/pushing image targets +IMG ?= ghcr.io/labring/sealos-pay-service:latest + +# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) +ifeq (,$(shell go env GOBIN)) +GOBIN=$(shell go env GOPATH)/bin +else +GOBIN=$(shell go env GOBIN) +endif + +# only support linux, non cgo +PLATFORMS ?= linux_arm64 linux_amd64 +GOOS=linux +CGO_ENABLED=0 +TARGETARCH=arm64 +GOARCH=$(shell go env GOARCH) + +GO_BUILD_FLAGS=-trimpath -ldflags "-s -w" + +.PHONY: all +all: build + +##@ General + +# The help target prints out all targets with their descriptions organized +# beneath their categories. The categories are represented by '##@' and the +# target descriptions by '##'. The awk commands is responsible for reading the +# entire set of makefiles included in this invocation, looking for lines of the +# file as xyz: ## something, and then pretty-format the target and help. Then, +# if there's a line with ##@ something, that gets pretty-printed as a category. +# More info on the usage of ANSI control characters for terminal formatting: +# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters +# More info on the awk command: +# http://linuxcommand.org/lc3_adv_awk.php + +.PHONY: help +help: ## Display this help. + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) + + +##@ Build + +.PHONY: clean +clean: + rm -f $(SERVICE_NAME) + +.PHONY: build +build: clean ## Build service-hub binary. + CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) go build $(GO_BUILD_FLAGS) -o bin/manager main.go + +.PHONY: docker-build +docker-build: build + mv bin/manager bin/service-pay-$(TARGETARCH) + docker build -t $(IMG) . + +.PHONY: docker-push +docker-push: + docker push $(IMG) \ No newline at end of file diff --git a/service/pay/api/appdetail.go b/service/pay/api/appdetail.go new file mode 100644 index 00000000000..d796d9a9676 --- /dev/null +++ b/service/pay/api/appdetail.go @@ -0,0 +1,30 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/handler" + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetAppDetails(c *gin.Context, client *mongo.Client) { + request, err := helper.Init(c, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("init failed before get app details: %v, %v", request, err)}) + return + } + + payDetails, err := handler.GetAppDetails(request, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("get app details failed : %v", err)}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "get app details success", + "payDetails": payDetails, + }) +} diff --git a/service/pay/api/bill.go b/service/pay/api/bill.go new file mode 100644 index 00000000000..e84f92a9c07 --- /dev/null +++ b/service/pay/api/bill.go @@ -0,0 +1,30 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/handler" + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetBill(c *gin.Context, client *mongo.Client) { + request, err := helper.Init(c, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("init failed before get bills: %v, %v", request, err)}) + return + } + + billDetails, err := handler.GetBillDetails(request, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("get bill details failed : %v", err)}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "get the bill details of user(" + request.User + ") success", + "billDetails": billDetails, + }) +} diff --git a/service/pay/api/payapp.go b/service/pay/api/payapp.go new file mode 100644 index 00000000000..10bf93c3a86 --- /dev/null +++ b/service/pay/api/payapp.go @@ -0,0 +1,59 @@ +package api + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "time" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/handler" + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/mongo" +) + +func CreatePayApp(c *gin.Context, client *mongo.Client) { + request, err := helper.Init(c, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("init failed before create payapp: %v, %v", request, err)}) + return + } + + appName := request.PayAppName + // check if the app Name already exists in appcoll + if err := handler.CheckAppNameExistOrNot(client, appName); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("app name already exists: %v", err)}) + return + } + + // generate sign + data := []byte(appName + time.Now().Format("20060102150405")) + hash := sha256.Sum256(data) + sign := hex.EncodeToString(hash[:7]) + // generate appID + data = []byte(sign + time.Now().Format("20060102150405")) + hash = sha256.Sum256(data) + var appID int64 + _, err = fmt.Sscanf(hex.EncodeToString(hash[:7]), "%16x", &appID) + if err != nil { + fmt.Println("appID could not be generated:", err) + return + } + // TODO At present, only wechat and stripe are supported, and then you can consider extending them + methods := []string{"wechat", "stripe"} + + result, err := handler.InsertApp(client, appID, sign, appName, methods) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("create pay app failed when insert into db: %v", err)}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "create pay app success", + "payAppName": appName, + "appID": appID, + "sign": sign, + "result": result, + }) +} diff --git a/service/pay/api/paymethod.go b/service/pay/api/paymethod.go new file mode 100644 index 00000000000..87970834c91 --- /dev/null +++ b/service/pay/api/paymethod.go @@ -0,0 +1,37 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/handler" + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/mongo" +) + +func CreatePayMethod(c *gin.Context, client *mongo.Client) { + request, err := helper.Init(c, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("init failed before create paymethod: %v, %v", request, err)}) + return + } + + if ok, err := handler.CheckPayMethodExistOrNot(client, request.Currency, request.PayMethod); ok && err == nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "paymethod is exist"}) + return + } + + result, err := handler.InsertPayMethod(request, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("create pay method failed when insert into db: %v", err)}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "create pay method success", + "result": result, + }) +} + +// TODO Change the amount or exchange rate or tax rate for a payment method diff --git a/service/pay/api/paysession.go b/service/pay/api/paysession.go new file mode 100644 index 00000000000..bfaa1f64826 --- /dev/null +++ b/service/pay/api/paysession.go @@ -0,0 +1,31 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/helper" + "github.com/labring/sealos/service/pay/method" + "go.mongodb.org/mongo-driver/mongo" +) + +// GetSession Get url from payment service providers (such as WeChat and Stripe) +func GetSession(c *gin.Context, client *mongo.Client) { + request, err := helper.Init(c, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("init failed before get paysession: %v, %v", request, err)}) + return + } + + switch request.PayMethod { + case "wechat": + method.GetWechatURL(c, request, client) + case "stripe": + method.GetStripeSession(c, request, client) + default: + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("paymethod is illegal: %v", request.PayMethod)}) + } + // TODO At present, the Currency of wechat and stripe seems to be CNY, and then if there are other currencies, here needs to be changed + // TODO To prevent multiple orders from the same IP address, you need to add IP restrictions +} diff --git a/service/pay/api/paystatus.go b/service/pay/api/paystatus.go new file mode 100644 index 00000000000..f1a01a47770 --- /dev/null +++ b/service/pay/api/paystatus.go @@ -0,0 +1,29 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/helper" + "github.com/labring/sealos/service/pay/method" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetPayStatus(c *gin.Context, client *mongo.Client) { + request, err := helper.Init(c, client) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("init failed before get payment status: %v, %v", request, err)}) + return + } + + switch request.PayMethod { + case "wechat": + method.GetWechatPaymentStatus(c, request, client) + case "stripe": + method.GetStripePaymentStatus(c, request, client) + default: + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("paymethod is illegal: %v", request.PayMethod)}) + } + // TODO The other status of this area except notpaid has not been tested, and it will be tested later +} diff --git a/service/pay/deploy/Kubefile b/service/pay/deploy/Kubefile new file mode 100644 index 00000000000..bd49a867d94 --- /dev/null +++ b/service/pay/deploy/Kubefile @@ -0,0 +1,17 @@ +FROM scratch +COPY registry registry +COPY manifests manifests + +ENV DEFAULT_NAMESPACE sealos +ENV WECHAT_APPID +ENV WECHAT_MCHAPIV3KEY +ENV WECHAT_MCHID +ENV WECHAT_PRIVATE_KEY +ENV MONGODB_URI +ENV STRIPE_API_KEY +ENV STRIPE_CURRENCY +ENV STRIPE_SUCCESS_POSTFIX +ENV STRIPE_CANCEL_POSTFIX +ENV MCH_CERTIFICATE_SERIAL_NUMBER + +CMD ["( kubectl create -f manifests/mongo-secret.yaml -n $DEFAULT_NAMESPACE || true ) && kubectl apply -f manifests/deploy.yaml"] \ No newline at end of file diff --git a/service/pay/deploy/manifests/deploy.yaml b/service/pay/deploy/manifests/deploy.yaml new file mode 100644 index 00000000000..d6ec792b673 --- /dev/null +++ b/service/pay/deploy/manifests/deploy.yaml @@ -0,0 +1,68 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: pay-service + cloud.sealos.io/app-deploy-manager: pay-service + name: pay-service + namespace: sealos +spec: + progressDeadlineSeconds: 600 + replicas: 3 + revisionHistoryLimit: 1 + selector: + matchLabels: + app: pay-service + strategy: + rollingUpdate: + maxSurge: 0 + maxUnavailable: 1 + type: RollingUpdate + template: + metadata: + labels: + app: pay-service + spec: + containers: + - envFrom: + - secretRef: + name: pay-secret + optional: true + image: ghcr.io/labring/sealos-pay-service:latest + imagePullPolicy: Always + name: pay-service + ports: + - containerPort: 2333 + name: pay-service + protocol: TCP + resources: + limits: + cpu: 500m + memory: 256Mi + requests: + cpu: 50m + memory: 25Mi + terminationMessagePath: /dev/termination-log + terminationMessagePolicy: File + dnsPolicy: ClusterFirst + restartPolicy: Always + schedulerName: default-scheduler + securityContext: {} + terminationGracePeriodSeconds: 30 +--- +apiVersion: v1 +kind: Service +metadata: + labels: + cloud.sealos.io/app-deploy-manager: pay-service + name: pay-service + namespace: sealos +spec: + ports: + - name: pay-service + port: 2333 + protocol: TCP + targetPort: 2303 + selector: + app: pay-service + type: ClusterIP \ No newline at end of file diff --git a/service/pay/deploy/manifests/pay-secret.yaml.tmpl b/service/pay/deploy/manifests/pay-secret.yaml.tmpl new file mode 100644 index 00000000000..39fff48096a --- /dev/null +++ b/service/pay/deploy/manifests/pay-secret.yaml.tmpl @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Secret +metadata: + name: pay-secret + namespace: {{ .DEFAULT_NAMESPACE }} +stringData: + AppID: {{ default "" .WECHAT_APPID }} + MchAPIv3Key: {{ default "" .WECHAT_MCHAPIV3KEY }} + MchCertificateSerialNumber: {{ default "" .MCH_CERTIFICATE_SERIAL_NUMBER }} + MchID: {{ default "" .WECHAT_MCHID }} + STRIPE_CANCEL_POSTFIX: {{ default "" .STRIPE_CANCEL_POSTFIX }} + STRIPE_SUCCESS_POSTFIX: {{ default "" .STRIPE_SUCCESS_POSTFIX }} + STRIPE_CURRENCY: {{ default "" .STRIPE_CURRENCY }} + STRIPE_API_KEY: {{ default "" .STRIPE_API_KEY }} + WechatPrivateKey: {{ default "" .WECHAT_PRIVATE_KEY }} + dburi: {{ default "" .MONGODB_URI }} diff --git a/service/pay/go.mod b/service/pay/go.mod new file mode 100644 index 00000000000..2de7a82efac --- /dev/null +++ b/service/pay/go.mod @@ -0,0 +1,54 @@ +module github.com/labring/sealos/service/pay + +go 1.20 + +require ( + github.com/gin-gonic/gin v1.9.1 + github.com/labring/sealos/controllers/pkg v0.0.0-00010101000000-000000000000 + github.com/matoous/go-nanoid/v2 v2.0.0 + github.com/stripe/stripe-go/v74 v74.30.0 + go.mongodb.org/mongo-driver v1.12.1 +) + +require ( + github.com/bytedance/sonic v1.9.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.14.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.16.7 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/kr/pretty v0.3.0 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect + github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.11 // indirect + github.com/wechatpay-apiv3/wechatpay-go v0.2.17 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect + golang.org/x/arch v0.3.0 // indirect + golang.org/x/crypto v0.12.0 // indirect + golang.org/x/net v0.14.0 // indirect + golang.org/x/sync v0.4.0 // indirect + golang.org/x/sys v0.12.0 // indirect + golang.org/x/text v0.12.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +replace ( + github.com/labring/sealos/controllers/pkg => ../../controllers/pkg + github.com/labring/sealos/service/pay => ../pay +) diff --git a/service/pay/go.sum b/service/pay/go.sum new file mode 100644 index 00000000000..aaac266b191 --- /dev/null +++ b/service/pay/go.sum @@ -0,0 +1,159 @@ +github.com/agiledragon/gomonkey v2.0.2+incompatible h1:eXKi9/piiC3cjJD1658mEE2o3NjkJ5vDLgYjCQu0Xlw= +github.com/agiledragon/gomonkey v2.0.2+incompatible/go.mod h1:2NGfXu1a80LLr2cmWXGBDaHEjb1idR6+FVlX5T3D9hw= +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= +github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= +github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/matoous/go-nanoid v1.5.0/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U= +github.com/matoous/go-nanoid/v2 v2.0.0 h1:d19kur2QuLeHmJBkvYkFdhFBzLoo1XVm2GgTpL+9Tj0= +github.com/matoous/go-nanoid/v2 v2.0.0/go.mod h1:FtS4aGPVfEkxKxhdWPAspZpZSh1cOjtM7Ej/So3hR0g= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= +github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stripe/stripe-go/v74 v74.30.0 h1:0Kf0KkeFnY7iRhOwvTerX0Ia1BRw+eV1CVJ51mGYAUY= +github.com/stripe/stripe-go/v74 v74.30.0/go.mod h1:f9L6LvaXa35ja7eyvP6GQswoaIPaBRvGAimAO+udbBw= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/wechatpay-apiv3/wechatpay-go v0.2.17 h1:i4YJA/6BqAbi2YfyPZBjpeEeO/+oa4UbKP4gSTRhhQg= +github.com/wechatpay-apiv3/wechatpay-go v0.2.17/go.mod h1:A254AUBVB6R+EqQFo3yTgeh7HtyqRRtN2w9hQSOrd4Q= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.12.1 h1:nLkghSU8fQNaK7oUmDhQFsnrtcoNy7Z6LVFKsEecqgE= +go.mongodb.org/mongo-driver v1.12.1/go.mod h1:/rGBTebI3XYboVmgz+Wv3Bcbl3aD0QF9zl6kDDw18rQ= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= +golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ= +golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/service/pay/handler/appdetail.go b/service/pay/handler/appdetail.go new file mode 100644 index 00000000000..0c431efc607 --- /dev/null +++ b/service/pay/handler/appdetail.go @@ -0,0 +1,45 @@ +package handler + +import ( + "context" + "fmt" + + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetAppDetails(request *helper.Request, client *mongo.Client) ([]helper.PayMethodDetail, error) { + appID := request.AppID + filter := bson.D{{Key: "appID", Value: appID}} + appColl := helper.InitDBAndColl(client, helper.Database, helper.AppColl) + + var appResult bson.M + if err := appColl.FindOne(context.TODO(), filter).Decode(&appResult); err != nil { + return nil, fmt.Errorf("read data of the collection app failed: %v", err) + } + methods, ok := appResult["methods"].(bson.A) + if !ok { + return nil, fmt.Errorf("methods type assertion failed") + } + var payDetails []helper.PayMethodDetail + for _, method := range methods { + pmColl := helper.InitDBAndColl(client, helper.Database, helper.PayMethodColl) + filter := bson.D{{Key: "payMethod", Value: method}} + + // query operation + cursor, err := pmColl.Find(context.TODO(), filter) + if err != nil { + return nil, fmt.Errorf("query error: %v", err) + } + // Retrieve documents for the current payment method + var methodPayDetails []helper.PayMethodDetail + if err := cursor.All(context.TODO(), &methodPayDetails); err != nil { + return nil, fmt.Errorf("cursor error: %v", err) + } + + // Add the matching method of the documents to the payDetails slice + payDetails = append(payDetails, methodPayDetails...) + } + return payDetails, nil +} diff --git a/service/pay/handler/bill.go b/service/pay/handler/bill.go new file mode 100644 index 00000000000..c382bf714a4 --- /dev/null +++ b/service/pay/handler/bill.go @@ -0,0 +1,32 @@ +package handler + +import ( + "context" + + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetBillDetails(request *helper.Request, client *mongo.Client) ([]helper.BillDetail, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.PaymentDetailsColl) + filter := bson.D{ + {Key: "user", Value: request.User}, + {Key: "appID", Value: request.AppID}, + } + + cursor, err := coll.Find(context.Background(), filter) + if err != nil { + return nil, err + } + defer cursor.Close(context.Background()) + + // init result array + var billDetails []helper.BillDetail + + if err := cursor.All(context.Background(), &billDetails); err != nil { + return nil, err + } + + return billDetails, nil +} diff --git a/service/pay/handler/payapp.go b/service/pay/handler/payapp.go new file mode 100644 index 00000000000..616e6280699 --- /dev/null +++ b/service/pay/handler/payapp.go @@ -0,0 +1,67 @@ +package handler + +import ( + "context" + "fmt" + + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func InsertApp(client *mongo.Client, appID int64, sign, appName string, methods []string) (*mongo.InsertManyResult, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.AppColl) + docs := []interface{}{ + helper.App{ + AppID: appID, + Sign: sign, + PayAppName: appName, + Methods: methods, + }, + } + + result, err := coll.InsertMany(context.TODO(), docs) + if err != nil { + //fmt.Println("insert the data of app failed:", err) + return nil, fmt.Errorf("insert the data of app failed: %v", err) + } + fmt.Println("insert the data of app success:", result) + return result, nil +} + +// CheckAppAllowOrNot checks if the appID is allowed to use the payMethod +func CheckAppAllowOrNot(client *mongo.Client, appID int64, payMethod string) error { + coll := helper.InitDBAndColl(client, helper.Database, helper.AppColl) + filter := bson.D{{Key: "appID", Value: appID}} + var result bson.M + if err := coll.FindOne(context.Background(), filter).Decode(&result); err != nil { + fmt.Println("no allowed appID could be found:", err) + return fmt.Errorf("no allowed appID could be found: %v", err) + } + + methods := result["methods"].(bson.A) + for _, method := range methods { + if method == payMethod { + return nil + } + } + return fmt.Errorf("this payment method is not allowed in this app") +} + +func CheckAppNameExistOrNot(client *mongo.Client, appName string) error { + coll := helper.InitDBAndColl(client, helper.Database, helper.AppColl) + filter := bson.D{{Key: "payAppName", Value: appName}} + + var result bson.M + err := coll.FindOne(context.Background(), filter).Decode(&result) + if err == mongo.ErrNoDocuments { + // appName does not exist, return nil + return nil + } else if err != nil { + // query error + return fmt.Errorf("query error: %v", err) + } + + // payAppName already exist + return fmt.Errorf("app name already exists") +} diff --git a/service/pay/handler/paymethod.go b/service/pay/handler/paymethod.go new file mode 100644 index 00000000000..c8650b88e5b --- /dev/null +++ b/service/pay/handler/paymethod.go @@ -0,0 +1,71 @@ +package handler + +import ( + "context" + "fmt" + + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetExchangeRate(client *mongo.Client, payMethod, currency string) (float64, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.PayMethodColl) + filter := bson.D{ + {Key: "payMethod", Value: payMethod}, + {Key: "currency", Value: currency}, + } + + var result bson.M + if err := coll.FindOne(context.Background(), filter).Decode(&result); err != nil { + fmt.Println("read data of the collection paymethod failed:", err) + return 0, fmt.Errorf("read data of the collection paymethod failed: %v", err) + } + exchangeRate, ok := result["exchangeRate"].(float64) + if !ok { + fmt.Println("status type assertion failed") + return 0, fmt.Errorf("status type assertion failed") + } + return exchangeRate, nil +} + +func InsertPayMethod(request *helper.Request, client *mongo.Client) (*mongo.InsertManyResult, error) { + payMethod := request.PayMethod + currency := request.Currency + amountOptions := request.AmountOptions + exchangerate := request.ExchangeRate + taxRate := request.TaxRate + + coll := helper.InitDBAndColl(client, helper.Database, helper.PayMethodColl) + + docs := []interface{}{ + helper.PayMethodDetail{ + PayMethod: payMethod, + Currency: currency, + AmountOptions: amountOptions, + ExchangeRate: exchangerate, + TaxRate: taxRate, + }, + } + + result, err := coll.InsertMany(context.TODO(), docs) + if err != nil { + return nil, fmt.Errorf("insert the data of paymethod failed: %v", err) + } + return result, nil +} + +func CheckPayMethodExistOrNot(client *mongo.Client, currency, payMethod string) (bool, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.PayMethodColl) + filter := bson.D{ + {Key: "payMethod", Value: payMethod}, + {Key: "currency", Value: currency}, + } + + var result bson.M + if err := coll.FindOne(context.Background(), filter).Decode(&result); err != nil { + fmt.Println("no matching payment method and currency could be found:", err) + return false, fmt.Errorf("no matching payment method and currency could be found: %v", err) + } + return true, nil +} diff --git a/service/pay/handler/paysession.go b/service/pay/handler/paysession.go new file mode 100644 index 00000000000..cb09cbead44 --- /dev/null +++ b/service/pay/handler/paysession.go @@ -0,0 +1,122 @@ +package handler + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/labring/sealos/controllers/pkg/pay" + + "github.com/labring/sealos/service/pay/helper" + gonanoid "github.com/matoous/go-nanoid/v2" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +// InsertDetails inserts data into both the payment_details and order_details tables and ensures transactionality +func InsertDetails(client *mongo.Client, user, payMethod, amount, currency string, appID int64, details map[string]interface{}) (string, error) { + // create transaction options + maxCommitTime := 5 * time.Second + transactionOptions := options.Transaction().SetMaxCommitTime(&maxCommitTime) + + // execute transaction + session, err := client.StartSession() + if err != nil { + fmt.Println("failed to create a session:", err) + } + defer session.EndSession(context.Background()) + + // execute transaction + result, err := session.WithTransaction(context.Background(), func(sessCtx mongo.SessionContext) (interface{}, error) { + // perform an operation to insert data into paymentDetails in a transaction + orderID, err := InsertPaymentDetails(client, user, payMethod, amount, currency, appID) + if err != nil { + fmt.Println("insert payment details failed:", err) + return nil, fmt.Errorf("insert payment details failed: %v", err) + } + + // the insertion of data to the orderDetailsColl in a transaction + if err := InsertOrderDetails(client, appID, user, orderID, amount, payMethod, currency, details); err != nil { + fmt.Println("insert order details failed:", err) + return nil, fmt.Errorf("insert order details failed: %v", err) + } + + return orderID, nil + }, transactionOptions) + + if err != nil { + fmt.Println("transaction execution failure:", err) + } + + orderID := result.(string) + fmt.Println("Order ID:", orderID) + return orderID, nil +} + +func InsertPaymentDetails(client *mongo.Client, user, payMethod, amount, currency string, appID int64) (string, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.PaymentDetailsColl) + orderID, err := gonanoid.New(18) + // switched to the Chinese time zone and optimized the format + payTime := time.Now().UTC().In(time.FixedZone("CST", 8*60*60)).Format("2006-01-02 15:04:05") + if err != nil { + return "", fmt.Errorf("create order id failed: %w", err) + } + docs := []interface{}{ + helper.PaymentDetails{ + OrderID: orderID, + User: user, + Amount: amount, + Currency: currency, + PayTime: payTime, + PayMethod: payMethod, + AppID: appID, + Status: pay.PaymentNotPaid, + }, + } + + result, err := coll.InsertMany(context.TODO(), docs) + if err != nil { + return "", fmt.Errorf("insert the data of payment details failed: %w", err) + } + fmt.Println("insert the data of payment details successfully:", result) + return orderID, nil +} + +func InsertOrderDetails(client *mongo.Client, appID int64, user, orderID, amount, payMethod, currency string, details map[string]interface{}) error { + coll := helper.InitDBAndColl(client, helper.Database, helper.OrderDetailsColl) + // switched to the Chinese time zone and optimized the format + payTime := time.Now().UTC().In(time.FixedZone("CST", 8*60*60)).Format("2006-01-02 15:04:05") + // get the exchange rate corresponding to the currency, + // and then calculate the corresponding RMB amount / sealos amount + exchangeRate, err := GetExchangeRate(client, payMethod, currency) + if err != nil { + return fmt.Errorf("get exchange rate failed: %w", err) + } + // convert amount to type float64 + amountFloat, err := strconv.ParseFloat(amount, 64) + if err != nil { + return fmt.Errorf("the amount cannot be converted to float64: %w", err) + } + // calculate the product of the amountFloat and the exchangeRate + newAmount := amountFloat * exchangeRate + newAmountStr := strconv.FormatFloat(newAmount, 'f', 2, 64) + + docs := []interface{}{ + helper.OrderDetails{ + OrderID: orderID, + Amount: newAmountStr, + User: user, + PayTime: payTime, + PayMethod: payMethod, + AppID: appID, + DetailsData: details, + }, + } + result, err := coll.InsertMany(context.TODO(), docs) + if err != nil { + return fmt.Errorf("insert the data of order details failed: %w", err) + } + fmt.Println("insert the data of order details successfully:", result) + return nil +} diff --git a/service/pay/handler/paystatus.go b/service/pay/handler/paystatus.go new file mode 100644 index 00000000000..c18a6e86886 --- /dev/null +++ b/service/pay/handler/paystatus.go @@ -0,0 +1,109 @@ +package handler + +import ( + "context" + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetPaymentStatus(client *mongo.Client, orderID string) (string, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.PaymentDetailsColl) + filter := bson.D{{Key: "orderID", Value: orderID}} + var paymentResult bson.M + if err := coll.FindOne(context.TODO(), filter).Decode(&paymentResult); err != nil { + fmt.Println("read data of the collection paymentDetails failed:", err) + return "", fmt.Errorf("read data of the collection paymentDetails failed: %v", err) + } + status, ok := paymentResult["status"].(string) + if !ok { + fmt.Println("status type assertion failed") + return "", fmt.Errorf("status type assertion failed") + } + return status, nil +} + +func UpdatePaymentStatus(client *mongo.Client, orderID string, status string) (string, error) { + coll := helper.InitDBAndColl(client, helper.Database, helper.PaymentDetailsColl) + filter := bson.D{{Key: "orderID", Value: orderID}} + update := bson.D{ + {Key: "$set", Value: bson.D{ + {Key: "status", Value: status}, + }}, + } + var paymentResult bson.M + if err := coll.FindOneAndUpdate(context.Background(), filter, update).Decode(&paymentResult); err != nil { + fmt.Println("update payment status failed:", err) + return "", fmt.Errorf("update payment status failed: %v", err) + } + // The payment Result here is the data before the update + return paymentResult["status"].(string), nil +} + +func UpdateDBIfDiff(c *gin.Context, orderID string, client *mongo.Client, status, aimStatus string) { + // If the database order Status is also aimed-Status, return directly + if status == aimStatus { + c.JSON(http.StatusOK, gin.H{ + "message": "payment status is: " + aimStatus + ",please try again later", + "status": status, + "orderID": orderID, + }) + return + } + paymentStatus, err := UpdatePaymentStatus(client, orderID, aimStatus) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "error": fmt.Sprintf("update payment status failed when wechat order status is %s: %s, %v", aimStatus, paymentStatus, err), + }) + return + } + c.JSON(http.StatusOK, gin.H{ + "message": "payment is " + aimStatus + ", database has been updated", + "status": aimStatus, + "orderID": orderID, + }) +} + +func CheckOrderExistOrNot(client *mongo.Client, request *helper.Request) error { + orderID := request.OrderID + payMethod := request.PayMethod + appID := request.AppID + user := request.User + coll := helper.InitDBAndColl(client, helper.Database, helper.OrderDetailsColl) + filter := bson.D{ + {Key: "orderID", Value: orderID}, + {Key: "payMethod", Value: payMethod}, + {Key: "user", Value: user}, + {Key: "appID", Value: appID}, + } + // Execute the MongoDB query + var result helper.OrderDetails + err := coll.FindOne(context.Background(), filter).Decode(&result) + if err != nil { + if err == mongo.ErrNoDocuments { + return fmt.Errorf("order not found") + } + return fmt.Errorf("failed to query order details: %w", err) + } + + // Perform additional checks based on the payMethod + switch payMethod { + case "stripe": + if result.DetailsData["sessionID"] != request.SessionID { + return fmt.Errorf("sessionID mismatch") + } + case "wechat": + if result.DetailsData["tradeNO"] != request.TradeNO { + return fmt.Errorf("TradeNO mismatch") + } + default: + return fmt.Errorf("unsupported payMethod: %s", payMethod) + } + + // Order and payMethod are valid + return nil +} diff --git a/service/pay/helper/constant.go b/service/pay/helper/constant.go new file mode 100644 index 00000000000..d21dc88bab0 --- /dev/null +++ b/service/pay/helper/constant.go @@ -0,0 +1,55 @@ +package helper + +// DB +const ( + DBURI = "dburi" + // TODO the database needs a new name + Database = "xy" + AppColl = "app" + PayMethodColl = "paymethod" + PaymentDetailsColl = "paymentdetails" + OrderDetailsColl = "orderdetails" +) + +// Paymethod +const ( + Wechat = "wechat" + Alipay = "alipay" + Stripe = "stripe" +) + +// TLS +const ( + Cert = "/path/to/certificates/tls.crt" + Key = "/path/to/certificates/tls.key" +) + +// stripe +const ( + DefaultPort string = "443" + DefaultDomain string = "cloud.sealos.io" +) +const ( + StripeSuccessPostfix = "STRIPE_SUCCESS_POSTFIX" + StripeCancelPostfix = "STRIPE_CANCEL_POSTFIX" + StripeCurrency = "STRIPE_CURRENCY" +) + +// Test +const ( + LOCALHOST = "http://localhost:2303" + DNS = "https://coqveoktbleo.dev.sealos.top" + GROUP = "/v1alpha1/pay" + CreatePayMethod = "/method" + CreatePayApp = "/app" + GetAppDetails = "/details" + GetSession = "/session" + GetPayStatus = "/status" + GetBill = "/bill" + TestAppID = 66683568733697785 + TestSign = "597d7f10a27219" + TestUser = "xy" + TestOrderID = "8QC6mu7vSNJckVhpKv" + TestSessionID = "cs_test_a1vbMHEx4iVfIWPoiJVVbBd7eecKDw8CDdJoLc7KRpahkMXYJ51EIlA1x5" + TestTradeNO = "049dfbf0b96ae9e2fa54a4b8eed6ea34" +) diff --git a/service/pay/helper/dto.go b/service/pay/helper/dto.go new file mode 100644 index 00000000000..faccd4ec1c1 --- /dev/null +++ b/service/pay/helper/dto.go @@ -0,0 +1,17 @@ +package helper + +type Request struct { + AppID int64 `json:"appID"` + Sign string `json:"sign"` + PayMethod string `json:"payMethod"` + Amount string `json:"amount"` + User string `json:"user"` + PayAppName string `json:"payAppName,omitempty"` + Currency string `json:"currency,omitempty"` + AmountOptions []string `json:"amountOptions,omitempty"` + ExchangeRate float64 `json:"exchangeRate,omitempty"` + TaxRate float64 `json:"taxRate,omitempty"` + TradeNO string `json:"tradeNO,omitempty"` + SessionID string `json:"sessionID,omitempty"` + OrderID string `json:"orderID,omitempty"` +} diff --git a/service/pay/helper/entity.go b/service/pay/helper/entity.go new file mode 100644 index 00000000000..03ddcef1454 --- /dev/null +++ b/service/pay/helper/entity.go @@ -0,0 +1,46 @@ +package helper + +type PaymentDetails struct { + OrderID string `bson:"orderID"` + User string `bson:"user"` + Amount string `bson:"amount"` + Currency string `bson:"currency"` + PayTime string `bson:"payTime"` + PayMethod string `bson:"payMethod"` + AppID int64 `bson:"appID"` + Status string `bson:"status"` +} + +type OrderDetails struct { + OrderID string `bson:"orderID"` + User string `bson:"user"` + Amount string `bson:"amount"` + PayTime string `bson:"paytime"` + PayMethod string `bson:"payMethod"` + AppID int64 `bson:"appID"` + DetailsData map[string]interface{} `bson:"detailsdata"` +} + +type App struct { + AppID int64 `bson:"appID"` + Sign string `bson:"sign"` + PayAppName string `bson:"payAppName"` + Methods []string `bson:"methods"` +} + +type BillDetail struct { + OrderID string `bson:"orderID"` + Amount string `bson:"amount"` + Currency string `bson:"currency"` + PayTime string `bson:"payTime"` + PayMethod string `bson:"payMethod"` + Status string `bson:"status"` +} + +type PayMethodDetail struct { + PayMethod string `bson:"payMethod"` + Currency string `bson:"currency"` + AmountOptions []string `bson:"amountOptions"` + ExchangeRate float64 `bson:"exchangeRate"` + TaxRate float64 `bson:"taxRate"` +} diff --git a/service/pay/helper/init.go b/service/pay/helper/init.go new file mode 100644 index 00000000000..cb5adfe17bb --- /dev/null +++ b/service/pay/helper/init.go @@ -0,0 +1,69 @@ +package helper + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readpref" +) + +func Init(c *gin.Context, client *mongo.Client) (*Request, error) { + payRequest := &Request{} + err := c.ShouldBindJSON(payRequest) + if err != nil { + return nil, fmt.Errorf("bind json error : %v", err) + } + // Identity authentication + if err = Authenticate(payRequest, client); err != nil { + return nil, fmt.Errorf("authenticate error : %v", err) + } + return payRequest, nil +} + +func Authenticate(r *Request, client *mongo.Client) error { + coll := InitDBAndColl(client, Database, AppColl) + appID := r.AppID + sign := r.Sign + + // create filter + filter := bson.D{ + {Key: "appID", Value: appID}, + {Key: "sign", Value: sign}, + } + + var result bson.M + if err := coll.FindOne(context.TODO(), filter).Decode(&result); err != nil { + // processing query error + if err == mongo.ErrNoDocuments { + // no matching document found, error returned + return fmt.Errorf("no matching app found: %v", err) + } + // for other errors, print the error message and handle it + return fmt.Errorf("unknown error: %v", err) + } + return nil +} + +func InitMongoClient(URI string) *mongo.Client { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client, err := mongo.Connect(ctx, options.Client().ApplyURI(URI)) + if err != nil { + log.Fatal(err) + } + if err = client.Ping(context.TODO(), readpref.Primary()); err != nil { + log.Fatal(err) + } + return client +} + +func InitDBAndColl(client *mongo.Client, datebase string, collection string) *mongo.Collection { + coll := client.Database(datebase).Collection(collection) + return coll +} diff --git a/service/pay/helper/logger.go b/service/pay/helper/logger.go new file mode 100644 index 00000000000..3edee008473 --- /dev/null +++ b/service/pay/helper/logger.go @@ -0,0 +1,39 @@ +package helper + +import ( + "fmt" + "time" + + "github.com/gin-gonic/gin" +) + +func RequestLogger() gin.HandlerFunc { + return func(c *gin.Context) { + t := time.Now() + + c.Next() + + latency := time.Since(t) + + fmt.Printf("%s %s %s %s\n", + c.Request.Method, + c.Request.RequestURI, + c.Request.Proto, + latency, + ) + } +} + +func ResponseLogger() gin.HandlerFunc { + return func(c *gin.Context) { + c.Writer.Header().Set("X-Content-Type-Options", "nosniff") + + c.Next() + + fmt.Printf("%d %s %s\n", + c.Writer.Status(), + c.Request.Method, + c.Request.RequestURI, + ) + } +} diff --git a/service/pay/main.go b/service/pay/main.go new file mode 100644 index 00000000000..6154e3106d1 --- /dev/null +++ b/service/pay/main.go @@ -0,0 +1,21 @@ +package main + +import ( + "github.com/labring/sealos/service/pay/router" +) + +func main() { + router.RegisterPayRouter() + + //cert, err := tls.LoadX509KeyPair("./key/pay.pem", "./key/pay.key") + //if err != nil { + // log.Fatalf("failed to load certificates and keys: %v", err) + //} + //cfg := &tls.Config{Certificates: []tls.Certificate{cert}} + // + //listener, err := tls.Listen("tcp", ":8080", cfg) + //if err != nil { + // log.Fatal(err) + //} + //defer listener.Close() +} diff --git a/service/pay/method/stripe.go b/service/pay/method/stripe.go new file mode 100644 index 00000000000..3c56caf9cd0 --- /dev/null +++ b/service/pay/method/stripe.go @@ -0,0 +1,131 @@ +package method + +import ( + "fmt" + "net/http" + "os" + "strconv" + + "github.com/labring/sealos/controllers/pkg/pay" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/handler" + "github.com/labring/sealos/service/pay/helper" + "github.com/stripe/stripe-go/v74" + "go.mongodb.org/mongo-driver/mongo" +) + +var DefaultURL = fmt.Sprintf("https://%s", GetEnvWithDefault("DOMAIN", helper.DefaultDomain)) + +func GetEnvWithDefault(s string, domain string) string { + if value, ok := os.LookupEnv(s); ok { + return value + } + return domain +} + +func GetStripeSession(c *gin.Context, request *helper.Request, client *mongo.Client) { + amountStr := request.Amount + amount, err := strconv.ParseInt(amountStr, 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error amount : %d, %v", amount, err)}) + return + } + + // check the database paymethod and report an error if there is no corresponding payment method + if _, err := handler.CheckPayMethodExistOrNot(client, request.Currency, request.PayMethod); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("paymethod is not exist: %v", err)}) + return + } + // check the app collection to see if the cluster is allowed to use this payment method + if err := handler.CheckAppAllowOrNot(client, request.AppID, helper.Stripe); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error pay method or currency in this app : %v", err)}) + return + } + + session, err := pay.CreateCheckoutSession(amount, pay.CNY, DefaultURL+os.Getenv(helper.StripeSuccessPostfix), DefaultURL+os.Getenv(helper.StripeCancelPostfix)) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error session : %v", err)}) + return + } + + appID := request.AppID + user := request.User + currency := request.Currency + stripeDetails := map[string]interface{}{ + "sessionID": session.ID, + } + // Ensure that these operations are atomic, meaning that if the lower operation fails, + // the upper operation must be rolled back + // helper.Insert Payment Details and helper.Insert Order Details are placed in a transaction helper.Insert Details, + // and if either fails, they are rolled back + + // insert payment details into database + orderID, err := handler.InsertDetails(client, user, helper.Stripe, amountStr, currency, appID, stripeDetails) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("insert stripe payment details failed: %s, %v", session.ID, err)}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "get stripe sessionID success", + "sessionID": session.ID, + "amount": amountStr, + "currency": currency, + "user": user, + "orderID": orderID, + }) +} + +func GetStripePaymentStatus(c *gin.Context, request *helper.Request, client *mongo.Client) { + // Firstly, check whether the order exists in the order Details, if not, directly return + if err := handler.CheckOrderExistOrNot(client, request); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("order does not exist: %v", err)}) + return + } + // check the payment status in the database first + status, err := handler.GetPaymentStatus(client, request.OrderID) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("get payment status failed from db: %s, %v", status, err)}) + return + } + // If the payment has been successful, return directly + if status == pay.PaymentSuccess { + c.JSON(http.StatusOK, gin.H{ + "message": "payment has been successfully completed", + "status": status, + "orderID": request.OrderID, + }) + return + } + // If it is not successful, then go to the payment provider server query + session, err := pay.GetSession(request.SessionID) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("get stripe session failed: %v, %v", session, err)}) + return + } + + switch session.Status { + case stripe.CheckoutSessionStatusComplete: + // change the status of the database to pay.Payment Success + paymentStatus, err := handler.UpdatePaymentStatus(client, request.OrderID, pay.PaymentSuccess) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "error": fmt.Sprintf("update payment status failed when wechat order status is success: %s, %v", paymentStatus, err), + }) + return + } + c.JSON(http.StatusOK, gin.H{ + "message": "payment has been successfully completed, database has been updated", + "status": pay.PaymentSuccess, + "orderID": request.OrderID, + }) + return + case stripe.CheckoutSessionStatusExpired: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentExpired) + case stripe.CheckoutSessionStatusOpen: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentNotPaid) + default: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentUnknown) + } +} diff --git a/service/pay/method/wechat.go b/service/pay/method/wechat.go new file mode 100644 index 00000000000..80418aeb5c7 --- /dev/null +++ b/service/pay/method/wechat.go @@ -0,0 +1,125 @@ +package method + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/controllers/pkg/pay" + "github.com/labring/sealos/service/pay/handler" + "github.com/labring/sealos/service/pay/helper" + "go.mongodb.org/mongo-driver/mongo" +) + +func GetWechatURL(c *gin.Context, request *helper.Request, client *mongo.Client) { + amountStr := request.Amount + amount, err := strconv.ParseInt(amountStr, 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error amount : %d, %v", amount, err)}) + return + } + + // check the database paymethod and report an error if there is no corresponding payment method + if _, err := handler.CheckPayMethodExistOrNot(client, request.Currency, helper.Wechat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error paymethod : %v", err)}) + return + } + // check the app collection to see if the cluster is allowed to use this payment method + if err := handler.CheckAppAllowOrNot(client, request.AppID, helper.Wechat); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error pay method or currency in this app : %v", err)}) + return + } + + user := request.User + tradeNO := pay.GetRandomString(32) + codeURL, err := pay.WechatPay(amount, user, tradeNO, "", "") + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error codeURL : %s, %v", codeURL, err)}) + return + } + appID := request.AppID + currency := request.Currency + wechatDetails := map[string]interface{}{ + "tradeNO": tradeNO, + "codeURL": codeURL, + } + + // Ensure that these operations are atomic, meaning that if the lower operation fails, + // the upper operation must be rolled back + // helper.Insert Payment Details and helper.Insert Order Details are placed in a transaction helper.Insert Details, + // and if either fails, they are rolled back + + // insert payment details into database + orderID, err := handler.InsertDetails(client, user, helper.Wechat, amountStr, currency, appID, wechatDetails) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("insert wechat payment details failed: %s, %v", codeURL, err)}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "get wechat url success", + "codeURL": codeURL, + "tradeNO": tradeNO, + "amount": amountStr, + "currency": currency, + "user": user, + "orderID": orderID, + }) +} + +func GetWechatPaymentStatus(c *gin.Context, request *helper.Request, client *mongo.Client) { + // Firstly, check whether the order exists in the order Details, if not, directly return + if err := handler.CheckOrderExistOrNot(client, request); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("order does not exist: %v", err)}) + return + } + + // check the payment status in the database first + status, err := handler.GetPaymentStatus(client, request.OrderID) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("get payment status failed from db: %s, %v", status, err)}) + return + } + // If the payment has been successful, return directly + if status == pay.PaymentSuccess { + c.JSON(http.StatusOK, gin.H{ + "message": "payment has been successfully completed", + "status": status, + "orderID": request.OrderID, + }) + return + } + + // If it is not successful, then go to the payment provider server query + orderResp, err := pay.QueryOrder(request.TradeNO) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("query order failed when get wechat payment status: %v, %v", orderResp, err)}) + return + } + switch *orderResp.TradeState { + case pay.StatusSuccess: + // change the status of the database to pay.Payment Success + paymentStatus, err := handler.UpdatePaymentStatus(client, request.OrderID, pay.PaymentSuccess) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "error": fmt.Sprintf("update payment status failed when wechat order status is success: %s, %v", paymentStatus, err), + }) + return + } + c.JSON(http.StatusOK, gin.H{ + "message": "payment has been successfully completed, database has been updated", + "status": pay.PaymentSuccess, + "orderID": request.OrderID, + }) + return + case pay.StatusProcessing: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentProcessing) + case pay.StatusNotPay: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentNotPaid) + case pay.StatusFail: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentFailed) + default: + handler.UpdateDBIfDiff(c, request.OrderID, client, status, pay.PaymentUnknown) + } +} diff --git a/service/pay/pay_test.go b/service/pay/pay_test.go new file mode 100644 index 00000000000..c4ad3b168e5 --- /dev/null +++ b/service/pay/pay_test.go @@ -0,0 +1,199 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "testing" + + "github.com/labring/sealos/service/pay/helper" +) + +func TestCreatePayMethod_Wechat(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "payMethod": "wechat", + "currency": "CNY", + "amountOptions": []string{"158", "368", "962", "1018", "2822"}, + "exchangeRate": 1, + "taxRate": 0.12, + } + createPayTest(t, data, http.MethodPut, helper.CreatePayMethod) +} + +func TestCreatePayMethod_Stripe(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "payMethod": "stripe", + "currency": "USD", + "amountOptions": []string{"258", "568", "862", "1218", "1822"}, + "exchangeRate": 2, + "taxRate": 0.2, + } + createPayTest(t, data, http.MethodPut, helper.CreatePayMethod) +} + +func TestCreatePayApp(t *testing.T) { + data := map[string]interface{}{ + "payAppName": "laf.io", + "appID": helper.TestAppID, + "sign": helper.TestSign, + } + createPayTest(t, data, http.MethodPut, helper.CreatePayApp) +} + +func TestAuthentication(t *testing.T) { + data := map[string]interface{}{ + "payAppName": "laf.io", + "appID": helper.TestAppID + 123, + "sign": helper.TestSign + "123", + } + createPayTest(t, data, http.MethodPut, helper.CreatePayApp) +} + +func TestGetAppDetails(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + } + createPayTest(t, data, http.MethodGet, helper.GetAppDetails) +} + +func TestGetSession_Wechat(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "amount": "1288", + "currency": "CNY", + "user": helper.TestUser, + "payMethod": "wechat", + } + createPayTest(t, data, http.MethodGet, helper.GetSession) +} + +func TestGetSession_Stripe(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "amount": "1288", + "currency": "USD", + "user": helper.TestUser, + "payMethod": "stripe", + } + createPayTest(t, data, http.MethodGet, helper.GetSession) +} + +func TestGetPayStatus(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "orderID": helper.TestOrderID, + "payMethod": helper.Stripe, + "user": helper.TestUser, + "sessionID": helper.TestSessionID, + //"TradeNO": helper.TestTradeNO, + } + createPayTest(t, data, http.MethodGet, helper.GetPayStatus) +} + +func TestGetPayStatus_seesionIDLXD(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "orderID": helper.TestOrderID, + "payMethod": helper.Stripe, + "user": helper.TestUser, + "sessionID": helper.TestSessionID + "abc", + // "TradeNO": "db27af04c65bd27bb3c3708addbafc01", + } + createPayTest(t, data, http.MethodGet, helper.GetPayStatus) + //The response should be: {"error":"order does not exist: sessionID mismatch"} +} + +func TestGetPayStatus_orderIDLXD(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "orderID": helper.TestOrderID + "abc", + "payMethod": helper.Stripe, + "user": helper.TestUser, + "sessionID": helper.TestSessionID, + // "TradeNO": "db27af04c65bd27bb3c3708addbafc01", + } + createPayTest(t, data, http.MethodGet, helper.GetPayStatus) + //The response should be: {"error":"order does not exist: order not found"} +} + +func TestGetPayStatus_payMethodLXD(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "orderID": helper.TestOrderID, + "payMethod": helper.Wechat, + "user": helper.TestUser, + "sessionID": helper.TestSessionID, + // "TradeNO": "db27af04c65bd27bb3c3708addbafc01", + } + createPayTest(t, data, http.MethodGet, helper.GetPayStatus) +} + +func TestGetPayStatus_userLXD(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "orderID": helper.TestOrderID, + "payMethod": helper.Wechat, + "user": helper.TestUser + "123", + "sessionID": helper.TestSessionID, + // "TradeNO": "db27af04c65bd27bb3c3708addbafc01", + } + createPayTest(t, data, http.MethodGet, helper.GetPayStatus) +} + +func TestGetBill(t *testing.T) { + data := map[string]interface{}{ + "appID": helper.TestAppID, + "sign": helper.TestSign, + "user": helper.TestUser, + } + createPayTest(t, data, http.MethodGet, helper.GetBill) +} + +func createPayTest(t *testing.T, data map[string]interface{}, httpMethod string, url string) { + // Create request body data + jsonData, err := json.Marshal(data) + if err != nil { + t.Fatal(err) + } + + // Create mock request and response objects + req, err := http.NewRequest(httpMethod, helper.LOCALHOST+helper.GROUP+url, bytes.NewBuffer(jsonData)) + if err != nil { + t.Fatal(err) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + + // Read response body + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + + // Print response body + fmt.Println(string(responseBody)) + + // Check response status code + if resp.StatusCode != http.StatusOK { + t.Errorf("Expected status code 200, but got %d", resp.StatusCode) + } + + // Close response body + defer resp.Body.Close() +} diff --git a/service/pay/router/router.go b/service/pay/router/router.go new file mode 100644 index 00000000000..b000412fc07 --- /dev/null +++ b/service/pay/router/router.go @@ -0,0 +1,70 @@ +package router + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "syscall" + + "github.com/gin-gonic/gin" + "github.com/labring/sealos/service/pay/api" + "github.com/labring/sealos/service/pay/helper" +) + +func RegisterPayRouter() { + router := gin.Default() + // Add logging middleware + // router.Use(conf.RequestLogger()) + // router.Use(conf.ResponseLogger()) + client := helper.InitMongoClient(os.Getenv(helper.DBURI)) + + payGroup := router.Group(helper.GROUP) + { + payGroup.PUT(helper.CreatePayMethod, func(c *gin.Context) { + api.CreatePayMethod(c, client) + }) + payGroup.PUT(helper.CreatePayApp, func(c *gin.Context) { + api.CreatePayApp(c, client) + }) + payGroup.GET(helper.GetAppDetails, func(c *gin.Context) { + api.GetAppDetails(c, client) + }) + payGroup.GET(helper.GetSession, func(c *gin.Context) { + api.GetSession(c, client) + }) + payGroup.GET(helper.GetPayStatus, func(c *gin.Context) { + api.GetPayStatus(c, client) + }) + payGroup.GET(helper.GetBill, func(c *gin.Context) { + api.GetBill(c, client) + }) + } + + // Create a buffered channel interrupt and use the signal. + interrupt := make(chan os.Signal, 1) + // Notify function to send the os Interrupt and SIGTERM signals to this channel + signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) + + // Start the HTTP server to listen on port 8080, accept the request, and process it + go func() { + err := router.Run(":2303") + fmt.Println("pay service is running on port 2303") + if err != nil { + log.Fatalf("Error running server: %v", err) + } + }() + + // Wait for interrupt signal + <-interrupt + + fmt.Println("pay service is shutting down") + // disconnect the MongoDB client + if err := client.Disconnect(context.Background()); err != nil { + log.Fatalf("Error disconnecting client: %v", err) + } + + // terminate procedure + os.Exit(0) +}