Added sangha-wide config/logger/command framework to paypal processor

parent ca7bca47
package main
import (
"fmt"
"math/big"
"os"
"github.com/davecgh/go-spew/spew"
"github.com/kr/pretty"
"github.com/logpacker/PayPal-Go-SDK"
"github.com/spf13/cobra"
"gitlab.techcultivation.org/sangha/mq"
"gitlab.techcultivation.org/sangha/sangha/config"
)
var (
fetchCmd = &cobra.Command{
Use: "fetch",
Short: "fetch new payments",
Long: `The fetch command retrieves all new incoming payments from PayPal`,
RunE: func(cmd *cobra.Command, args []string) error {
return executeFetch()
},
}
)
func executeFetch() error {
// Create a client instance
c, err := paypalsdk.NewClient(config.Settings.PaymentProviders.PayPal.ClientID,
config.Settings.PaymentProviders.PayPal.Secret,
paypalsdk.APIBaseSandBox)
if err != nil {
panic(err)
}
logf, err := os.Create("./log/paypal.log")
if err != nil {
panic(err)
}
defer logf.Close()
c.SetLog(logf)
_, err = c.GetAccessToken()
if err != nil {
panic(err)
}
payments, err := c.GetPayments()
if err != nil {
panic(err)
}
for _, payment := range payments {
if len(payment.Transactions) == 0 {
spew.Dump(payment)
panic("No transactions found for payment!")
}
if len(payment.Transactions) > 1 {
spew.Dump(payment)
panic("Too many transactions found for payment!")
}
value, ab, err := big.ParseFloat(payment.Transactions[0].Amount.Total, 10, 2, big.ToNearestEven)
if err != nil {
spew.Dump(payment)
panic("Can't parse value of this transaction")
}
if ab != 10 {
spew.Dump(payment)
panic("Actual base of transaction value is not 10")
}
valuei, _ := value.Int64()
// spew.Dump(payment)
p := mq.Payment{
Name: fmt.Sprintf("%s %s", payment.Payer.PayerInfo.FirstName, payment.Payer.PayerInfo.LastName),
Address: []string{
payment.Payer.PayerInfo.ShippingAddress.RecipientName,
payment.Payer.PayerInfo.ShippingAddress.Line1,
},
City: payment.Payer.PayerInfo.ShippingAddress.City,
ZIP: payment.Payer.PayerInfo.ShippingAddress.PostalCode,
Country: payment.Payer.PayerInfo.ShippingAddress.CountryCode,
Phone: payment.Payer.PayerInfo.Phone,
Email: payment.Payer.PayerInfo.Email,
DateTime: *payment.Transactions[0].RelatedResources[0].Sale.CreateTime,
Amount: valuei * 100, // in smallest currency unit
AmountS: payment.Transactions[0].Amount.Total,
Currency: payment.Transactions[0].Amount.Currency,
TransactionCode: payment.Transactions[0].Custom,
Description: payment.Transactions[0].Description,
Source: "paypal",
SourceID: payment.ID,
SourcePayerID: payment.Payer.PayerInfo.PayerID,
SourceTransactionID: payment.Transactions[0].RelatedResources[0].Sale.ID,
}
/* ac := accounting.Accounting{Symbol: "E", Precision: 2}
fmt.Println(ac.FormatMoneyBigFloat(p.Value)) */
pretty.Println(p)
err = p.Process()
if err != nil {
panic(err)
}
}
return nil
}
func init() {
RootCmd.AddCommand(fetchCmd)
}
package main
import (
"fmt"
"math/big"
"net/http"
"os"
"os/signal"
"github.com/davecgh/go-spew/spew"
swagger "github.com/emicklei/go-restful-swagger12"
"github.com/kr/pretty"
"github.com/logpacker/PayPal-Go-SDK"
"github.com/muesli/smolder"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gitlab.techcultivation.org/sangha/mq"
"gitlab.techcultivation.org/sangha/payment-processors/paypal/resources/payments"
"gitlab.techcultivation.org/sangha/sangha/config"
"gitlab.techcultivation.org/sangha/sangha/db"
"gitlab.techcultivation.org/sangha/sangha/logger"
)
func handleSignals() (chan int, bool) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, os.Kill)
shutdownGracefully := false
requestIncChan := make(chan int)
go func() {
boldGreen := string(byte(27)) + "[1;32m"
boldRed := string(byte(27)) + "[1;31m"
boldEnd := string(byte(27)) + "[0m"
pendingRequests := 0
for {
select {
case sig := <-sigChan:
if !shutdownGracefully {
shutdownGracefully = true
fmt.Printf(boldGreen+"\nGot %s signal, shutting down gracefully. Press Ctrl-C again to stop now.\n\n"+boldEnd, sig.String())
if pendingRequests == 0 {
os.Exit(0)
}
} else {
fmt.Printf(boldRed+"\nGot %s signal, shutting down now!\n\n"+boldEnd, sig.String())
os.Exit(0)
}
case inc := <-requestIncChan:
pendingRequests += inc
if shutdownGracefully {
log.Infoln("Pending requests:", pendingRequests)
if pendingRequests == 0 {
os.Exit(0)
}
}
}
}
}()
return requestIncChan, shutdownGracefully
}
func paypal() {
// Create a client instance
c, err := paypalsdk.NewClient(config.Settings.PaymentProviders.PayPal.ClientID,
config.Settings.PaymentProviders.PayPal.Secret,
paypalsdk.APIBaseSandBox)
if err != nil {
panic(err)
var (
// RootCmd is the core command used for cli-arg parsing
RootCmd = &cobra.Command{
Use: "paypal",
Short: "paypal processor",
Long: "paypal processor is the PayPal processor of the sangha framework\n" +
"Complete documentation is available at https://gitlab.techcultivation.org/sangha/sangha",
SilenceErrors: false,
SilenceUsage: true,
}
)
logf, err := os.Create("./log/paypal.log")
if err != nil {
panic(err)
}
defer logf.Close()
c.SetLog(logf)
_, err = c.GetAccessToken()
if err != nil {
panic(err)
}
func main() {
var configFile, logLevelStr string
RootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "config.json", "use this config file (JSON format)")
RootCmd.PersistentFlags().StringVarP(&logLevelStr, "loglevel", "l", "info", "log level")
payments, err := c.GetPayments()
logLevel, err := log.ParseLevel(logLevelStr)
if err != nil {
panic(err)
}
for _, payment := range payments {
if len(payment.Transactions) == 0 {
spew.Dump(payment)
panic("No transactions found for payment!")
}
if len(payment.Transactions) > 1 {
spew.Dump(payment)
panic("Too many transactions found for payment!")
}
value, ab, err := big.ParseFloat(payment.Transactions[0].Amount.Total, 10, 2, big.ToNearestEven)
if err != nil {
spew.Dump(payment)
panic("Can't parse value of this transaction")
}
if ab != 10 {
spew.Dump(payment)
panic("Actual base of transaction value is not 10")
}
valuei, _ := value.Int64()
// spew.Dump(payment)
p := mq.Payment{
Name: fmt.Sprintf("%s %s", payment.Payer.PayerInfo.FirstName, payment.Payer.PayerInfo.LastName),
Address: []string{
payment.Payer.PayerInfo.ShippingAddress.RecipientName,
payment.Payer.PayerInfo.ShippingAddress.Line1,
},
City: payment.Payer.PayerInfo.ShippingAddress.City,
ZIP: payment.Payer.PayerInfo.ShippingAddress.PostalCode,
Country: payment.Payer.PayerInfo.ShippingAddress.CountryCode,
Phone: payment.Payer.PayerInfo.Phone,
Email: payment.Payer.PayerInfo.Email,
DateTime: *payment.Transactions[0].RelatedResources[0].Sale.CreateTime,
Amount: valuei * 100, // in smallest currency unit
AmountS: payment.Transactions[0].Amount.Total,
Currency: payment.Transactions[0].Amount.Currency,
TransactionCode: payment.Transactions[0].Custom,
Description: payment.Transactions[0].Description,
Source: "paypal",
SourceID: payment.ID,
SourcePayerID: payment.Payer.PayerInfo.PayerID,
SourceTransactionID: payment.Transactions[0].RelatedResources[0].Sale.ID,
}
/* ac := accounting.Accounting{Symbol: "E", Precision: 2}
fmt.Println(ac.FormatMoneyBigFloat(p.Value)) */
pretty.Println(p)
err = p.Process()
if err != nil {
panic(err)
}
log.Fatal(err)
}
}
log.SetLevel(logLevel)
func main() {
ch, shutdownGracefully := handleSignals()
config.ParseSettings()
config.ParseSettings(configFile)
logger.SetupLogger(config.Settings.Connections.Logger.Protocol,
config.Settings.Connections.Logger.Address,
"paypal-processor")
......@@ -162,37 +45,7 @@ func main() {
db.SetupPostgres(config.Settings.Connections.PostgreSQL)
mq.SetupAMQP(config.Settings.Connections.AMQP)
context := &db.APIContext{
Config: *config.Settings,
}
// Setup web-service
smolderConfig := smolder.APIConfig{
BaseURL: config.Settings.API.BaseURL,
PathPrefix: config.Settings.API.PathPrefix,
if err := RootCmd.Execute(); err != nil {
os.Exit(-1)
}
wsContainer := smolder.NewSmolderContainer(smolderConfig, &shutdownGracefully, ch)
func(resources ...smolder.APIResource) {
for _, r := range resources {
r.Register(wsContainer, smolderConfig, context)
}
}(
&payments.PaymentResource{},
)
if config.Settings.API.SwaggerFilePath != "" {
wsConfig := swagger.Config{
WebServices: wsContainer.RegisteredWebServices(),
WebServicesUrl: config.Settings.API.BaseURL,
ApiPath: config.Settings.API.SwaggerAPIPath,
SwaggerPath: config.Settings.API.SwaggerPath,
SwaggerFilePath: config.Settings.API.SwaggerFilePath,
}
swagger.RegisterSwaggerService(wsConfig, wsContainer)
}
// GlobalLog("Starting web-api...")
server := &http.Server{Addr: config.Settings.API.Bind, Handler: wsContainer}
log.Fatal(server.ListenAndServe())
}
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
swagger "github.com/emicklei/go-restful-swagger12"
"github.com/muesli/smolder"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gitlab.techcultivation.org/sangha/payment-processors/paypal/resources/payments"
"gitlab.techcultivation.org/sangha/sangha/config"
"gitlab.techcultivation.org/sangha/sangha/db"
)
var (
serveCmd = &cobra.Command{
Use: "serve",
Short: "start the API and serve",
Long: `The serve command starts the API`,
RunE: func(cmd *cobra.Command, args []string) error {
return executeServe()
},
}
)
func executeServe() error {
ch, shutdownGracefully := handleSignals()
context := &db.APIContext{
Config: *config.Settings,
}
// Setup web-service
smolderConfig := smolder.APIConfig{
BaseURL: config.Settings.API.BaseURL,
PathPrefix: config.Settings.API.PathPrefix,
}
wsContainer := smolder.NewSmolderContainer(smolderConfig, &shutdownGracefully, ch)
func(resources ...smolder.APIResource) {
for _, r := range resources {
r.Register(wsContainer, smolderConfig, context)
}
}(
&payments.PaymentResource{},
)
if config.Settings.API.SwaggerFilePath != "" {
wsConfig := swagger.Config{
WebServices: wsContainer.RegisteredWebServices(),
WebServicesUrl: config.Settings.API.BaseURL,
ApiPath: config.Settings.API.SwaggerAPIPath,
SwaggerPath: config.Settings.API.SwaggerPath,
SwaggerFilePath: config.Settings.API.SwaggerFilePath,
}
swagger.RegisterSwaggerService(wsConfig, wsContainer)
}
// GlobalLog("Starting web-api...")
server := &http.Server{Addr: config.Settings.API.Bind, Handler: wsContainer}
log.Fatal(server.ListenAndServe())
return nil
}
func handleSignals() (chan int, bool) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, os.Kill)
shutdownGracefully := false
requestIncChan := make(chan int)
go func() {
boldGreen := string(byte(27)) + "[1;32m"
boldRed := string(byte(27)) + "[1;31m"
boldEnd := string(byte(27)) + "[0m"
pendingRequests := 0
for {
select {
case sig := <-sigChan:
if !shutdownGracefully {
shutdownGracefully = true
fmt.Printf(boldGreen+"\nGot %s signal, shutting down gracefully. Press Ctrl-C again to stop now.\n\n"+boldEnd, sig.String())
if pendingRequests == 0 {
os.Exit(0)
}
} else {
fmt.Printf(boldRed+"\nGot %s signal, shutting down now!\n\n"+boldEnd, sig.String())
os.Exit(0)
}
case inc := <-requestIncChan:
pendingRequests += inc
if shutdownGracefully {
log.Infoln("Pending requests:", pendingRequests)
if pendingRequests == 0 {
os.Exit(0)
}
}
}
}
}()
return requestIncChan, shutdownGracefully
}
func init() {
RootCmd.AddCommand(serveCmd)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment