76 lines
1.8 KiB
Go
Raw Normal View History

2017-07-16 05:50:57 +00:00
package paypal
import (
"net/http"
"github.com/aerogo/aero"
2017-07-16 18:29:10 +00:00
"github.com/animenotifier/arn"
2017-07-17 01:14:05 +00:00
"github.com/animenotifier/notify.moe/utils"
2019-03-28 13:32:45 +00:00
paypalsdk "github.com/logpacker/PayPal-Go-SDK"
2017-07-16 05:50:57 +00:00
)
2018-02-24 09:29:20 +00:00
// CreatePayment creates the PayPal payment, typically via a JSON API route.
2017-07-16 05:50:57 +00:00
func CreatePayment(ctx *aero.Context) string {
2018-02-24 09:29:20 +00:00
// Make sure the user is logged in
2017-07-17 01:14:05 +00:00
user := utils.GetUser(ctx)
if user == nil {
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusUnauthorized, "Not logged in")
2017-07-17 01:14:05 +00:00
}
2018-02-24 09:29:20 +00:00
// Verify amount
2017-10-14 13:41:31 +00:00
amount, err := ctx.Request().Body().String()
if err != nil {
return ctx.Error(http.StatusBadRequest, "Could not read amount", err)
}
2017-10-05 10:36:26 +00:00
switch amount {
2018-03-04 18:26:15 +00:00
case "1000", "2000", "3000", "6000", "12000", "25000", "50000", "75000":
2017-10-05 10:36:26 +00:00
// OK
default:
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusBadRequest, "Incorrect amount")
2017-10-05 10:36:26 +00:00
}
// Initiate PayPal client
2017-07-16 18:29:10 +00:00
c, err := arn.PayPal()
2017-07-16 05:50:57 +00:00
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Could not initiate PayPal client", err)
}
2017-10-05 10:36:26 +00:00
// Get access token
2017-07-16 05:50:57 +00:00
_, err = c.GetAccessToken()
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Could not get PayPal access token", err)
}
2017-10-05 10:36:26 +00:00
// Create payment
2017-07-16 18:29:10 +00:00
p := paypalsdk.Payment{
Intent: "sale",
Payer: &paypalsdk.Payer{
PaymentMethod: "paypal",
},
Transactions: []paypalsdk.Transaction{paypalsdk.Transaction{
Amount: &paypalsdk.Amount{
2017-10-06 03:53:49 +00:00
Currency: "JPY",
Total: amount,
2017-07-16 18:29:10 +00:00
},
2017-07-17 01:14:05 +00:00
Description: "Top Up Balance",
2017-07-16 18:29:10 +00:00
}},
RedirectURLs: &paypalsdk.RedirectURLs{
ReturnURL: "https://" + ctx.App.Config.Domain + "/paypal/success",
CancelURL: "https://" + ctx.App.Config.Domain + "/paypal/cancel",
},
2017-07-16 05:50:57 +00:00
}
2017-07-16 18:29:10 +00:00
paymentResponse, err := c.CreatePayment(p)
2017-07-16 05:50:57 +00:00
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Could not create PayPal payment", err)
}
2017-07-16 18:29:10 +00:00
return ctx.JSON(paymentResponse)
2017-07-16 05:50:57 +00:00
}