Swiftpack.co - Package - Buratti/VaporPayPal

VaporPayPal

Will update for Vapor 3 soon.

Swift Build Status Code Coverage

Add VaporPayPal to your Package.swift

dependencies: [
    .Package(url: "https://github.com/Buratti/VaporPayPal.git", majorVersion: 0, minor: 1)
]
import Vapor
import HTTP
import VaporPayPal

class PayPalController {
    
    let clientId = "YOUR_CLIENT_ID"
    let clientSecret = "YOUR_CLIENT_SECRET"
    
    func getApprovalUrl(request: Request) throws -> ResponseRepresentable {
        let paypal = VaporPayPal(clientId: clientId, clientSecret: clientSecret, mode: .sandbox)
        let payment = VaporPayPalPayment()
        let amount = VaporPayPalAmount(15.0, .usd)
        let transaction = VaporPayPalTransaction(amount: amount)
        
        payment.redirectUrls.returnUrl = "http://localhost:8080/return"
        payment.redirectUrls.cancelUrl = "http://localhost:8080/cancel"
        payment.transactions.append(transaction)
        
        try paypal.create(payment)
        guard let approvalUrl = payment.approvalUrl else {
            throw Abort.serverError
        }
        
        // Redirect the user to PayPal
        return Response(redirect: approvalUrl)
    }
    
    /// The user will be redirected here if he confirms the payment
    func executePayment(request: Request) throws -> ResponseRepresentable {
        guard let paymentId = request.query?["paymentId"]?.string,
            let payerId = request.query?["PayerID"]?.string else {
                throw Abort.badRequest
        }
        
        let payment = VaporPayPalPayment(id: paymentId)
        let execution = VaporPayPalPaymentExecution(payerId: payerId)
        
        let paypal = VaporPayPal(clientId: clientId, clientSecret: clientSecret, mode: .sandbox)
        try paypal.execute(payment, execution)
        
        guard payment.state == .approved else {
            throw Abort.custom(status: .unprocessableEntity, message: "This payment was not approved")
        }
        
        return "Successful payment! 💰"
    }
    
    /// The user will be redirected here if he cancels the payment
    func cancelPayment(request: Request) throws -> ResponseRepresentable {
        return "Payment canceled 😓"
    }
}

let drop = Droplet()
let paypalController = PayPalController()

drop.get("paypal", handler: paypalController.getApprovalUrl)
drop.get("return", handler: paypalController.executePayment)
drop.get("cancel", handler: paypalController.cancelPayment)

drop.run()

Github

link
Stars: 10
Help us keep the lights on

Dependencies

Used By

Total: 0

Releases

v0.1.0 - Mar 30, 2017