A refund transaction.

See PayPal Developer documentation for more information.

Inheritance: PayPalRelationalObject
Exemple #1
8
 public Refund Refund(APIContext apiContext, Refund refund)
 {
     return Sale.Refund(apiContext, this.id, refund);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            paymentid = Request.Params["paymentid"];
            if (string.IsNullOrEmpty(paymentid)) {
                history = Payment.List(apiContext).payments;
            } else
            {
                var payment = Payment.Get(apiContext, paymentid);
                var transactions = payment.transactions.GetEnumerator();
                Sale sale = null;
                int total = 100; //fixed amount
                var invoiceNum = "";
                while (transactions.MoveNext())
                {
                    //total += Int32.Parse(transactions.Current.amount.total);
                    sale = transactions.Current.related_resources[0].sale; //It's dangerous
                    invoiceNum = transactions.Current.invoice_number;
                }

                var refund = new Refund()
                {
                    amount = new Amount()
                    {
                        currency = "USD",
                        total = total.ToString()
                    }
                };
                if (sale != null) {
                    var response = sale.Refund(apiContext, refund);
                    message = GetGlobalResourceObject("Resources", "msg3") + " " + invoiceNum + " " + GetGlobalResourceObject("Resources", "msg2");
                }
            }
        }
Exemple #3
0
        public void RefundIdTest()
        {
            try
            {
                var apiContext = TestingUtil.GetApiContext();
                this.RecordConnectionDetails();

                var pay = PaymentTest.CreatePaymentAuthorization(apiContext);
                this.RecordConnectionDetails();

                Assert.IsNotNull(pay);
                Assert.IsNotNull(pay.transactions);
                Assert.IsTrue(pay.transactions.Count > 0);
                var transaction = pay.transactions[0];

                Assert.IsNotNull(transaction.related_resources);
                Assert.IsTrue(transaction.related_resources.Count > 0);

                var resource = transaction.related_resources[0];
                Assert.IsNotNull(resource.authorization);

                var authorization = Authorization.Get(apiContext, resource.authorization.id);
                this.RecordConnectionDetails();

                var cap = new Capture
                {
                    amount = new Amount
                    {
                        total = "1",
                        currency = "USD"
                    }
                };
                var response = authorization.Capture(apiContext, cap);
                this.RecordConnectionDetails();

                var fund = new Refund
                {
                    amount = new Amount
                    {
                        total = "1",
                        currency = "USD"
                    }
                };

                apiContext.ResetRequestId();
                var responseRefund = response.Refund(apiContext, fund);
                this.RecordConnectionDetails();

                var retrievedRefund = Refund.Get(apiContext, responseRefund.id);
                this.RecordConnectionDetails();

                Assert.AreEqual(responseRefund.id, retrievedRefund.id);
            }
            catch(ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
Exemple #4
0
 public static Refund GetRefund()
 {
     var refund = new Refund();
     refund.capture_id = "101";
     refund.id = "102";
     refund.parent_payment = "103";
     refund.sale_id = "104";
     refund.state = "COMPLETED";
     refund.amount = AmountTest.GetAmount();
     refund.create_time = TestingUtil.GetCurrentDateISO(-1);
     refund.links = LinksTest.GetLinksList();
     return refund;
 }
Exemple #5
0
 public static Refund GetRefund()
 {
     var refund = new Refund();
     refund.capture_id = "101";
     refund.id = "102";
     refund.parent_payment = "103";
     refund.sale_id = "104";
     refund.state = "Approved";
     refund.amount = AmountTest.GetAmount();
     refund.create_time = "2013-01-17T18:12:02.347Z";
     refund.links = LinksTest.GetLinksList();
     return refund;
 }
        /// <summary>
        /// If admin approves refund, send request to paypal for 
        /// refund and mark that refund as Approved
        /// </summary>
        /// <param name="id">id of refund</param>
        /// <returns></returns>
        public ActionResult Approve(int id)
        {
            var apiContext = GetApiContext();
            if (apiContext == null)
                return new HttpStatusCodeResult(HttpStatusCode.NotAcceptable);

            var refundPayment = db.Refunds.Find(id);

            if (refundPayment == null)
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var cart = db.Carts.Where(x => x.PaymentId == refundPayment.PaymentId).SingleOrDefault();
            
            try
            {
                var payment = Payment.Get(apiContext, refundPayment.PaymentId);  //find payment with selected paymenId

                var sale = payment.transactions[0].related_resources[0].sale;

                var refund = new Refund()  //create new refund to be sent to paypal
                {
                    sale_id = refundPayment.PaymentId,
                    amount = new Amount()
                    {
                        currency = "USD",
                        total = cart.TotalPrice.ToString()
                    }
                };
                var response = sale.Refund(apiContext, refund);  //send request for refund

                refundPayment.Finished = "Approved";
                cart.Purchased = "Refunded";
               
                MailBuilder(cart.ApplicationUserId, refundPayment.Finished,cart.PaymentId);
                
                db.SaveChanges();
                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }
            catch
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }

        }
Exemple #7
0
        public void SaleRefundTest()
        {
            try
            {
                var apiContext = TestingUtil.GetApiContext();
                this.RecordConnectionDetails();

                // Create a credit card sale payment
                var payment = PaymentTest.CreatePaymentForSale(apiContext);
                this.RecordConnectionDetails();

                // Get the sale resource
                var sale = payment.transactions[0].related_resources[0].sale;

                var refund = new Refund
                {
                    amount = new Amount
                    {
                        currency = "USD",
                        total = "0.01"
                    }
                };

                apiContext.ResetRequestId();
                var response = sale.Refund(apiContext, refund);
                this.RecordConnectionDetails();

                Assert.IsNotNull(response);
                Assert.AreEqual("completed", response.state);
            }
            catch(ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
 /// <summary>
 /// Creates (and processes) a new Refund Transaction added as a related resource.
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <param name="refund">Refund</param>
 /// <returns>Refund</returns>
 public Refund Refund(APIContext apiContext, Refund refund)
 {
     return(Capture.Refund(apiContext, this.id, refund));
 }
Exemple #9
0
        public static Refund Refund(APIContext apiContext, string saleId, Refund refund)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);
            ArgumentValidator.Validate(saleId, "saleId");
            ArgumentValidator.Validate(refund, "refund");

            // Configure and send the request
            var pattern = "v1/payments/sale/{0}/refund";
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { saleId });
            return PayPalResource.ConfigureAndExecute<Refund>(apiContext, HttpMethod.POST, resourcePath, refund.ConvertToJson());
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                // ###Redirect URLS
                // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/SaleRefund.aspx?";
                var guid = Convert.ToString((new Random()).Next(100000));
                var redirectUrl = baseURI + "guid=" + guid;

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                var payment = new Payment
                {
                    intent = "sale",
                    payer = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions = new List<Transaction>
                    {
                        new Transaction
                        {
                            description = "Transaction description.",
                            invoice_number = Common.GetRandomInvoiceNumber(),
                            amount = new Amount
                            {
                                currency = "USD",
                                total = "100.00",
                                details = new Details
                                {
                                    tax = "15",
                                    shipping = "10",
                                    subtotal = "75"
                                }
                            },
                            item_list = new ItemList
                            {
                                items = new List<Item>
                                {
                                    new Item
                                    {
                                        name = "Item Name",
                                        currency = "USD",
                                        price = "15",
                                        quantity = "5",
                                        sku = "sku"
                                    }
                                }
                            }
                        }
                    },
                    redirect_urls = new RedirectUrls
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    }
                };

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create PayPal payment", payment);
                #endregion

                // Create a payment using a valid APIContext
                var createdPayment = payment.Create(apiContext);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdPayment);
                #endregion

                // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                var links = createdPayment.links.GetEnumerator();
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
                    }
                }
                Session.Add(guid, createdPayment.id);
                Session.Add("flow-" + guid, this.flow);
            }
            else
            {
                var guid = Request.Params["guid"];

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow = Session["flow-" + guid] as RequestFlow;
                this.RegisterSampleRequestFlow();
                this.flow.RecordApproval("PayPal payment approved successfully.");
                #endregion

                // Using the information from the redirect, setup the payment to execute.
                var paymentId = Session[guid] as string;
                var paymentExecution = new PaymentExecution() { payer_id = payerId };
                var payment = new Payment() { id = paymentId };

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Execute PayPal payment", payment);
                #endregion

                // Execute the payment.
                var executedPayment = payment.Execute(apiContext, paymentExecution);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(executedPayment);
                #endregion

                // A refund transaction. Use the amount to create a refund object
                var refund = new Refund()
                {
                    amount = new Amount()
                    {
                        currency = "USD",
                        total = "100.00"
                    }
                };

                // Get the sale resource from the executed payment's list of related resources.
                var sale = executedPayment.transactions[0].related_resources[0].sale;

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Refund sale", refund, string.Format("URI: /v1/payments/sale/{0}/refund", sale.id));
                #endregion
            
                // Refund by posting Refund object using a valid APIContext
                var response = sale.Refund(apiContext, refund);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(response);
                #endregion

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Get the details of the payment", description: "ID: " + executedPayment.id);
                #endregion

                var retrievedPayment = Payment.Get(apiContext, executedPayment.id);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(retrievedPayment);
                #endregion

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // ###Payment
            // A Payment Resource; create one with its intent set to `sale`, `authorize`, or `order`
            var payment = new Payment()
            {
                intent = "authorize",
                // A resource representing a Payer that funds a payment. Use the List of `FundingInstrument` and the Payment Method as 'credit_card'
                payer = new Payer()
                {
                    // The Payment creation API requires a list of
                    // FundingInstrument; add the created `FundingInstrument`
                    // to a List
                    funding_instruments = new List<FundingInstrument>() 
                    {
                        // A resource representing a Payeer's funding instrument.
                        // Use a Payer ID (A unique identifier of the payer generated
                        // and provided by the facilitator. This is required when
                        // creating or using a tokenized funding instrument)
                        // and the `CreditCardDetails`
                        new FundingInstrument()
                        {
                            // A resource representing a credit card that can be used to fund a payment.
                            credit_card = new CreditCard()
                            {
                                billing_address = new Address()
                                {
                                    city = "Johnstown",
                                    country_code = "US",
                                    line1 = "52 N Main ST",
                                    postal_code = "43210",
                                    state = "OH"
                                },
                                cvv2 = "874",
                                expire_month = 11,
                                expire_year = 2018,
                                first_name = "Joe",
                                last_name = "Shopper",
                                number = "4877274905927862",
                                type = "visa"
                            }
                        }
                    },
                    payment_method = "credit_card"
                },
                // The Payment creation API requires a list of transactions; add the created `Transaction` to a List
                transactions = new List<Transaction>()
                {
                    // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it. Transaction is created with a `Payee` and `Amount` types
                    new Transaction()
                    {
                        // Let's you specify a payment amount.
                        amount = new Amount()
                        {
                            currency = "USD",
                            // Total must be equal to sum of shipping, tax and subtotal.
                            total = "107.47",
                            details = new Details()
                            {
                                shipping = "0.03",
                                subtotal = "107.41",
                                tax = "0.03"
                            }
                        },
                        description = "This is the payment transaction description."
                    }
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest(title: "Create authorization for credit card payment", requestObject: payment);
            #endregion

            // Create a payment by posting to the APIService
            // using a valid APIContext
            var createdPayment = payment.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(createdPayment);
            #endregion

            // ###Authorization
            // Once the payment with intent set to `authorize` has been created, retrieve its authorization object.
            var authorization = createdPayment.transactions[0].related_resources[0].authorization;

            // ###Capture
            // Create a Capture object by doing a capture on Authorization object.
            var capture = new Capture()
            {
                is_final_capture = true,
                amount = new Amount()
                {
                    currency = "USD",
                    total = "1.00"
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Capture authorized payment", capture, string.Format("URI: v1/payments/authorization/{0}/capture", authorization.id));
            #endregion

            // Capture by POSTing to
            // URI v1/payments/authorization/{authorization_id}/capture
            var responseCapture = authorization.Capture(apiContext, capture);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(responseCapture);
            #endregion

            // ###Refund
            // Create a Refund object
            var refund = new Refund()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    total = "0.50"
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Capture refund", refund, "ID: " + responseCapture.id);
            #endregion

            // Do a Refund by POSTing to 
            // URI v1/payments/capture/{capture_id}/refund
            var response = responseCapture.Refund(Configuration.GetAPIContext(), refund);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(response);
            #endregion

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Exemple #12
0
        public IHttpActionResult RefundPayment(string cartId)
        {
            var cart = db.Carts.Find(Int32.Parse(cartId));

            if (cart == null)
                return NotFound();            
            if (cart.TimeOfPurchase.AddDays(7) > DateTime.Now)  //if coupons have been purchased in last 7 
            {                                                   //days then make refund

                if (cart.PaymentId == string.Empty)
                    MakeRefund(cart.Id);

                var apiContext = GetApiContext();

                if (apiContext == null)
                    return StatusCode(HttpStatusCode.NotAcceptable);

                try
                {
                    var payment = Payment.Get(apiContext, cart.PaymentId);  //find payment with selected paymenId

                    var sale = payment.transactions[0].related_resources[0].sale;


                    var refund = new Refund()  //create new refund to be sent to paypal
                    {
                        sale_id = cart.PaymentId,
                        amount = new Amount()
                        {
                            currency = "USD",
                            total = cart.TotalPrice.ToString()
                        }
                    };
                    var response = sale.Refund(apiContext, refund);  //send request for refund

                    var paypalRefund = new PayPalRefund()  //new object refund in our database to be saved
                    {
                        ApplicationUserId = cart.ApplicationUserId,
                        Option = "Automatic Refund Done in 7 Days",
                        Content = "",
                        PaymentId = cart.PaymentId,
                        Finished = "Approved",
                        CartId = cart.Id
                    };

                    cart.Purchased = "Refunded";  //set cart state to Refunded


                    db.Refunds.Add(paypalRefund);
                    db.SaveChanges();
                    Mail mail = db.Mails.Where(x => x.Subject == "Refound").First();
                    MailBulider(cart.ApplicationUserId, cart.Id, mail, paypalRefund.Finished, cart.PaymentId);
                    MakeRefund(cart.Id);
                    return Ok();
                }
                catch
                {
                    return NotFound();
                }
            }
            return BadRequest(cart.Id.ToString() + "," + cart.PaymentId); //if it has passed more then 7 days, user has to 
        }                                   //send request to admin to approve him/her refund